input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
import unittest
import sys
from term import py_codec_impl as py_impl
import term.native_codec_impl as native_impl
from term.atom import Atom, StrictAtom
from term.pid import Pid
from term.reference import Reference
from term.fun import Fun
from term.list import list_to_unicode_str
class TestETFDecode(unittest.TestCase):
# Sentinel used to verify that post-decoded tails are preserved properly
EXPECTED_TAIL_BYTES = bytes([1, 2, 3, 4, 5])
def _etf_bytes(self, b):
return bytes(b) + self.EXPECTED_TAIL_BYTES
def assertExpectedTail(self, tail):
self.assertEqual(tail, self.EXPECTED_TAIL_BYTES)
def test_decode_atom_py(self):
self._decode_atom(py_impl)
self._decode_atom_utf8(py_impl)
def test_decode_atom_native(self):
self._decode_atom(native_impl)
self._decode_atom_utf8(native_impl)
def _decode_atom(self, codec):
""" Try an atom 'hello' encoded as Latin1 atom (16-bit length)
or small atom (8bit length)
"""
b1 = self._etf_bytes([131, py_impl.TAG_ATOM_EXT,
0, 5,
104, 101, 108, 108, 111])
(t1, tail1) = codec.binary_to_term(b1, None)
self.assertTrue(isinstance(t1, Atom), "Result must be Atom object")
self.assertEqual(t1, "hello")
self.assertExpectedTail(tail1)
b2 = self._etf_bytes([131, py_impl.TAG_SMALL_ATOM_EXT,
5,
104, 101, 108, 108, 111])
(t2, tail2) = codec.binary_to_term(b2, None)
self.assertTrue(isinstance(t2, Atom), "Result must be Atom object")
self.assertEqual(t2, "hello")
self.assertExpectedTail(tail2)
def _decode_atom_utf8(self, codec):
b1 = self._etf_bytes([131, py_impl.TAG_ATOM_UTF8_EXT,
0, 6,
108, 195, 164, 103, 101, 116])
(t1, tail1) = codec.binary_to_term(b1, None)
self.assertTrue(isinstance(t1, Atom), "Result must be Atom object")
self.assertTrue(isinstance(t1, str), "Result must be str")
self.assertEqual(t1, u"läget")
self.assertExpectedTail(tail1)
# ----------------
def test_decode_atom_as_string_py(self):
self._decode_atom_as_string(py_impl)
def test_decode_atom_as_string_native(self):
self._decode_atom_as_string(native_impl)
def _decode_atom_as_string(self, codec):
""" Try an atom 'hello' to a Python string """
b1 = self._etf_bytes([131, py_impl.TAG_ATOM_EXT,
0, 5,
104, 101, 108, 108, 111])
(t2, tail2) = codec.binary_to_term(b1, {"atom": "str"})
self.assertTrue(isinstance(t2, str),
"Expected str, have: " + t2.__class__.__name__)
self.assertEqual(t2, "hello")
self.assertExpectedTail(tail2)
(t3, tail3) = codec.binary_to_term(b1, {"atom": "bytes"})
self.assertTrue(isinstance(t3, bytes),
"Expected bytes, have: " + t3.__class__.__name__)
self.assertEqual(t3, b'hello')
self.assertExpectedTail(tail3)
# ----------------
def test_decode_atom_as_strict_py(self):
self._decode_atom_as_strict(py_impl)
def test_decode_atom_as_strict_native(self):
self._decode_atom_as_strict(native_impl)
def _decode_atom_as_strict(self, codec):
b1 = self._etf_bytes([131, py_impl.TAG_ATOM_EXT,
0, 5,
104, 101, 108, 108, 111])
(t1, tail1) = codec.binary_to_term(b1, {"atom": "StrictAtom"})
self.assertTrue(isinstance(t1, StrictAtom), "Result must be StrictAtom "
"got {}".format(type(t1)))
self.assertEqual(t1, "hello")
self.assertExpectedTail(tail1)
b2 = self._etf_bytes([131, py_impl.TAG_SMALL_ATOM_EXT,
5,
104, 101, 108, 108, 111])
(t2, tail2) = codec.binary_to_term(b2, {"atom": "StrictAtom"})
self.assertTrue(isinstance(t2, StrictAtom), "Result must be Atom "
"object")
self.assertEqual(t2, "hello")
self.assertExpectedTail(tail2)
# ----------------
def test_decode_atom_custom_callable_py(self):
self._decode_atom_custom_callable(py_impl)
self._decode_atom_custom_class(py_impl)
def test_decode_atom_custom_callable_native(self):
self._decode_atom_custom_callable(native_impl)
self._decode_atom_custom_class(native_impl)
def _decode_atom_custom_callable(self, codec):
b1 = self._etf_bytes([131, py_impl.TAG_ATOM_EXT,
0, 5,
104, 101, 108, 108, 111])
a_fun = lambda x: bytes(x.encode('utf8'))
(t1, tail1) = codec.binary_to_term(b1, {"atom_call": a_fun})
self.assertTrue(isinstance(t1, bytes))
self.assertEqual(t1, b"hello")
self.assertExpectedTail(tail1)
def _decode_atom_custom_class(self, codec):
b1 = self._etf_bytes([131, py_impl.TAG_ATOM_EXT,
0, 5,
104, 101, 108, 108, 111])
class A(str):
pass
class B:
def __init__(self, text):
self._text = text
(t1, tail1) = codec.binary_to_term(b1, {"atom_call": str})
self.assertTrue(isinstance(t1, str))
self.assertEqual(t1, "hello")
self.assertExpectedTail(tail1)
(t2, tail2) = codec.binary_to_term(b1, {"atom_call": A})
self.assertTrue(isinstance(t2, str))
self.assertTrue(isinstance(t2, A))
self.assertEqual(t2, "hello")
self.assertExpectedTail(tail2)
(t3, tail3) = codec.binary_to_term(b1, {"atom_call": B})
self.assertTrue(isinstance(t3, B))
self.assertEqual(t3._text, "hello")
self.assertExpectedTail(tail3)
# ----------------
def test_ref_count_leak_on_custom_atom(self):
b = self._etf_bytes([131, py_impl.TAG_ATOM_EXT,
0, 5,
104, 101, 108, 108, 111])
def test_fun(codec, b_data):
class A(str):
pass
return codec.binary_to_term(b_data, {'atom_call': A})
for i in range(10):
p_res, p_tail = test_fun(py_impl, b)
n_res, n_tail = test_fun(native_impl, b)
p_type = type(p_res)
p_type_refs = sys.getrefcount(p_type)
n_type = type(n_res)
n_type_refs = sys.getrefcount(n_type)
self.assertEqual(p_res, n_res)
self.assertEqual(p_tail, n_tail)
self.assertNotEqual(p_type, n_type)
self.assertEqual(p_type_refs, n_type_refs)
# ----------------
def test_decode_str_py(self):
self._decode_str_ascii(py_impl)
self._decode_str_unicode(py_impl)
self._decode_str_int_list(py_impl)
def test_decode_str_native(self):
self._decode_str_ascii(native_impl)
self._decode_str_unicode(native_impl)
self._decode_str_int_list(py_impl)
def _decode_str_ascii(self, codec):
""" A string with bytes, encoded as optimized byte array. """
b1 = self._etf_bytes([131, py_impl.TAG_STRING_EXT,
0, 5,
104, 101, 108, 108, 111])
(t1, tail1) = codec.binary_to_term(b1, None)
self.assertTrue(isinstance(t1, str), "Result must be str")
self.assertEqual(t1, "hello")
self.assertExpectedTail(tail1)
(t2, tail2) = codec.binary_to_term(b1, {"byte_string": "bytes"})
self.assertTrue(isinstance(t2, bytes),
"Result must be bytes, got " + t2.__class__.__name__)
self.assertEqual(t2, b"hello")
self.assertExpectedTail(tail2)
def _decode_str_int_list(self, codec):
""" A string with bytes, encoded as optimized byte array. """
b1 = self._etf_bytes([131, py_impl.TAG_STRING_EXT,
0, 5,
104, 101, 108, 108, 111])
(t1, tail1) = codec.binary_to_term(b1, {"byte_string": "int_list"})
self.assertEqual(t1, [104, 101, 108, 108, 111])
self.assertExpectedTail(tail1)
def _decode_str_unicode(self, codec):
""" A string with emoji, encoded as a list of unicode integers. """
b1 = self._etf_bytes([
131, py_impl.TAG_LIST_EXT,
0, 0, 0, 3, # length
py_impl.TAG_INT, 0, 0, 38, 34, # 32-bit radiation hazard
py_impl.TAG_SMALL_INT, 32, # 8-bit space (32)
py_impl.TAG_INT, 0, 0, 38, 35, # 32-bit bio-hazard
py_impl.TAG_NIL_EXT # list tail: NIL
])
(t1, tail) = codec.binary_to_term(b1, None)
self.assertTrue(isinstance(t1, list), "Result must be a list")
self.assertEqual(list_to_unicode_str(t1), u"☢ ☣")
self.assertExpectedTail(tail)
# ----------------
def test_decode_pid_py(self):
self._decode_pid(py_impl)
def test_decode_pid_native(self):
self._decode_pid(native_impl)
def _decode_pid(self, codec):
""" Try a pid """
data = self._etf_bytes([
131, 103, 100, 0, 13, 101, 114, 108, 64, 49, 50, 55, 46,
48, 46, 48, 46, 49, 0, 0, 0, 64, 0, 0, 0, 0, 1
])
(val, tail) = codec.binary_to_term(data, None)
self.assertTrue(isinstance(val, Pid))
self.assertExpectedTail(tail)
# ----------------
def test_decode_new_pid_py(self):
self._decode_new_pid(py_impl)
def test_decode_new_pid_native(self):
self._decode_new_pid(native_impl)
def _decode_new_pid(self, codec):
""" Try a new pid """
data = self._etf_bytes([
131, 88, 100, 0, 13, 101, 114, 108, 64, 49, 50, 55, 46,
48, 46, 48, 46, 49, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 1
])
(val, tail) = codec.binary_to_term(data, None)
self.assertTrue(isinstance(val, Pid))
self.assertExpectedTail(tail)
# ----------------
def test_decode_ref_py(self):
self._decode_ref(py_impl)
def test_decode_ref_native(self):
self._decode_ref(native_impl)
def _decode_ref(self, codec):
""" Try a reference """
b1 = self._etf_bytes([
131, 114, 0, 3, 100, 0, 13, 101, 114, 108, 64, 49, 50,
55, 46, 48, 46, 48, 46, 49, 1, 0, 0, 1, 58, 0, 0, 0, 2,
0, 0, 0, 0
])
(t1, tail) = codec.binary_to_term(b1, None)
self.assertTrue(isinstance(t1, Reference))
self.assertExpectedTail(tail)
# ----------------
def test_decode_newer_ref_py(self):
self._decode_newer_ref(py_impl)
def test_decode_newer_ref_native(self):
self._decode_newer_ref(native_impl)
def _decode_newer_ref(self, codec):
""" Try a newer reference """
b1 = self._etf_bytes([
131, 90, 0, 3, 100, 0, 13, 101, 114, 108, 64, 49, 50,
55, 46, 48, 46, 48, 46, 49, 0, 0, 0, 1, 0, 0, 1, 58,
0, 0, 0, 2, 0, 0, 0, 0
])
(t1, tail) = codec.binary_to_term(b1, None)
self.assertTrue(isinstance(t1, Reference))
self.assertExpectedTail(tail)
# ----------------
def test_decode_tuple_py(self):
self._decode_tuple(py_impl)
def test_decode_tuple_native(self):
self._decode_tuple(native_impl)
def _decode_tuple(self, codec):
""" Try decode some tuple values """
data1 = self._etf_bytes([131, py_impl.TAG_SMALL_TUPLE_EXT,
2,
py_impl.TAG_SMALL_INT, 1,
py_impl.TAG_ATOM_EXT, 0, 2, 111, 107])
(val1, tail1) = codec.binary_to_term(data1, None)
self.assertEqual((1, Atom("ok")), val1)
self.assertExpectedTail(tail1)
data2 = self._etf_bytes([131, py_impl.TAG_LARGE_TUPLE_EXT,
0, 0, 0, 2,
py_impl.TAG_SMALL_INT, 1,
py_impl.TAG_ATOM_EXT, 0, 2, 111, 107])
(val2, tail2) = codec.binary_to_term(data2, None)
self.assertEqual((1, Atom("ok")), val2)
self.assertExpectedTail(tail2)
# Empty tuple
data3 = self._etf_bytes([131, py_impl.TAG_SMALL_TUPLE_EXT, 0])
(val3, tail3) = codec.binary_to_term(data3, None)
self.assertEqual((), val3)
self.assertExpectedTail(tail3)
# ----------------
def test_decode_list_py(self):
self._decode_list(py_impl)
def test_decode_list_native(self):
self._decode_list(native_impl)
def _decode_list(self, codec):
""" Try decode some list values """
data1 = self._etf_bytes([131, py_impl.TAG_NIL_EXT])
(val1, tail1) = codec.binary_to_term(data1, None)
self.assertEqual([], val1)
self.assertExpectedTail(tail1)
# Test data is [1, ok]
data2 = self._etf_bytes([131, py_impl.TAG_LIST_EXT,
0, 0, 0, 2,
py_impl.TAG_SMALL_INT, 1,
py_impl.TAG_ATOM_EXT, 0, 2, 111, 107,
py_impl.TAG_NIL_EXT])
(val2, tail2) = codec.binary_to_term(data2, None)
self.assertTrue(isinstance(val2, list),
"Expected list, got: %s (%s)"
% (val2.__class__.__name__, val2))
self.assertEqual(val2, [1, Atom("ok")])
self.assertExpectedTail(tail2)
# ----------------
def test_decode_map_py(self):
self._decode_map(py_impl)
def test_decode_map_native(self):
self._decode_map(native_impl)
def _decode_map(self, codec):
""" Try a map #{1 => 2, ok => error} """
data = self._etf_bytes([
131,
py_impl.TAG_MAP_EXT, 0, 0, 0, 2,
py_impl.TAG_SMALL_INT, 1,
py_impl.TAG_SMALL_INT, 2,
py_impl.TAG_ATOM_EXT, 0, 2, 111, 107,
py_impl.TAG_ATOM_EXT, 0, 5, 101, 114, 114, 111, 114
])
(val, tail) = codec.binary_to_term(data, None)
self.assertTrue(isinstance(val, dict))
self.assertEqual(val, {1: 2, Atom("ok"): Atom("error")})
self.assertExpectedTail(tail)
# ----------------
def test_float_py(self):
self._float(py_impl)
def test_float_native(self):
self._float(native_impl)
def _float(self, codec):
""" Try decode a prepared double Pi """
data = self._etf_bytes([
py_impl.ETF_VERSION_TAG,
py_impl.TAG_NEW_FLOAT_EXT, # a 8-byte IEEE double
64, 9, 33, 251, 84, 68, 45, 17
])
negative = self._etf_bytes([
py_impl.ETF_VERSION_TAG,
py_impl.TAG_NEW_FLOAT_EXT,
192, 71, 188, 40, 245, 194, 143, 92
])
(val, tail) = codec.binary_to_term(data, None)
(nval, ntail) = codec.binary_to_term(negative, None)
self.assertEqual(val, 3.14159265358979)
self.assertExpectedTail(tail)
self.assertEqual(nval, -47.47)
self.assertExpectedTail(ntail)
# ----------------
def test_float_in_packed_type_py(self):
self._float_in_packed_type(py_impl)
def test_float_in_packed_type_native(self):
self._float_in_packed_type(native_impl)
def _float_in_packed_type(self, codec):
example = self._etf_bytes([
py_impl.ETF_VERSION_TAG, py_impl.TAG_SMALL_TUPLE_EXT, 3,
py_impl.TAG_NEW_FLOAT_EXT, 64, 9, 30, 184, 81, 235, 133, 31,
py_impl.TAG_SMALL_INT, 13,
py_impl.TAG_NEW_FLOAT_EXT, 64, 1, 194, 143, 92, 40, 245, 195
])
val, tail = codec.binary_to_term(example, None)
self.assertEqual(val, (3.14, 13, 2.22))
self.assertExpectedTail(tail)
# ----------------
def test_decode_int_py(self):
self._decode_int(py_impl)
def test_decode_int_native(self):
self._decode_int(native_impl)
def _decode_int(self, codec):
positive = self._etf_bytes([131, 98, 0, 0, 18, 139]) # 4747
negative = self._etf_bytes([131, 98, 255, 255, 237, 117]) # -4747
(positive_val, positive_tail) = codec.binary_to_term(positive, None)
(negative_val, negative_tail) = codec.binary_to_term(negative, None)
self.assertEqual(positive_val, 4747)
self.assertExpectedTail(positive_tail)
self.assertEqual(negative_val, -4747)
self.assertExpectedTail(negative_tail)
# ----------------
def test_decode_small_big_py(self):
self._decode_small_big(py_impl)
def test_decode_small_big_native(self):
self._decode_small_big(native_impl)
def _decode_small_big(self, codec):
positive = self._etf_bytes([131, 110, 9, 0, 0, 0, 0, 0, | |
<gh_stars>0
"""
cppgen.py - AST pass to that prints C++ code
"""
import io
import json # for "C escaping"
import sys
from typing import overload, Union, Optional, Any, Dict
from mypy.visitor import ExpressionVisitor, StatementVisitor
from mypy.types import (
Type, AnyType, NoneTyp, TupleType, Instance, Overloaded, CallableType,
UnionType, UninhabitedType, PartialType)
from mypy.nodes import (
Expression, Statement, Block, NameExpr, IndexExpr, MemberExpr, TupleExpr,
ExpressionStmt, AssignmentStmt, IfStmt, StrExpr, SliceExpr, FuncDef,
UnaryExpr, ComparisonExpr, CallExpr, IntExpr, ListExpr, DictExpr,
ListComprehension)
import format_strings
from crash import catch_errors
from util import log
SHARED_PTR = False # global variable set by main()
T = None
class UnsupportedException(Exception):
pass
def _GetCTypeForCast(type_expr):
if isinstance(type_expr, MemberExpr):
subtype_name = '%s::%s' % (type_expr.expr.name, type_expr.name)
elif isinstance(type_expr, IndexExpr):
# List[word_t] would be a problem.
# But worked around it in osh/word_parse.py
#subtype_name = 'List<word_t>'
raise AssertionError()
else:
subtype_name = type_expr.name
# Hack for now
if subtype_name != 'int':
subtype_name += '*'
return subtype_name
def _GetCastKind(module_path, subtype_name):
cast_kind = 'static_cast'
# Hack for the CastDummy in expr_to_ast.py
if 'expr_to_ast.py' in module_path:
for name in (
'sh_array_literal', 'command_sub', 'braced_var_sub',
'double_quoted', 'single_quoted',
# Another kind of hack, not because of CastDummy
'place_expr_t',
):
if name in subtype_name:
cast_kind = 'reinterpret_cast'
break
return cast_kind
def _GetContainsFunc(t):
contains_func = None
if isinstance(t, Instance):
type_name = t.type.fullname()
if type_name == 'builtins.list':
contains_func = 'list_contains'
elif type_name == 'builtins.str':
contains_func = 'str_contains'
elif type_name == 'builtins.dict':
contains_func = 'dict_contains'
elif isinstance(t, UnionType):
# Special case for Optional[T] == Union[T, None]
if len(t.items) != 2:
raise NotImplementedError('Expected Optional, got %s' % t)
if not isinstance(t.items[1], NoneTyp):
raise NotImplementedError('Expected Optional, got %s' % t)
contains_func = _GetContainsFunc(t.items[0])
return contains_func # None checked later
def IsStr(t):
"""Helper to check if a type is a string."""
return isinstance(t, Instance) and t.type.fullname() == 'builtins.str'
def _CheckConditionType(t):
"""
strings, lists, and dicts shouldn't be used in boolean contexts, because that
doesn't translate to C++.
"""
if isinstance(t, Instance):
type_name = t.type.fullname()
if type_name == 'builtins.str':
return False
elif type_name == 'builtins.list':
return False
elif type_name == 'builtins.dict':
return False
elif isinstance(t, UnionType):
if (len(t.items) == 2 and
IsStr(t.items[0]) and isinstance(t.items[1], NoneTyp)):
return False # Optional[str]
return True
def get_c_type(t, param=False, local=False):
is_pointer = False
if isinstance(t, NoneTyp): # e.g. a function that doesn't return anything
return 'void'
elif isinstance(t, AnyType):
# Note: this usually results in another compile-time error. We should get
# rid of the 'Any' types.
c_type = 'void'
is_pointer = True
elif isinstance(t, PartialType):
# Note: bin/oil.py has some of these? Not sure why.
c_type = 'void'
is_pointer = True
# TODO: It seems better not to check for string equality, but that's what
# mypyc/genops.py does?
elif isinstance(t, Instance):
type_name = t.type.fullname()
if type_name == 'builtins.int':
c_type = 'int'
elif type_name == 'builtins.float':
c_type = 'double'
elif type_name == 'builtins.bool':
c_type = 'bool'
elif type_name == 'builtins.str':
c_type = 'Str'
is_pointer = True
elif type_name == 'builtins.list':
assert len(t.args) == 1, t.args
type_param = t.args[0]
inner_c_type = get_c_type(type_param)
c_type = 'List<%s>' % inner_c_type
is_pointer = True
elif type_name == 'builtins.dict':
params = []
for type_param in t.args:
params.append(get_c_type(type_param))
c_type = 'Dict<%s>' % ', '.join(params)
is_pointer = True
elif type_name == 'typing.IO':
c_type = 'void'
is_pointer = True
else:
# note: fullname() => 'parse.Lexer'; name() => 'Lexer'
base_class_names = [b.type.fullname() for b in t.type.bases]
#log('** base_class_names %s', base_class_names)
# Check base class for pybase.SimpleObj so we can output
# expr_asdl::tok_t instead of expr_asdl::tok_t*. That is a enum, while
# expr_t is a "regular base class".
# NOTE: Could we avoid the typedef? If it's SimpleObj, just generate
# tok_e instead?
if 'asdl.pybase.SimpleObj' not in base_class_names:
is_pointer = True
parts = t.type.fullname().split('.')
c_type = '%s::%s' % (parts[-2], parts[-1])
elif isinstance(t, UninhabitedType):
# UninhabitedType has a NoReturn flag
c_type = 'void'
elif isinstance(t, TupleType):
inner_c_types = []
for inner_type in t.items:
inner_c_types.append(get_c_type(inner_type))
c_type = 'Tuple%d<%s>' % (len(t.items), ', '.join(inner_c_types))
is_pointer = True
elif isinstance(t, UnionType):
# Special case for Optional[T] == Union[T, None]
if len(t.items) != 2:
raise NotImplementedError('Expected Optional, got %s' % t)
if not isinstance(t.items[1], NoneTyp):
raise NotImplementedError('Expected Optional, got %s' % t)
c_type = get_c_type(t.items[0])
elif isinstance(t, CallableType):
# Function types are expanded
# Callable[[Parser, Token, int], arith_expr_t] =>
# arith_expr_t* (*f)(Parser*, Token*, int) nud;
ret_type = get_c_type(t.ret_type)
arg_types = [get_c_type(typ) for typ in t.arg_types]
c_type = '%s (*f)(%s)' % (ret_type, ', '.join(arg_types))
else:
raise NotImplementedError('MyPy type: %s %s' % (type(t), t))
if is_pointer:
if param or local:
c_type = 'Local<%s>' % c_type
else:
c_type += '*'
return c_type
class Generate(ExpressionVisitor[T], StatementVisitor[None]):
def __init__(self, types: Dict[Expression, Type], const_lookup, f,
virtual=None, local_vars=None, fmt_ids=None,
decl=False, forward_decl=False):
self.types = types
self.const_lookup = const_lookup
self.f = f
self.virtual = virtual
# local_vars: FuncDef node -> list of type, var
# This is different from member_vars because we collect it in the 'decl'
# phase. But then write it in the definition phase.
self.local_vars = local_vars
self.fmt_ids = fmt_ids
self.fmt_funcs = io.StringIO()
self.decl = decl
self.forward_decl = forward_decl
self.unique_id = 0
self.indent = 0
self.local_var_list = [] # Collected at assignment
self.prepend_to_block = None # For writing vars after {
self.in_func_body = False
self.in_return_expr = False
# This is cleared when we start visiting a class. Then we visit all the
# methods, and accumulate the types of everything that looks like
# self.foo = 1. Then we write C++ class member declarations at the end
# of the class.
# This is all in the 'decl' phase.
self.member_vars = {} # type: Dict[str, Type]
self.current_class_name = None # for prototypes
self.imported_names = set() # For module::Foo() vs. self.foo
def log(self, msg, *args):
ind_str = self.indent * ' '
log(ind_str + msg, *args)
def write(self, msg, *args):
if self.decl or self.forward_decl:
return
if args:
msg = msg % args
self.f.write(msg)
# Write respecting indent
def write_ind(self, msg, *args):
if self.decl or self.forward_decl:
return
ind_str = self.indent * ' '
if args:
msg = msg % args
self.f.write(ind_str + msg)
# A little hack to reuse this pass for declarations too
def decl_write(self, msg, *args):
# TODO:
# self.header_f ?
# Just one file for all exported?
if args:
msg = msg % args
self.f.write(msg)
def decl_write_ind(self, msg, *args):
ind_str = self.indent * ' '
if args:
msg = msg % args
self.f.write(ind_str + msg)
#
# COPIED from IRBuilder
#
@overload
def accept(self, node: Expression) -> T: ...
@overload
def accept(self, node: Statement) -> None: ...
def accept(self, node: Union[Statement, Expression]) -> Optional[T]:
with catch_errors(self.module_path, node.line):
if isinstance(node, Expression):
try:
res = node.accept(self)
#res = self.coerce(res, self.node_type(node), node.line)
# If we hit an error during compilation, we want to
# keep trying, so we can produce more error
# messages. Generate a temp of the right type to keep
# from causing more downstream trouble.
except UnsupportedException:
res = self.alloc_temp(self.node_type(node))
return res
else:
try:
node.accept(self)
except UnsupportedException:
pass
return None
# Not in superclasses:
def visit_mypy_file(self, o: 'mypy.nodes.MypyFile') -> T:
# Skip some stdlib stuff. A lot of it is brought in by 'import
# typing'.
if o.fullname() in (
'__future__', 'sys', 'types', 'typing', 'abc', '_ast', 'ast',
'_weakrefset', 'collections', 'cStringIO', 're', 'builtins'):
# These module are special; their contents are currently all
# built-in primitives.
return
self.log('')
self.log('mypyfile %s', o.fullname())
mod_parts = o.fullname().split('.')
if self.forward_decl:
comment = 'forward declare'
elif self.decl:
comment = 'declare'
else:
comment = 'define'
self.decl_write_ind('namespace %s { // %s\n', mod_parts[-1], comment)
self.module_path = o.path
if self.forward_decl:
self.indent += 1
#self.log('defs %s', o.defs)
for node in o.defs:
# skip module docstring
if (isinstance(node, ExpressionStmt) and
isinstance(node.expr, StrExpr)):
continue
self.accept(node)
# Write fmtX() functions inside the namespace.
if self.decl:
self.decl_write(self.fmt_funcs.getvalue())
self.fmt_funcs = io.StringIO() # clear it for the next file
if self.forward_decl:
self.indent -= 1
self.decl_write('\n')
self.decl_write_ind(
'} // %s namespace %s\n', comment, mod_parts[-1])
self.decl_write('\n')
# NOTE: Copied ExpressionVisitor and StatementVisitor nodes below!
# LITERALS
def visit_int_expr(self, o: 'mypy.nodes.IntExpr') -> T:
self.write(str(o.value))
def visit_str_expr(self, o: 'mypy.nodes.StrExpr') -> T:
self.write(self.const_lookup[o])
def visit_bytes_expr(self, o: 'mypy.nodes.BytesExpr') -> T:
pass
def visit_unicode_expr(self, | |
[ self._ssl_cert_filename, self._ssl_key_filename ]
def _InitCaches( self ):
pass
def _InitDB( self ):
create_db = False
db_path = os.path.join( self._db_dir, self._db_filenames[ 'main' ] )
if not os.path.exists( db_path ):
create_db = True
external_db_paths = [ os.path.join( self._db_dir, self._db_filenames[ db_name ] ) for db_name in self._db_filenames if db_name != 'main' ]
existing_external_db_paths = [ external_db_path for external_db_path in external_db_paths if os.path.exists( external_db_path ) ]
if len( existing_external_db_paths ) > 0:
message = 'Although the external files, "{}" do exist, the main database file, "{}", does not! This makes for an invalid database, and the program will now quit. Please contact hydrus_dev if you do not know how this happened or need help recovering from hard drive failure.'
message = message.format( ', '.join( existing_external_db_paths ), db_path )
raise HydrusExceptions.DBAccessException( message )
self._InitDBConnection()
result = self._Execute( 'SELECT 1 FROM sqlite_master WHERE type = ? AND name = ?;', ( 'table', 'version' ) ).fetchone()
if result is None:
create_db = True
if create_db:
self._is_first_start = True
self._CreateDB()
self._cursor_transaction_wrapper.CommitAndBegin()
def _InitDBConnection( self ):
self._CloseDBConnection()
db_path = os.path.join( self._db_dir, self._db_filenames[ 'main' ] )
try:
if os.path.exists( db_path ) and not HydrusPaths.FileisWriteable( db_path ):
raise HydrusExceptions.DBAccessException( '"{}" seems to be read-only!'.format( db_path ) )
self._db = sqlite3.connect( db_path, isolation_level = None, detect_types = sqlite3.PARSE_DECLTYPES )
c = self._db.cursor()
self._SetCursor( c )
self._is_connected = True
self._cursor_transaction_wrapper = HydrusDBBase.DBCursorTransactionWrapper( self._c, HG.db_transaction_commit_period )
if HG.no_db_temp_files:
self._Execute( 'PRAGMA temp_store = 2;' ) # use memory for temp store exclusively
self._AttachExternalDatabases()
self._LoadModules()
self._Execute( 'ATTACH ":memory:" AS mem;' )
except HydrusExceptions.DBAccessException as e:
raise
except Exception as e:
raise HydrusExceptions.DBAccessException( 'Could not connect to database! If the answer is not obvious to you, please let hydrus dev know. Error follows:' + os.linesep * 2 + str( e ) )
HydrusDBBase.TemporaryIntegerTableNameCache.instance().Clear()
# durable_temp is not excluded here
db_names = [ name for ( index, name, path ) in self._Execute( 'PRAGMA database_list;' ) if name not in ( 'mem', 'temp' ) ]
for db_name in db_names:
# MB -> KB
cache_size = HG.db_cache_size * 1024
self._Execute( 'PRAGMA {}.cache_size = -{};'.format( db_name, cache_size ) )
self._Execute( 'PRAGMA {}.journal_mode = {};'.format( db_name, HG.db_journal_mode ) )
if HG.db_journal_mode in ( 'PERSIST', 'WAL' ):
self._Execute( 'PRAGMA {}.journal_size_limit = {};'.format( db_name, 1024 ** 3 ) ) # 1GB for now
self._Execute( 'PRAGMA {}.synchronous = {};'.format( db_name, HG.db_synchronous ) )
try:
self._Execute( 'SELECT * FROM {}.sqlite_master;'.format( db_name ) ).fetchone()
except sqlite3.OperationalError as e:
message = 'The database seemed valid, but hydrus failed to read basic data from it. You may need to run the program in a different journal mode using --db_journal_mode. Full error information:'
message += os.linesep * 2
message += str( e )
HydrusData.DebugPrint( message )
raise HydrusExceptions.DBAccessException( message )
try:
self._cursor_transaction_wrapper.BeginImmediate()
except Exception as e:
if 'locked' in str( e ):
raise HydrusExceptions.DBAccessException( 'Database appeared to be locked. Please ensure there is not another client already running on this database, and then try restarting the client.' )
raise HydrusExceptions.DBAccessException( str( e ) )
def _InitExternalDatabases( self ):
pass
def _LoadModules( self ):
pass
def _ManageDBError( self, job, e ):
raise NotImplementedError()
def _ProcessJob( self, job ):
job_type = job.GetType()
( action, args, kwargs ) = job.GetCallableTuple()
try:
if job_type in ( 'read_write', 'write' ):
self._current_status = 'db write locked'
self._cursor_transaction_wrapper.NotifyWriteOccuring()
else:
self._current_status = 'db read locked'
self.publish_status_update()
if job_type in ( 'read', 'read_write' ):
result = self._Read( action, *args, **kwargs )
elif job_type in ( 'write' ):
result = self._Write( action, *args, **kwargs )
if job.IsSynchronous():
job.PutResult( result )
self._cursor_transaction_wrapper.Save()
if self._cursor_transaction_wrapper.TimeToCommit():
self._current_status = 'db committing'
self.publish_status_update()
self._cursor_transaction_wrapper.CommitAndBegin()
self._DoAfterJobWork()
except Exception as e:
self._ManageDBError( job, e )
try:
self._cursor_transaction_wrapper.Rollback()
except Exception as rollback_e:
HydrusData.Print( 'When the transaction failed, attempting to rollback the database failed. Please restart the client as soon as is convenient.' )
self._CloseDBConnection()
self._InitDBConnection()
HydrusData.PrintException( rollback_e )
finally:
self._CleanAfterJobWork()
self._current_status = ''
self.publish_status_update()
def _Read( self, action, *args, **kwargs ):
raise NotImplementedError()
def _RepairDB( self, version ):
for module in self._modules:
module.Repair( version, self._cursor_transaction_wrapper )
def _ReportOverupdatedDB( self, version ):
pass
def _ReportUnderupdatedDB( self, version ):
pass
def _ReportStatus( self, text ):
HydrusData.Print( text )
def _ShrinkMemory( self ):
self._Execute( 'PRAGMA shrink_memory;' )
def _UnloadModules( self ):
pass
def _UpdateDB( self, version ):
raise NotImplementedError()
def _Write( self, action, *args, **kwargs ):
raise NotImplementedError()
def publish_status_update( self ):
pass
def CurrentlyDoingJob( self ):
return self._currently_doing_job
def GetApproxTotalFileSize( self ):
total = 0
for filename in self._db_filenames.values():
path = os.path.join( self._db_dir, filename )
total += os.path.getsize( path )
return total
def GetSSLPaths( self ):
# create ssl keys
cert_here = os.path.exists( self._ssl_cert_path )
key_here = os.path.exists( self._ssl_key_path )
if cert_here ^ key_here:
raise Exception( 'While creating the server database, only one of the paths "{}" and "{}" existed. You can create a db with these files already in place, but please either delete the existing file (to have hydrus generate its own pair) or find the other in the pair (to use your own).'.format( self._ssl_cert_path, self._ssl_key_path ) )
elif not ( cert_here or key_here ):
HydrusData.Print( 'Generating new cert/key files.' )
if not HydrusEncryption.OPENSSL_OK:
raise Exception( 'The database was asked for ssl cert and keys to start either the server or the client api in https. The files do not exist yet, so the database wanted to create new ones, but unfortunately PyOpenSSL is not available, so this cannot be done. If you are running from source, please install this module using pip. Or drop in your own client.crt/client.key or server.crt/server.key files in the db directory.' )
HydrusEncryption.GenerateOpenSSLCertAndKeyFile( self._ssl_cert_path, self._ssl_key_path )
return ( self._ssl_cert_path, self._ssl_key_path )
def GetStatus( self ):
return ( self._current_status, self._current_job_name )
def IsConnected( self ):
return self._is_connected
def IsDBUpdated( self ):
return self._is_db_updated
def IsFirstStart( self ):
return self._is_first_start
def LoopIsFinished( self ):
return self._loop_finished
def JobsQueueEmpty( self ):
return self._jobs.empty()
def MainLoop( self ):
try:
self._InitDBConnection() # have to reinitialise because the thread id has changed
self._InitCaches()
except:
self._DisplayCatastrophicError( traceback.format_exc() )
self._could_not_initialise = True
return
self._ready_to_serve_requests = True
error_count = 0
while not ( ( self._local_shutdown or HG.model_shutdown ) and self._jobs.empty() ):
try:
job = self._jobs.get( timeout = 1 )
self._currently_doing_job = True
self._current_job_name = job.ToString()
self.publish_status_update()
try:
if HG.db_report_mode:
summary = 'Running db job: ' + job.ToString()
HydrusData.ShowText( summary )
if HG.profile_mode:
summary = 'Profiling db job: ' + job.ToString()
HydrusData.Profile( summary, 'self._ProcessJob( job )', globals(), locals(), min_duration_ms = HG.db_profile_min_job_time_ms )
else:
self._ProcessJob( job )
error_count = 0
| |
<filename>canflood/build/dialog.py<gh_stars>10-100
# -*- coding: utf-8 -*-
"""
ui class for the BUILD toolset
"""
#==============================================================================
# imports-----------
#==============================================================================
#python
import sys, os, datetime, time
"""see __init__.py for dependency check"""
import pandas as pd
import numpy as np #assuming if pandas is fine, numpy will be fine
#PyQt
from PyQt5 import uic, QtWidgets
from PyQt5.QtWidgets import QAction, QFileDialog, QListWidget, QTableWidgetItem
#qgis
#from qgis.core import *
from qgis.core import QgsProject, QgsVectorLayer, QgsRasterLayer, QgsMapLayerProxyModel, \
QgsWkbTypes, QgsMapLayer
#==============================================================================
# custom imports
#==============================================================================
#get hlpr funcs
import hlpr.plug
from hlpr.plug import bind_layersListWidget
#from hlpr.basic import get_valid_filename, force_open_dir
from hlpr.exceptions import QError as Error
#get sub-models
from build.rsamp import Rsamp
from build.lisamp import LikeSampler
from build.prepr import Preparor
from build.validator import Vali
#get sub-dialogs
from build.dialog_vfunc import vDialog
from build.dialog_rprep import RPrepDialog
#===============================================================================
# load UI file
#===============================================================================
# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
ui_fp = os.path.join(os.path.dirname(__file__), 'build.ui')
assert os.path.exists(ui_fp), 'failed to find the ui file: \n %s'%ui_fp
FORM_CLASS, _ = uic.loadUiType(ui_fp)
#===============================================================================
# class objects-------
#===============================================================================
class BuildDialog(QtWidgets.QDialog, FORM_CLASS, hlpr.plug.QprojPlug):
event_name_set = [] #event names
icon_fn = 'Andy_Tools_Hammer_Spanner_23x23.png'
icon_name = 'Build'
icon_location = 'toolbar'
def __init__(self, iface, parent=None, **kwargs):
#=======================================================================
# #init baseclass
#=======================================================================
"""these will only ini tthe first baseclass (QtWidgets.QDialog)
required"""
super(BuildDialog, self).__init__(parent) #only calls QtWidgets.QDialog
#=======================================================================
# attachments
#=======================================================================
#=======================================================================
# setup funcs
#=======================================================================
self.setupUi(self)
self.qproj_setup(iface=iface, **kwargs)
#self.connect_slots()
self.logger.debug('BuildDialog initilized')
def connect_slots(self):
"""
using the cointaier (dict) self.launch_actions to store functions
that should be called once the dialog is launched
see self.launch()
"""
log = self.logger.getChild('connect_slots')
#=======================================================================
# init children
#=======================================================================
"""TODO: make these init on first click"""
self.vDialog = vDialog(self.iface) #init and attach vfunc library dialog(connected below)
self.RPrepDialog=RPrepDialog(self.iface)
#======================================================================
# pull project data
#======================================================================
#pull layer info from project
rlays_d = dict()
vlays_d = dict()
for layname, layer in QgsProject.instance().mapLayers().items():
if isinstance(layer, QgsVectorLayer):
vlays_d[layname] = layer
elif isinstance(layer, QgsRasterLayer):
rlays_d[layname] = layer
else:
self.logger.debug('%s not filtered'%layname)
#=======================================================================
# general----------------
#=======================================================================
#ok/cancel buttons
self.buttonBox.accepted.connect(self.reject) #back out of the dialog
self.buttonBox.rejected.connect(self.reject)
#connect to status label
"""
this could be moved onto the feedback object...
but would be a lot of work to move it off the logger
and not sure what the benefit would be
"""
self.logger.statusQlab=self.progressText #connect to the progress text
#self.logger.statusQlab.setText('BuildDialog initialized')
#======================================================================
#TAB: SETUP----------
#======================================================================
#=======================================================================
# session controls
#=======================================================================
#Working Directory
self._connect_wdir(self.pushButton_wd, self.pushButton_wd_open, self.lineEdit_wdir,
default_wdir = os.path.join(os.path.expanduser('~'), 'CanFlood', 'build'))
#AOI
hlpr.plug.bind_MapLayerComboBox(self.comboBox_aoi,
iface=self.iface, layerType=QgsMapLayerProxyModel.PolygonLayer)
#CanFlood Control
self.pushButton_cf.clicked.connect(
lambda: self.fileSelect_button(self.lineEdit_cf_fp,
caption='Select Control File',
path = self.lineEdit_wdir.text(),
filters="Text Files (*.txt)")
)
self.pushButton_s_cfOpen.clicked.connect(lambda: os.startfile(self.lineEdit_cf_fp.text()))
#=======================================================================
# Control File Assembly
#=======================================================================
#elevation t ype
self.comboBox_SSelv.addItems(['datum', 'ground']) #ss elevation type
#Vulnerability Curve Set
def browse_curves():
return self.browse_button(self.lineEdit_curve, prompt='Select Curve Set',
qfd = QFileDialog.getOpenFileName)
self.pushButton_SScurves.clicked.connect(browse_curves)# SS. Vuln Curve Set. Browse
#generate new control file
self.pushButton_generate.clicked.connect(self.build_scenario) #SS. generate
#=======================================================================
# TAB: INVENTORY------------
#=======================================================================
#=======================================================================
# vfunc
#=======================================================================
#give commmon widgets
for wName in self.vDialog.inherit_atts:
assert hasattr(self, wName), wName
setattr(self.vDialog, wName, getattr(self, wName))
#connect launcher button
def vDia(): #helper to connect slots and
"""only executing setup once called to simplify initial loading"""
_ = self.vDialog._setup()
self.vDialog.show()
self.pushButton_inv_vfunc.clicked.connect(vDia)
self.pushButton_Inv_curves.clicked.connect(self.store_curves)
#=======================================================================
# Store IVlayer
#=======================================================================
#inventory vector layer box
hlpr.plug.bind_MapLayerComboBox(self.comboBox_ivlay,
layerType=QgsMapLayerProxyModel.VectorLayer, iface=self.iface)
#attempt to select the layer during launch
self.launch_actions['attempt finv'] = lambda: self.comboBox_ivlay.attempt_selection('finv')
#set it on the session for the other dialogs
self.comboBox_ivlay.layerChanged.connect(
lambda: setattr(self.session, 'finv_vlay', self.comboBox_ivlay.currentLayer()))
#index field name
self.comboBox_ivlay.layerChanged.connect(
lambda : self.mfcb_connect(self.mFieldComboBox_cid,
self.comboBox_ivlay.currentLayer(), fn_str='xid'))
#connect button
self.pushButton_Inv_store.clicked.connect(self.store_finv)
#=======================================================================
# NRPI
#=======================================================================
#filter the vector layer
self.mMapLayerComboBox_inv_finv.setFilters(QgsMapLayerProxyModel.VectorLayer)
self.mMapLayerComboBox_inv_finv.setCurrentIndex(-1) #clear the selection
#connect the push button
self.pushButton_inv_const.clicked.connect(self.construct_finv)
#======================================================================
# TAB: HAZARD SAMPLER---------
#======================================================================
#=======================================================================
# wsl raster layers
#=======================================================================
#list widget
bind_layersListWidget(self.listView_expo_rlays, log, iface=self.iface,
layerType=QgsMapLayer.RasterLayer) #add custom bindigns
#connect buttons
self.pushButton_expo_sAll.clicked.connect(self.listView_expo_rlays.check_all)
self.pushButton_expo_clear.clicked.connect(self.listView_expo_rlays.clear_checks)
self.pushButton_expo_sVis.clicked.connect(self.listView_expo_rlays.select_visible)
self.pushButton_expo_canvas.clicked.connect(self.listView_expo_rlays.select_canvas)
"""not sure if this fix is needed... but possibleissue with kwarg passing"""
self.pushButton_expo_refr.clicked.connect(lambda x: self.listView_expo_rlays.populate_layers())
#populate the widget
self.launch_actions['hazlay selection'] = lambda: self.listView_expo_rlays.populate_layers()
#=======================================================================
# inundation
#=======================================================================
hlpr.plug.bind_MapLayerComboBox(self.comboBox_HS_DTM,
layerType=QgsMapLayerProxyModel.RasterLayer, iface=self.iface)
#attempt to select the layer during launch
self.launch_actions['attempt dtm2'] = lambda: self.comboBox_HS_DTM.attempt_selection('dtm')
#=======================================================================
# #exposure type
#=======================================================================
#populate the exposure type
self.hs_expoType_d = {'value':'Values', 'area':'Area-Threshold'}
self.comboBox_HS_EC_type.addItems(list(self.hs_expoType_d.values()))
#force logic ontofindChildren type controls
def force_expoTypeControlLogic():
self.logger.debug('force_expoTypeControlLogic called')
vlay = self.comboBox_ivlay.currentLayer()
if isinstance(vlay,QgsVectorLayer):
gtype = QgsWkbTypes().displayString(vlay.wkbType())
if not 'Point' in gtype: #complex geometry
#value selected. freeze area controls
if self.comboBox_HS_EC_type.currentText() == self.hs_expoType_d['value']:
self.groupBox_HS_AT.setDisabled(True)
self.groupBox_HS_VS.setDisabled(False)
#area threshold selected
elif self.comboBox_HS_EC_type.currentText() == self.hs_expoType_d['area']:
self.groupBox_HS_AT.setDisabled(False)
self.groupBox_HS_VS.setDisabled(True) #disable the Value Sampling box
else:
log.debug('bad selection on comboBox_HS_EC_type: \'%s\''%(
self.comboBox_HS_EC_type.currentText()))
#type box
self.HSvalueSamplingType_d = {'global':'Global', 'passet':'Per-Asset'}
#force logic onto exposure type when the finv selection changes
def force_expoTypeLogic():
vlay = self.comboBox_ivlay.currentLayer()
if isinstance(vlay,QgsVectorLayer):
gtype = QgsWkbTypes().displayString(vlay.wkbType())
self.label_HS_finvgtype.setText(gtype) #set the label
self.comboBox_HS_EC_type.setCurrentIndex(0)
if 'Point' in gtype: #simple geometry
self.comboBox_HS_EC_type.setDisabled(True)
#turn off complex controls
self.groupBox_HS_AT.setDisabled(True)
self.groupBox_HS_VS.setDisabled(True)
self.comboBox_HS_VS_type.setCurrentIndex(-1)
else:
self.comboBox_HS_EC_type.setDisabled(False)
force_expoTypeControlLogic()
else:
#disable until a finv is selected
self.label_HS_finvgtype.setText('select a finv on the \'Inventory\' tab')
self.comboBox_HS_EC_type.setCurrentIndex(-1)
self.comboBox_HS_EC_type.setDisabled(True)
#link to the finv
self.comboBox_ivlay.layerChanged.connect(force_expoTypeLogic)
#link to the type combobox
self.comboBox_HS_EC_type.currentTextChanged.connect(force_expoTypeControlLogic)
#=======================================================================
# value sampling
#=======================================================================
self.comboBox_HS_VS_type.addItems(list(self.HSvalueSamplingType_d.values()))
self.comboBox_HS_VS_type.setCurrentIndex(-1)
#statistic or field box
def force_vsStatBox(): #populate the comboox according to the selected type
self.comboBox_HS_VS_stat.clear()
vlay = self.comboBox_ivlay.currentLayer()
if isinstance(vlay,QgsVectorLayer):
selection = self.comboBox_HS_VS_type.currentText()
#user selected global
if selection == self.HSvalueSamplingType_d['global']:
self.comboBox_HS_VS_stat.addItems(['Mean','Median','Min','Max'])
elif selection == self.HSvalueSamplingType_d['passet']:
self.comboBox_HS_VS_stat.addItems([f.name() for f in vlay.fields()])
else:
log.debug('bad selection on comboBox_HS_VS_type: \'%s\''%selection)
self.comboBox_HS_VS_type.currentTextChanged.connect(force_vsStatBox)
#=======================================================================
# #execute buttons
#=======================================================================
self.pushButton_HSgenerate.clicked.connect(self.run_rsamp)
#=======================================================================
# Raster Prep
#=======================================================================
#give commmon widgets
for wName in self.RPrepDialog.inherit_atts:
assert hasattr(self, wName), wName
setattr(self.RPrepDialog, wName, getattr(self, wName))
#connect launcher button
def rpDia(): #helper to connect slots and
"""only executing setup once called to simplify initial loading"""
_ = self.RPrepDialog._setup()
self.RPrepDialog.pushButton_HS_prep.clicked.connect(self.run_rPrep)
self.RPrepDialog.show()
self.pushButton_HS_rprep.clicked.connect(rpDia)
#======================================================================
# TAB: EVENT VARIABLES---------
#======================================================================
self.pushButton_ELstore.clicked.connect(self.set_event_vals)
"""not much here?
table population is done by run_rsamp()
"""
#======================================================================
# TAB: CONDITIONAL P-----------
#======================================================================
"""
run_rsamp() attempts to populate this
todo: rename the buttons so they align w/ the set labels
todo: automatically populate the first column of boxes w/ those layers
sampled w/ rsamp
"""
#list of combo box names on the likelihood sampler tab
self.ls_cb_d = { #set {hazard raster : lpol}
1: (self.MLCB_LS1_event_3, self.MLCB_LS1_lpol_3),
2: (self.MLCB_LS1_event_4, self.MLCB_LS1_lpol_4),
3: (self.MLCB_LS1_event_5, self.MLCB_LS1_lpol_5),
4: (self.MLCB_LS1_event, self.MLCB_LS1_lpol),
5: (self.MLCB_LS1_event_6, self.MLCB_LS1_lpol_6),
6: (self.MLCB_LS1_event_7, self.MLCB_LS1_lpol_7),
7: (self.MLCB_LS1_event_2, self.MLCB_LS1_lpol_2),
8: (self.MLCB_LS1_event_8, self.MLCB_LS1_lpol_8)
}
#loop and set filteres
first = True
for sname, (mlcb_haz, mlcb_lpol) in self.ls_cb_d.items():
#set drop down filters on hazard bars
mlcb_haz.setFilters(QgsMapLayerProxyModel.RasterLayer)
mlcb_haz.setAllowEmptyLayer(True)
mlcb_haz.setCurrentIndex(-1) #set selection to none
#on polygon bars
mlcb_lpol.setFilters(QgsMapLayerProxyModel.PolygonLayer)
mlcb_lpol.setAllowEmptyLayer(True)
mlcb_lpol.setCurrentIndex(-1) #set selection to none
#store the first lpol box for connecting the FieldName dropdown
if first:
mlcb_lpol_1 = mlcb_lpol
first = False
#connect to update the field name box (based on the first layer)
def upd_lfield(): #updating the field box
return self.mfcb_connect(
self.mFieldComboBox_LSfn, mlcb_lpol_1.currentLayer(),
fn_str = 'fail' )
mlcb_lpol_1.layerChanged.connect(upd_lfield)
#connect execute
self.pushButton_LSsample.clicked.connect(self.run_lisamp)
#=======================================================================
# clear button
#=======================================================================
self.pushButton_CP_clear.clicked.connect(self._CP_clear)
#======================================================================
# DTM sampler---------
#======================================================================
hlpr.plug.bind_MapLayerComboBox(self.comboBox_dtm,
layerType=QgsMapLayerProxyModel.RasterLayer, iface=self.iface)
#attempt to select the layer during launch
self.launch_actions['attempt dtm'] = lambda: self.comboBox_dtm.attempt_selection('dtm')
self.pushButton_DTMsamp.clicked.connect(self.run_dsamp)
#======================================================================
# validator-----------
#======================================================================
self.pushButton_Validate.clicked.connect(self.run_validate)
#=======================================================================
# wrap
#=======================================================================
log.debug('complete')
return
#===========================================================================
# HELPERS----------
#===========================================================================
def set_setup(self, set_cf_fp=True, set_finv=True, #attach parameters from setup tab
logger=None,):
if logger is None: logger=self.logger
log = logger.getChild('set_setup')
#=======================================================================
# #call the common
#=======================================================================
self._set_setup(set_cf_fp=set_cf_fp) #resets inherit_fieldNames
self.inherit_fieldNames.append('init_q_d')
#=======================================================================
# custom setups
#=======================================================================
#project aoi
self.aoi_vlay = self.comboBox_aoi.currentLayer()
#file behavior
self.loadRes = self.checkBox_loadres.isChecked()
#=======================================================================
# #inventory vector layer---------
#=======================================================================
if set_finv:
#===================================================================
# get using sleection logic
#===================================================================
vlay_raw = self.comboBox_ivlay.currentLayer()
assert not vlay_raw is None, 'must select a finv vlay'
aoi_vlay = self.comboBox_aoi.currentLayer()
#selected finv features
if self.checkBox_sels.isChecked():
assert aoi_vlay is None, 'specify \'Selected features only\' or | |
import os
import time
import json
import uuid
from sqlite3 import connect
# Configuration
DATABASE_FILE = "database.db"
FILE_PATH = os.path.dirname(os.path.realpath(__file__)) + "/" + DATABASE_FILE
ROOT_ID = "root"
## Testing
RECREATE_ENTRIES = True
RECREATE_ENTRIES = False
# # # # # # #
# Interface #
# # # # # # #
async def add_entry(websocket, data):
client_id = data['client_id']
parent_id = data['parent_id']
text = data['text']
if not parent_id:
parent_id = ROOT_ID
new_entry_id = database_add_entry(client_id, parent_id, text)
if new_entry_id == None:
await websocket.send(json.dumps({
'type': 'error',
'message': "Could not add entry"
}))
else:
new_entry_data = create_data_for_entry(client_id, parent_id, new_entry_id)
await websocket.send(json.dumps({
'type': 'adding_successful',
'new_entry': new_entry_data
}))
async def change_text(websocket, data):
client_id = data['client_id']
entry_id = data['entry_id']
text = data['text']
database_rename_entry(client_id, entry_id, text)
await websocket.send(json.dumps({
'type': 'change_text_successful',
'entry_id': entry_id,
'text': text
}))
async def move_entry(websocket, data):
client_id = data['client_id']
entry_id = data['entry_id']
delta = data['delta']
success = move_entry_in_database(client_id, entry_id, delta)
await websocket.send(json.dumps({
'type': 'move_entry_response',
'success': success,
'entry_id': entry_id,
'delta': delta
}))
list_direct_children(client_id, get_parent_id_for_entry_id(client_id, entry_id))
async def delete_entry(websocket, data):
client_id = data['client_id']
entry_id = data['entry_id']
deleted_ids = delete_entry_from_database(client_id, entry_id)
await websocket.send(json.dumps({
'type': 'delete_successful',
'deleted_entry_ids': deleted_ids
}))
async def request_data(websocket, data):
client_id = data['client_id']
entry_id = ROOT_ID
hierarchical_data = get_entry_data_recursivly(client_id, entry_id)
await websocket.send(json.dumps({
'type': 'update_data',
'data': hierarchical_data
}))
async def paste_entry(websocket, data):
client_id = data['client_id']
entry_id = data['entry_id']
target_id = data['target_id']
clipboard_type = data['type'] # cut | copy
if clipboard_type == 'cut':
old_parent_id = cut_paste_entry_in_database(client_id, entry_id, target_id)
await websocket.send(json.dumps({
'type': 'cut_paste_successful',
'entry_id': entry_id,
'old_parent_id': old_parent_id,
'new_parent_id': target_id,
'clipboard_type': clipboard_type
}))
"""
elif clipboard_type == 'copy':
new_root_id = copy_paste_entry_in_database(client_id, entry_id, target_id)
await websocket.send(json.dumps({
'type': 'copy_paste_successful',
'new_root_id': new_root_id,
'new_parent_id': target_id,
'copied_entry_id': entry_id,
'clipboard_type': clipboard_type
}))
"""
# # # # # # #
# Database #
# # # # # # #
def setup_database():
with connect(FILE_PATH) as conn:
cursor = conn.cursor()
if RECREATE_ENTRIES:
cursor.execute('DROP TABLE IF EXISTS data')
cursor.execute('DROP TABLE IF EXISTS users')
cursor.execute('CREATE TABLE IF NOT EXISTS data (entry_id STRING, text STRING, client_id STRING, parent_id STRING, priority INTEGER)')
cursor.execute('CREATE TABLE IF NOT EXISTS users (id STRING, name STRING)')
if RECREATE_ENTRIES:
user_id = get_id()
user_name = 'test'
with connect(FILE_PATH) as conn:
cursor = conn.cursor()
sql = 'INSERT INTO users (id, name) VALUES(?, ?)'
params = (user_id, user_name)
cursor.execute(sql, params)
return user_id
def user_exists(user_name):
with connect(FILE_PATH) as conn:
cursor = conn.cursor()
sql = 'SELECT * FROM users WHERE name=?'
params = (user_name, )
cursor.execute(sql, params)
return len(cursor.fetchall()) > 0
def database_add_entry(client_id, parent_id, text):
children_of_parent = get_children_for(client_id, parent_id)
with connect(FILE_PATH) as conn:
entry_id = get_id()
cursor = conn.cursor()
sql = 'INSERT INTO data (client_id, entry_id, text, parent_id, priority) VALUES(?, ?, ?, ?, ?)'
params = (client_id, entry_id, text, parent_id, len(children_of_parent))
cursor.execute(sql, params)
return entry_id
def database_rename_entry(client_id, entry_id, text):
with connect(FILE_PATH) as conn:
cursor = conn.cursor()
sql = 'UPDATE data SET text=? WHERE client_id=? AND entry_id=?'
params = (text, client_id, entry_id)
cursor.execute(sql, params)
return entry_id
def get_entry_data_recursivly(client_id, entry_id):
data = create_data_for_entry(client_id, None, entry_id)
_iterate_children_entries(client_id, data, entry_id)
return data
def create_data_for_entry(client_id, parent_id, child_id):
return {
"id": child_id,
'text': get_text_for_id(client_id, child_id),
'labels': [],
'entries': [],
'parent_id': parent_id
}
def _iterate_children_entries(client_id, parent_data, parent_id):
for child_id in get_children_for(client_id, parent_id):
data = create_data_for_entry(client_id, parent_id, child_id)
_iterate_children_entries(client_id, data, child_id)
parent_data['entries'].append(data)
def get_children_for(client_id, parent_id):
with connect(FILE_PATH) as conn:
cursor = conn.cursor()
sql = 'SELECT entry_id FROM data WHERE client_id=? AND parent_id=? ORDER BY priority ASC'
params = (client_id, parent_id)
cursor.execute(sql, params)
all_ids = cursor.fetchall()
if len(all_ids) > 0:
return [x[0] for x in all_ids]
return []
def get_text_for_id(client_id, entry_id):
with connect(FILE_PATH) as conn:
cursor = conn.cursor()
sql = 'SELECT text FROM data WHERE client_id=? AND entry_id=?'
params = (client_id, entry_id)
cursor.execute(sql, params)
the_one = cursor.fetchone()
if the_one != None:
return the_one[0]
return None
def move_entry_in_database(client_id, entry_id, delta):
with connect(FILE_PATH) as conn:
cursor = conn.cursor()
sql = "SELECT parent_id, priority FROM data WHERE client_id=? AND entry_id=?"
params = (client_id, entry_id)
cursor.execute(sql, params)
row = cursor.fetchone()
parent_id = row[0]
current_priority = row[1]
parent_subtasks = get_children_for(client_id, parent_id)
subtasks_length = len(parent_subtasks)
target_priority = max(0, min(subtasks_length - 1, current_priority + delta))
if current_priority == target_priority:
return False
with connect(FILE_PATH) as conn:
cursor = conn.cursor()
# XXX This only works when shifting elements by 1
# Move other entry to new place
sql = "UPDATE data SET priority=? WHERE client_id=? AND priority=? AND parent_id=?"
params = (current_priority, client_id, target_priority, parent_id)
cursor.execute(sql, params)
# Move selected entry to target place
sql = "UPDATE data SET priority=? WHERE client_id=? AND entry_id=?"
params = (target_priority, client_id, entry_id)
cursor.execute(sql, params)
fix_priorities_for_level(client_id, parent_id)
list_direct_children(client_id, parent_id)
return True
def delete_entry_from_database(client_id, entry_id):
parent_id = get_parent_id_for_entry_id(client_id, entry_id) # Needed after deletion for fixing priorities
deleted_ids = []
with connect(FILE_PATH) as conn:
cursor = conn.cursor()
def delete_recursivly(parent_id):
deleted_ids.append(parent_id)
# Print deleted entry to be able to "restore" accidently deleted entries
sql = "SELECT parent_id, entry_id, text FROM data WHERE client_id=? AND entry_id=?"
params = (client_id, parent_id)
cursor.execute(sql, params)
print("DELETED\t", "\t".join(cursor.fetchone()))
for child_id in get_children_for(client_id, parent_id):
delete_recursivly(child_id)
sql = "DELETE FROM data WHERE client_id=? AND entry_id=?"
params = (client_id, parent_id)
cursor.execute(sql, params)
sql = "UPDATE data SET priority=priority-1 WHERE priority>(SELECT priority FROM data WHERE client_id=? AND entry_id=?) AND client_id=? AND parent_id=?"
params = (client_id, entry_id, client_id, parent_id)
cursor.execute(sql, params)
delete_recursivly(entry_id)
# fix_priorities_for_level(client_id, parent_id)
list_direct_children(client_id, parent_id)
return deleted_ids
def cut_paste_entry_in_database(client_id, entry_id, target_id):
children_of_parent = get_children_for(client_id, target_id)
with connect(FILE_PATH) as conn:
cursor = conn.cursor()
# Get old data
sql = 'SELECT parent_id, priority FROM data WHERE client_id=? AND entry_id=?'
params = (client_id, entry_id)
cursor.execute(sql, params)
result = cursor.fetchone()
old_parent_id = result[0]
old_priority = result[1]
# Assign pasted entry to new parent
sql = 'UPDATE data SET parent_id=?, priority=? WHERE client_id=? AND entry_id=?'
params = (target_id, len(children_of_parent), client_id, entry_id)
cursor.execute(sql, params)
# Adjust priorities of old siblings
sql = "UPDATE data SET priority=priority-1 WHERE parent_id=? AND priority>?"
params = (old_parent_id, old_priority)
cursor.execute(sql, params)
# fix_priorities_for_level(client_id, old_parent_id)
# fix_priorities_for_level(client_id, target_id)
list_direct_children(client_id, target_id)
return old_parent_id
"""
def copy_paste_entry_in_database(client_id, entry_id, target_id):
hierarchical_data = get_entry_data_recursivly(client_id, entry_id)
print(json.dumps(hierarchical_data, indent=2))
all_new_ids = []
def add_copy(new_parent_id, to_copy_entry_id, to_copy_entry_data):
local_new_entry_id = database_add_entry(client_id, new_parent_id, to_copy_entry_data['text'])
all_new_ids.append(local_new_entry_id)
for child_entry_id, child_entry_data in to_copy_entry_data['entries'].items():
add_copy(local_new_entry_id, child_entry_id, child_entry_data)
add_copy(target_id, entry_id, hierarchical_data)
return all_new_ids[0] # return new root element
"""
"""
# This does not work because SQLite does not support variables
def fix_priorities_recursivly(client_id):
def work_entry(parent_id):
with connect(FILE_PATH) as conn:
cursor = conn.cursor()
sql = "SET @i:=0; UPDATE data SET priority = @i:=(@i+1) WHERE client_id=?, parent_id=?"
params = (client_id, parent_id, )
cursor.execute(sql, params)
for child_id in get_children_for(client_id, parent_id):
work_entry(child_id)
work_entry(ROOT_ID)
"""
def get_parent_id_for_entry_id(client_id, entry_id):
with connect(FILE_PATH) as conn:
cursor = conn.cursor()
sql = 'SELECT parent_id FROM data WHERE client_id=? AND entry_id=?'
params = (client_id, entry_id)
cursor.execute(sql, params)
result = cursor.fetchone()
print("result")
print(result)
parent_id = result[0]
return parent_id
# HACK this should not be necessary
# This reassigns priorities to all children entries to make sure
# that there are no duplicates and no gaps
def fix_priorities_recursivly(user_name):
print(f"Fixing priorities for {user_name}")
client_id = get_client_id_for_username(user_name)
client_id = user_name # FIXME why does this not use the real client_id?
def work(parent_id, level):
fix_priorities_for_level(client_id, parent_id)
# list_direct_children(client_id, parent_id)
print(f'{" " * level}{get_text_for_id(client_id, parent_id)}')
for child_id in get_children_for(client_id, parent_id):
work(child_id, level+1)
work(ROOT_ID, 0)
def fix_priorities_for_level(client_id, parent_id):
priority = 0
with connect(FILE_PATH) as conn:
cursor = conn.cursor()
sql = 'SELECT entry_id FROM data WHERE client_id=? and parent_id=? ORDER BY priority ASC'
params = (client_id, parent_id)
cursor.execute(sql, params)
direct_children = cursor.fetchall()
for child_entry in direct_children:
child_id = child_entry[0]
sql = 'UPDATE data SET priority=? WHERE client_id=? AND entry_id=?'
params = (priority, client_id, child_id)
cursor.execute(sql, params)
priority += 1
# # # # # # # # # # #
# Helper functions #
# # # # # # # # # # #
def get_id():
return uuid.uuid4().hex
def get_client_id_for_username(username):
with connect(FILE_PATH) as conn:
cursor = conn.cursor()
sql = 'SELECT id FROM users WHERE name=?'
params = (username, )
cursor.execute(sql, params)
return cursor.fetchone()[0]
def list_all_entries_for_user(client_id):
with connect(FILE_PATH) as conn:
cursor = conn.cursor()
sql = 'SELECT parent_id, entry_id, text, priority FROM data WHERE client_id=? ORDER BY priority ASC'
params = (client_id, )
cursor.execute(sql, params)
print(" [ Data ] ")
for l in cursor.fetchall():
print(l)
def list_direct_children(client_id, parent_id):
with connect(FILE_PATH) as conn:
cursor = conn.cursor()
sql = 'SELECT parent_id, entry_id, text, priority FROM data WHERE client_id=? AND parent_id=? ORDER BY priority ASC'
params = | |
= "undefined"
obj_attr_list["target_state"] = "undefined"
_status, _fmsg = self.parse_cli(obj_attr_list, parameters, command)
if not _status :
_status, _fmsg = self.initialize_object(obj_attr_list, command)
_cloud_name = obj_attr_list["cloud_name"]
if _status in [0, 483920, 912543] :
if _status not in [483920] :
self.osci.add_to_list(_cloud_name, "VM", "PENDING", obj_attr_list["uuid"] + "|" + obj_attr_list["name"], int(time()))
self.osci.pending_object_set(_cloud_name, "VM", obj_attr_list["uuid"], "status", "Changing state to: " + obj_attr_list["target_state"] + "(" + obj_attr_list["suspected_command"] + ")")
_runstate_pending = True
if _status == 483920 :
_tmp_result = self.continue_vm(obj_attr_list)
_status = _tmp_result["status"]
_fmsg = _tmp_result["msg"]
_result = _tmp_result["result"]
obj_attr_list.update(_result)
obj_attr_list["target_state"] = "attached"
obj_attr_list["suspected_command"] = "run"
elif _status == 912543 :
_status, _fmsg, _result = self.vmrunstateall(parameters, obj_attr_list["suspected_command"])
elif not _status :
_current_state = self.osci.get_object_state(_cloud_name, "VM", obj_attr_list["uuid"])
_target_state = obj_attr_list["target_state"].lower()
if _target_state == "resume" :
_target_state = "attached"
if _target_state == "restore" :
_target_state = "attached"
if _target_state not in ["save", "suspend", "fail", "attached" ] :
_fmsg = "Unknown state: " + _target_state
_status = 101
if not _status :
if _target_state != _current_state :
obj_attr_list["current_state"] = _current_state
self.set_cloud_operations_instance(obj_attr_list["model"])
_cld_conn = self.coi[obj_attr_list["model"]][self.pid + '-' + obj_attr_list["experiment_id"]]
# TAC looks up libvirt function based on target state
# Do not remove this
if _target_state == "attached" :
if _current_state == "save" :
obj_attr_list["target_state"] = "restore"
else :
obj_attr_list["target_state"] = "resume"
elif _target_state in [ "fail", "suspend"] and _current_state != "attached" :
_msg = "Unable to fail a VM that is not on the \""
_msg += "attached\" state."
_status = 871
raise self.ObjectOperationException(_msg, _status)
_status, _fmsg = _cld_conn.vmrunstate(obj_attr_list)
if not _status :
self.osci.set_object_state(_cloud_name, "VM", obj_attr_list["uuid"], _target_state)
if _target_state != "attached" :
self.osci.add_to_list(_cloud_name, "VM", "VMS_UNDERGOING_" + _target_state.upper(), obj_attr_list["uuid"])
elif _target_state == "attached" :
self.osci.remove_from_list(_cloud_name, "VM", "VMS_UNDERGOING_SAVE", obj_attr_list["uuid"])
self.osci.remove_from_list(_cloud_name, "VM", "VMS_UNDERGOING_SUSPEND", obj_attr_list["uuid"])
self.osci.remove_from_list(_cloud_name, "VM", "VMS_UNDERGOING_FAIL", obj_attr_list["uuid"])
if "mgt_201_runstate_request_originated" in obj_attr_list :
self.osci.update_object_attribute(_cloud_name, "VM", \
obj_attr_list["uuid"], \
False, \
"mgt_201_runstate_request_originated", \
obj_attr_list["mgt_201_runstate_request_originated"])
if "mgt_202_runstate_request_sent" in obj_attr_list :
self.osci.update_object_attribute(_cloud_name, "VM", \
obj_attr_list["uuid"], \
False, \
"mgt_202_runstate_request_sent", \
obj_attr_list["mgt_202_runstate_request_sent"])
if "mgt_203_runstate_request_completed" in obj_attr_list :
self.osci.update_object_attribute(_cloud_name, "VM", \
obj_attr_list["uuid"], \
False, \
"mgt_203_runstate_request_completed", \
obj_attr_list["mgt_203_runstate_request_completed"])
self.record_management_metrics(_cloud_name, "VM", obj_attr_list, "runstate")
_status = 0
else :
_result = obj_attr_list
_msg = "VM is already at the \"" + obj_attr_list["target_state"]
_msg += "\" state. There is no need to explicitly change it."
cbdebug(_msg)
_status = 0
except self.ObjectOperationException, obj :
_status = obj.status
_fmsg = str(obj.msg)
except self.osci.ObjectStoreMgdConnException, obj :
_status = obj.status
_fmsg = str(obj.msg)
except CldOpsException, obj :
_status = obj.status
_fmsg = str(obj.msg)
except Exception, e :
_status = 23
_fmsg = str(e)
finally:
unique_state_key = "-state-" + str(time())
if _status :
if _status != 9 :
_msg = "VM object " + obj_attr_list["uuid"] + " ("
_msg += "named \"" + obj_attr_list["name"] + "\") could "
_msg += " not have his run state changed to \""
_msg += obj_attr_list["target_state"] + "\" on this "
_msg += "experiment: " + _fmsg
cberr(_msg)
obj_attr_list["tracking"] = "Change state request: " + _fmsg
if "uuid" in obj_attr_list and "cloud_name" in obj_attr_list and self.osci :
self.osci.create_object(_cloud_name, "FAILEDTRACKINGVM", \
obj_attr_list["uuid"] + \
unique_state_key, \
obj_attr_list, False, True, 3600)
else :
_msg = _fmsg
else :
_msg = "VM object " + obj_attr_list["uuid"]
_msg += " (named \"" + obj_attr_list["name"] + "\") had "
_msg += "its run state successfully changed to \""
_msg += obj_attr_list["target_state"] + "\" on this "
_msg += "experiment."
cbdebug(_msg)
obj_attr_list["tracking"] = "Change state request: success."
self.osci.create_object(_cloud_name, "FINISHEDTRACKINGVM", obj_attr_list["uuid"] + unique_state_key, \
obj_attr_list, False, True, 3600)
if _runstate_pending :
self.osci.pending_object_remove(_cloud_name, "VM", obj_attr_list["uuid"], "status")
self.osci.remove_from_list(_cloud_name, "VM", "PENDING", obj_attr_list["uuid"] + "|" + obj_attr_list["name"], True)
return self.package(_status, _msg, _result)
@trace
def vmrunstateall(self, parameters, command) :
'''
TBD
'''
try :
_status = 100
_fmsg = "An error has occurred, but no error message was captured"
_smsg = ''
_obj_attr_list = {}
_target_state = "undefined"
if BaseObjectOperations.default_cloud is None :
_obj_attr_list["cloud_name"] = parameters.split()[0]
else :
if len(parameters) > 0 and BaseObjectOperations.default_cloud == parameters.split()[0] :
True
else :
parameters = BaseObjectOperations.default_cloud + ' ' + parameters
_obj_attr_list["cloud_name"] = parameters.split()[0]
parameters = parameters.split()
if len(parameters) >= 3 :
_all = parameters[1]
_target_state= parameters[2]
_status = 0
if len(parameters) < 3:
_status = 9
_fmsg = "Usage: vmrunstate <cloud name> <vm name> <runstate> [mode]"
if not _status :
_obj_attr_list["command_originated"] = int(time())
_obj_attr_list["command"] = "vmrunstateall " + _obj_attr_list["cloud_name"] + " all"
_obj_attr_list["name"] = "all"
self.get_counters(_obj_attr_list["cloud_name"], _obj_attr_list)
self.record_management_metrics(_obj_attr_list["cloud_name"], "VM", _obj_attr_list, "trace")
_vm_list = False
if _target_state == "attached" and (command == "repair" or command == "resume") :
_vm_list = self.osci.get_list(_obj_attr_list["cloud_name"], "VM", "VMS_UNDERGOING_FAIL")
elif _target_state == "attached" and command == "restore" :
_vm_list = self.osci.get_list(_obj_attr_list["cloud_name"], "VM", "VMS_UNDERGOING_SAVE")
else :
_vm_list = []
_vms = self.osci.get_object_list(_obj_attr_list["cloud_name"], "VM")
if _vms :
for _vm in _vms :
_current_state = self.osci.get_object_state(_obj_attr_list["cloud_name"], "VM", _vm)
if _current_state and _current_state == "attached" :
_vm_list.append(_vm)
if _vm_list :
_vm_counter = 0
_obj_attr_list["parallel_operations"] = {}
_obj_attr_list["parallel_operations"][_vm_counter] = {}
for _vm in _vm_list :
if len(_vm) == 2 :
_vm_uuid = _vm[0]
else :
_vm_uuid = _vm
_vm_attr_list = self.osci.get_object(_obj_attr_list["cloud_name"], "VM", False, _vm_uuid, False)
_vm_name = _vm_attr_list["name"]
_obj_attr_list["runstate_parallelism"] = _vm_attr_list["runstate_parallelism"]
_obj_attr_list["parallel_operations"][_vm_counter] = {}
_obj_attr_list["parallel_operations"][_vm_counter]["uuid"] = _vm_attr_list["uuid"]
_obj_attr_list["parallel_operations"][_vm_counter]["parameters"] = _obj_attr_list["cloud_name"] + ' ' + _vm_name + ' ' + _target_state
_obj_attr_list["parallel_operations"][_vm_counter]["operation"] = "vm-runstate"
_vm_counter += 1
if _vm_counter > int(_obj_attr_list["runstate_parallelism"]) :
_obj_attr_list["runstate_parallelism"] = int(_obj_attr_list["runstate_parallelism"])
else :
_obj_attr_list["runstate_parallelism"] = _vm_counter
_status, _fmsg = self.parallel_obj_operation("runstate", _obj_attr_list)
else :
_fmsg = " No VMs are in state suitable for the transition "
_fmsg += "specified (to the \"" + _target_state + "\" state)."
_status = 791
except self.ObjectOperationException, obj :
_status = obj.status
_fmsg = str(obj.msg)
except self.osci.ObjectStoreMgdConnException, obj :
_status = obj.status
_fmsg = str(obj.msg)
except ImportError, msg :
_status = 8
_fmsg = str(msg)
except AttributeError, msg :
_status = 8
_fmsg = str(msg)
except Exception, e :
_status = 23
_fmsg = str(e)
finally:
if _status :
_msg = "Failure while changing all suitable VMs to the state \""
_msg += _target_state + "\" on this experiment: " + _fmsg
cberr(_msg)
else :
_msg = "All suitable VMs were successfully changed to the state"
_msg += "\"" + _target_state + "\" on this experiment"
cbdebug(_msg)
return _status, _msg, None
@trace
def airunstate_actual(self, obj_attr_list) :
'''
TBD
'''
_status = 0
_target_state = obj_attr_list["target_state"].lower()
_msg = "Going to change the state of all VMs for AI "
_msg += obj_attr_list["name"] + " to the \"" + _target_state
_msg += "\" state."
cbdebug(_msg, True)
self.runstate_list_for_ai(obj_attr_list, obj_attr_list["target_state"])
if obj_attr_list["state_changed_vms"] != "0" :
_status, _fmsg = self.parallel_obj_operation("runstate", obj_attr_list)
if not _status :
self.osci.set_object_state(obj_attr_list["cloud_name"], "AI", obj_attr_list["uuid"], _target_state)
return _status, _fmsg
@trace
def airunstate(self, obj_attr_list, parameters, command) :
'''
TBD
'''
try :
_status = 100
_result = []
_runstate_pending = False
_fmsg = "An error has occurred, but no error message was captured"
_obj_type = command.split('-')[0].upper()
obj_attr_list["name"] = "undefined"
_status, _fmsg = self.parse_cli(obj_attr_list, parameters, command)
if not _status :
_status, _fmsg = self.initialize_object(obj_attr_list, command)
_cloud_name = obj_attr_list["cloud_name"]
if _status in [0, 483920, 912543] :
if _status not in [483920] :
self.osci.add_to_list(_cloud_name, "AI", "PENDING", obj_attr_list["uuid"] + "|" + obj_attr_list["name"], int(time()))
self.osci.pending_object_set(_cloud_name, "AI", obj_attr_list["uuid"], "status", "Changing state to: " + obj_attr_list["target_state"] + "(" + obj_attr_list["suspected_command"] + ")")
_runstate_pending = True
if _status == 483920 :
_tmp_result = self.continue_app(obj_attr_list)
_status = _tmp_result["status"]
_fmsg = _tmp_result["msg"]
_result = _tmp_result["result"]
obj_attr_list.update(_result)
obj_attr_list["target_state"] = "attached"
obj_attr_list["suspected_command"] = "run"
elif _status == 912543 :
_status, _fmsg, _result = self.airunstateall(parameters, obj_attr_list["suspected_command"])
elif not _status :
_status, _fmsg = self.airunstate_actual(obj_attr_list)
_result = obj_attr_list
except self.ObjectOperationException, obj :
_status = obj.status
_fmsg = str(obj.msg)
except self.osci.ObjectStoreMgdConnException, obj :
_status = obj.status
_fmsg = str(obj.msg)
except Exception, e :
_status = 23
_fmsg = str(e)
finally:
unique_state_key = "-state-" + str(time())
if _status :
if _status != 9 :
_msg = "Could not change all VMs state: " + | |
<reponame>jurafish/Paddle<filename>python/paddle/distributed/auto_parallel/context.py
# Copyright (c) 2021 PaddlePaddle 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
import copy
from collections import defaultdict
from paddle.fluid import framework
from paddle.fluid import core
from .attribute import TensorDistributedAttribute
from .attribute import OperatorDistributedAttribute
from .utils import append_distributed_attr_suffix
from .interface import _g_process_mesh_map
# There always exists a default context for user. And user can set it to another one.
DEFAULT_DISTRIBUTED_CONTEXT = None
def get_default_distributed_context():
global DEFAULT_DISTRIBUTED_CONTEXT
if DEFAULT_DISTRIBUTED_CONTEXT is None:
dist_context = DistributedContext()
set_default_distributed_context(dist_context)
return DEFAULT_DISTRIBUTED_CONTEXT
def set_default_distributed_context(dist_context):
global DEFAULT_DISTRIBUTED_CONTEXT
DEFAULT_DISTRIBUTED_CONTEXT = dist_context
class DistributedContext:
"""
DistributedContext is used to collect related distributed information for program and graph.
One auto-parallel run should use its own DistributedContext to avoid interfering other run.
"""
def __init__(self):
self._is_initialized_for_program = False
self._is_initialized_for_graph = False
self._tensor_distributed_attr_map_for_program = {}
self._op_distributed_attr_map_for_program = {}
self._tensor_distributed_attr_map_for_graph = {}
self._op_distributed_attr_map_for_graph = {}
self._get_dist_op_helper = DistOpHelper()
self._process_mesh = _g_process_mesh_map.get(0, None)
def is_initialized_for_program(self):
return self._is_initialized_for_program
def is_initialized_for_graph(self):
return self._is_initialized_for_graph
def get_tensor_distributed_attr_for_program(self, tensor):
tensor_id = tensor.desc.id()
tensor_dist_attr = self._tensor_distributed_attr_map_for_program.get(
tensor_id, None)
return tensor_dist_attr
def set_tensor_distributed_attr_for_program(self, tensor, tensor_dist_attr):
tensor_id = tensor.desc.id()
self._tensor_distributed_attr_map_for_program[
tensor_id] = tensor_dist_attr
def get_op_distributed_attr_for_program(self, op):
op_id = op.desc.id()
op_dist_attr = self._op_distributed_attr_map_for_program.get(op_id,
None)
return op_dist_attr
def set_op_distributed_attr_for_program(self, op, op_dist_attr):
op_id = op.desc.id()
self._op_distributed_attr_map_for_program[op_id] = op_dist_attr
def get_tensor_distributed_attr_for_graph(self, tensor_node):
tensor_node_id = tensor_node.id()
tensor_dist_attr = self._tensor_distributed_attr_map_for_graph.get(
tensor_node_id, None)
return tensor_dist_attr
def set_tensor_distributed_attr_for_graph(self, tensor_node,
tensor_dist_attr):
tensor_node_id = tensor_node.id()
self._tensor_distributed_attr_map_for_graph[
tensor_node_id] = tensor_dist_attr
def get_op_distributed_attr_for_graph(self, op_node):
op_node_id = op_node.id()
op_dist_attr = self._op_distributed_attr_map_for_graph.get(op_node_id,
None)
return op_dist_attr
def set_op_distributed_attr_for_graph(self, op_node, op_dist_attr):
op_node_id = op_node.id()
self._op_distributed_attr_map_for_graph[op_node_id] = op_dist_attr
def set_process_mesh(self, process_mesh):
self._process_mesh = process_mesh
def get_dist_op_helper(self):
return self._get_dist_op_helper
def initialize_distributed_attr_for_program(self, program):
if self._is_initialized_for_program:
return
for block in program.blocks:
for tensor in block.vars.values():
# Since only tensors have distributed attributes, it's better to make sure var is a tensor
tensor_dist_attr = self.get_tensor_distributed_attr_for_program(
tensor)
if tensor_dist_attr is None:
tensor_dist_attr = TensorDistributedAttribute(tensor, self)
self._copy_distributed_attr_from_tensor_desc(
tensor.desc, tensor_dist_attr)
self.set_tensor_distributed_attr_for_program(
tensor, tensor_dist_attr)
if tensor.type == core.VarDesc.VarType.READER:
tensor_dist_attr.set_shape([])
else:
tensor_dist_attr.set_shape(tensor.desc.shape())
if tensor_dist_attr.get_process_mesh() is not None:
tensor_dist_attr.mark_as_annotated("process_mesh")
if tensor_dist_attr.get_dims_mapping() is None:
tensor_dims_mapping = [
-1 for _ in range(len(tensor_dist_attr.get_shape()))
]
tensor_dist_attr.set_dims_mapping(tensor_dims_mapping)
else:
tensor_dist_attr.mark_as_annotated("dims_mapping")
if isinstance(tensor, framework.Parameter):
tensor_dist_attr.mark_as_parameter()
for op in block.ops:
op_dist_attr = self.get_op_distributed_attr_for_program(op)
if op_dist_attr is None:
op_dist_attr = OperatorDistributedAttribute(op, self)
self._copy_distributed_attr_from_op_desc(op.desc,
op_dist_attr)
self.set_op_distributed_attr_for_program(op, op_dist_attr)
# Default distributed implementation for all operators
# This will be updated during the completion prcess
op_dist_attr.set_impl_idx(-2)
if op_dist_attr.get_process_mesh() is not None:
op_dist_attr.mark_as_annotated("process_mesh")
for tensor_name in op.input_arg_names:
# There may be a better way to find the tensor by name
if op.type == "create_py_reader" \
or tensor.type == core.VarDesc.VarType.READER:
op_dist_attr.set_input_shape(tensor_name, [])
else:
tensor = op.block._var_recursive(tensor_name)
op_dist_attr.set_input_shape(tensor_name,
tensor.desc.shape())
if op_dist_attr.get_input_dims_mapping(tensor_name) is None:
tensor_dims_mapping = [
-1
for _ in range(
len(op_dist_attr.get_input_shape(tensor_name)))
]
op_dist_attr.set_input_dims_mapping(tensor_name,
tensor_dims_mapping)
else:
op_dist_attr.mark_as_annotated_input_dims_mapping(
tensor_name)
if isinstance(tensor, framework.Parameter):
op_dist_attr.mark_as_parameter(tensor_name)
for tensor_name in op.output_arg_names:
tensor = op.block._var_recursive(tensor_name)
if tensor.type == core.VarDesc.VarType.READER:
op_dist_attr.set_output_shape(tensor_name, [])
else:
op_dist_attr.set_output_shape(tensor_name,
tensor.desc.shape())
if op_dist_attr.get_output_dims_mapping(
tensor_name) is None:
tensor_dims_mapping = [
-1
for _ in range(
len(
op_dist_attr.get_output_shape(tensor_name)))
]
op_dist_attr.set_output_dims_mapping(
tensor_name, tensor_dims_mapping)
else:
op_dist_attr.mark_as_annotated_output_dims_mapping(
tensor_name)
if isinstance(tensor, framework.Parameter):
op_dist_attr.mark_as_parameter(tensor_name)
self._is_initialized_for_program = True
def finalize_distributed_attr_for_program(self, program):
assert self._is_initialized_for_program, \
"The program must initialize its distributed attribute before finalization."
for block in program.blocks:
for tensor in block.vars.values():
tensor_dist_attr = self.get_tensor_distributed_attr_for_program(
tensor)
if tensor_dist_attr is not None:
self._store_distributed_attr_to_tensor_desc(
tensor.desc, tensor_dist_attr)
for op in block.ops:
op_dist_attr = self.get_op_distributed_attr_for_program(op)
if op_dist_attr is not None:
self._store_distributed_attr_to_op_desc(op.desc,
op_dist_attr)
def _copy_distributed_attr_from_tensor_desc(self, desc, dist_attr):
from paddle.distributed.auto_parallel.interface import _g_process_mesh_map
attr_name = append_distributed_attr_suffix("mesh_id")
if desc.has_attr(attr_name):
mesh_id = desc.attr(attr_name)
process_mesh = _g_process_mesh_map[mesh_id]
copied_process_mesh = copy.deepcopy(process_mesh)
dist_attr.set_process_mesh(copied_process_mesh)
attr_name = append_distributed_attr_suffix("dim_mapping")
if desc.has_attr(attr_name):
dims_mapping = desc.attr(attr_name)
copied_dims_mapping = copy.deepcopy(dims_mapping)
dist_attr.set_dims_mapping(copied_dims_mapping)
attr_name = append_distributed_attr_suffix("mask")
if desc.has_attr(attr_name):
shard_mask = desc.attr(attr_name)
copied_shard_mask = copy.deepcopy(shard_mask)
dist_attr.set_shard_mask(copied_shard_mask)
attr_name = append_distributed_attr_suffix("offload_device")
if desc.has_attr(attr_name):
offload_device = desc.attr(attr_name)
copied_offload_device = copy.deepcopy(offload_device)
dist_attr.set_offload_device(copied_offload_device)
def _copy_distributed_attr_from_op_desc(self, desc, dist_attr):
from paddle.distributed.auto_parallel.interface import _g_process_mesh_map
attr_name = append_distributed_attr_suffix("mesh_id")
if desc.has_attr(attr_name):
mesh_id = desc.attr(attr_name)
process_mesh = _g_process_mesh_map[mesh_id]
copied_process_mesh = copy.deepcopy(process_mesh)
dist_attr.set_process_mesh(copied_process_mesh)
for tensor_name in desc.input_arg_names():
attr_name = append_distributed_attr_suffix("IN_" + tensor_name)
if desc.has_attr(attr_name):
dims_mapping = desc.attr(attr_name)
copied_dims_mapping = copy.deepcopy(dims_mapping)
dist_attr.set_input_dims_mapping(tensor_name,
copied_dims_mapping)
for tensor_name in desc.output_arg_names():
attr_name = append_distributed_attr_suffix("OUT_" + tensor_name)
if desc.has_attr(attr_name):
dims_mapping = desc.attr(attr_name)
copied_dims_mapping = copy.deepcopy(dims_mapping)
dist_attr.set_input_dims_mapping(tensor_name,
copied_dims_mapping)
attr_name = append_distributed_attr_suffix("pipeline_stage")
if desc.has_attr(attr_name):
pipeline_stage = desc.attr(attr_name)
copied_pipeline_stage = copy.deepcopy(pipeline_stage)
dist_attr.set_pipeline_stage(copied_pipeline_stage)
def _store_distributed_attr_to_tensor_desc(self, desc, dist_attr):
process_mesh = dist_attr.get_process_mesh()
if process_mesh is not None:
attr_name = append_distributed_attr_suffix("mesh_id")
desc._set_attr(attr_name, process_mesh._id)
dims_mapping = dist_attr.get_dims_mapping()
if dims_mapping is not None:
attr_name = append_distributed_attr_suffix("dim_mapping")
desc._set_attr(attr_name, dims_mapping)
shard_mask = dist_attr.get_shard_mask()
if shard_mask is not None:
attr_name = append_distributed_attr_suffix("mask")
desc._set_attr(attr_name, shard_mask)
offload_device = dist_attr.get_offload_device()
if offload_device is not None:
attr_name = append_distributed_attr_suffix("offload_device")
desc._set_attr(attr_name, offload_device)
def _store_distributed_attr_to_op_desc(self, desc, dist_attr):
process_mesh = dist_attr.get_process_mesh()
if process_mesh is not None:
attr_name = append_distributed_attr_suffix("mesh_id")
desc._set_attr(attr_name, process_mesh._id)
for tensor_name in desc.input_arg_names():
dims_mapping = dist_attr.get_input_dims_mapping(tensor_name)
if dims_mapping is not None:
attr_name = append_distributed_attr_suffix("IN_" + tensor_name)
desc._set_attr(attr_name, dims_mapping)
for tensor_name in desc.output_arg_names():
dims_mapping = dist_attr.get_output_dims_mapping(tensor_name)
if dims_mapping is not None:
attr_name = append_distributed_attr_suffix("OUT_" + tensor_name)
desc._set_attr(attr_name, dims_mapping)
pipeline_stage = dist_attr.get_pipeline_stage()
if pipeline_stage is not None:
attr_name = append_distributed_attr_suffix("pipeline_stage")
desc._set_attr(attr_name, pipeline_stage)
def initialize_distributed_attr_for_graph(self, graph):
assert self._is_initialized_for_program, \
"The program must initialize its distributed attribute before its graph."
if self._is_initialized_for_graph:
return
all_nodes = graph.all_nodes()
for node in all_nodes:
if node.is_var() and node.var() is not None:
tensor_desc = node.var()
tensor_id = tensor_desc.id()
tensor_dist_attr = self._tensor_distributed_attr_map_for_program[
tensor_id]
assert tensor_dist_attr is not None, \
"Tensor must have a distributed attribute after the initialization for program."
new_tensor_dist_attr = copy.deepcopy(tensor_dist_attr)
self.set_tensor_distributed_attr_for_graph(node,
new_tensor_dist_attr)
if node.is_op() and node.op() is not None:
op_desc = node.op()
op_id = op_desc.id()
op_dist_attr = self._op_distributed_attr_map_for_program[op_id]
assert op_dist_attr is not None, \
"Operator must have a distributed attribute after the initialization for program."
new_op_dist_attr = copy.deepcopy(op_dist_attr)
self.set_op_distributed_attr_for_graph(node, new_op_dist_attr)
self._is_initialized_for_graph = True
def clear_distributed_attr_for_program(self):
self._tensor_distributed_attr_map_for_program.clear()
self._op_distributed_attr_map_for_program.clear()
def clear_distributed_attr_for_graph(self):
self._tensor_distributed_attr_map_for_graph.clear()
self._op_distributed_attr_map_for_graph.clear()
def copy_distribute_attr_from_graph_to_program(self, graph, program):
assert self._is_initialized_for_program and self._is_initialized_for_graph, \
"The distribute attributes must be initialized both in its program and graph"
updated_tensors = {}
all_nodes = graph.all_nodes()
for node in all_nodes:
if node.is_var() and node.var() is not None:
tensor_desc = node.var()
tensor_id = tensor_desc.id()
updated = updated_tensors.get(tensor_desc.name(), False)
# If a var has multiples var nodes in graph, only use the first one for now
if not updated:
tensor_dist_attr = self.get_tensor_distributed_attr_for_graph(
node)
new_tensor_dist_attr = copy.deepcopy(tensor_dist_attr)
self._tensor_distributed_attr_map_for_program[
tensor_id] = new_tensor_dist_attr
updated_tensors[tensor_desc.name()] = True
if node.is_op() and node.op() is not None:
op_desc = node.op()
op_id = op_desc.id()
op_dist_attr = self.get_op_distributed_attr_for_graph(node)
new_op_dist_attr = copy.deepcopy(op_dist_attr)
self._op_distributed_attr_map_for_program[
op_id] = new_op_dist_attr
def amend_distributed_attr_for_program(self):
for attr in self._tensor_distributed_attr_map_for_program.values():
assert attr.is_valid(), \
"Tensor's distributed attribute {} is not valid".format(attr)
tensor_shape = attr.get_shape()
dims_mapping = attr.get_dims_mapping()
process_mesh_shape = attr.get_process_mesh().topology
# If the dimension of tensor is less than the sharding dimension of process mesh,
# we just amend the dimension mapping to -1. (Is this really OK?)
for i in range(len(tensor_shape)):
if dims_mapping[i] != -1 and tensor_shape[i] > 0 \
and process_mesh_shape[dims_mapping[i]] > tensor_shape[i]:
dims_mapping[i] = -1
for attr in self._op_distributed_attr_map_for_program.values():
assert attr.is_valid(), \
"Operator's distributed attribute {} is not valid".format(attr)
for arg_name in attr.get_owner_op().desc.input_arg_names():
tensor_shape = attr.get_input_shape(arg_name)
dims_mapping = attr.get_input_dims_mapping(arg_name)
process_mesh_shape = attr.get_process_mesh().topology
# If the dimension of tensor is less than the sharding dimension of process mesh,
# we just amend the dimension mapping to -1. (Is this really OK?)
for i in range(len(tensor_shape)):
if dims_mapping[i] != -1 and tensor_shape[i] > 0 \
and process_mesh_shape[dims_mapping[i]] > tensor_shape[i]:
dims_mapping[i] = -1
for arg_name in attr.get_owner_op().desc.output_arg_names():
tensor_shape = attr.get_output_shape(arg_name)
dims_mapping = attr.get_output_dims_mapping(arg_name)
process_mesh_shape = attr.get_process_mesh().topology
# If the dimension of tensor is less than the sharding dimension of process mesh,
# we just amend the dimension mapping to -1. (Is this really OK?)
for i in range(len(tensor_shape)):
if dims_mapping[i] != -1 and tensor_shape[i] > 0 \
and process_mesh_shape[dims_mapping[i]] > tensor_shape[i]:
dims_mapping[i] = -1
class DistOpHelper:
"""
DistOpHelper is used to create a dist op desc | |
mask
if self.mask is not None:
out |= self.mask
return out
def is_hom(self, allele=None):
"""Find genotype calls that are homozygous.
Parameters
----------
allele : int, optional
Allele index.
Returns
-------
out : ndarray, bool, shape (n_variants, n_samples)
Array where elements are True if the genotype call matches the
condition.
Examples
--------
>>> import allel
>>> g = allel.GenotypeArray([[[0, 0], [0, 1]],
... [[0, 1], [1, 1]],
... [[2, 2], [-1, -1]]])
>>> g.is_hom()
array([[ True, False],
[False, True],
[ True, False]])
>>> g.is_hom(allele=1)
array([[False, False],
[False, True],
[False, False]])
>>> v = g[:, 0]
>>> v
<GenotypeVector shape=(3, 2) dtype=int64>
0/0 0/1 2/2
>>> v.is_hom()
array([ True, False, True])
"""
if allele is None:
allele1 = self.values[..., 0, np.newaxis]
other_alleles = self.values[..., 1:]
tmp = (allele1 >= 0) & (allele1 == other_alleles)
out = np.all(tmp, axis=-1)
else:
out = np.all(self.values == allele, axis=-1)
# handle mask
if self.mask is not None:
out &= ~self.mask
return out
def is_hom_ref(self):
"""Find genotype calls that are homozygous for the reference allele.
Returns
-------
out : ndarray, bool, shape (n_variants, n_samples)
Array where elements are True if the genotype call matches the
condition.
Examples
--------
>>> import allel
>>> g = allel.GenotypeArray([[[0, 0], [0, 1]],
... [[0, 1], [1, 1]],
... [[0, 2], [-1, -1]]])
>>> g.is_hom_ref()
array([[ True, False],
[False, False],
[False, False]])
>>> v = g[:, 0]
>>> v
<GenotypeVector shape=(3, 2) dtype=int64>
0/0 0/1 0/2
>>> v.is_hom_ref()
array([ True, False, False])
"""
return self.is_hom(allele=0)
def is_hom_alt(self):
"""Find genotype calls that are homozygous for any alternate (i.e.,
non-reference) allele.
Returns
-------
out : ndarray, bool, shape (n_variants, n_samples)
Array where elements are True if the genotype call matches the
condition.
Examples
--------
>>> import allel
>>> g = allel.GenotypeArray([[[0, 0], [0, 1]],
... [[0, 1], [1, 1]],
... [[2, 2], [-1, -1]]])
>>> g.is_hom_alt()
array([[False, False],
[False, True],
[ True, False]])
>>> v = g[:, 1]
>>> v
<GenotypeVector shape=(3, 2) dtype=int64>
0/1 1/1 ./.
>>> v.is_hom_alt()
array([False, True, False])
"""
allele1 = self.values[..., 0, np.newaxis]
other_alleles = self.values[..., 1:]
tmp = (allele1 > 0) & (allele1 == other_alleles)
out = np.all(tmp, axis=-1)
# handle mask
if self.mask is not None:
out &= ~self.mask
return out
def is_het(self, allele=None):
"""Find genotype calls that are heterozygous.
Returns
-------
out : ndarray, bool, shape (n_variants, n_samples)
Array where elements are True if the genotype call matches the
condition.
allele : int, optional
Heterozygous allele.
Examples
--------
>>> import allel
>>> g = allel.GenotypeArray([[[0, 0], [0, 1]],
... [[0, 1], [1, 1]],
... [[0, 2], [-1, -1]]])
>>> g.is_het()
array([[False, True],
[ True, False],
[ True, False]])
>>> g.is_het(2)
array([[False, False],
[False, False],
[ True, False]])
>>> v = g[:, 0]
>>> v
<GenotypeVector shape=(3, 2) dtype=int64>
0/0 0/1 0/2
>>> v.is_het()
array([False, True, True])
"""
allele1 = self.values[..., 0, np.newaxis] # type: np.ndarray
other_alleles = self.values[..., 1:] # type: np.ndarray
out = np.all(self.values >= 0, axis=-1) & np.any(allele1 != other_alleles, axis=-1)
if allele is not None:
out &= np.any(self.values == allele, axis=-1)
# handle mask
if self.mask is not None:
out &= ~self.mask
return out
def is_call(self, call):
"""Locate genotypes with a given call.
Parameters
----------
call : array_like, int, shape (ploidy,)
The genotype call to find.
Returns
-------
out : ndarray, bool, shape (n_variants, n_samples)
Array where elements are True if the genotype is `call`.
Examples
--------
>>> import allel
>>> g = allel.GenotypeArray([[[0, 0], [0, 1]],
... [[0, 1], [1, 1]],
... [[0, 2], [-1, -1]]])
>>> g.is_call((0, 2))
array([[False, False],
[False, False],
[ True, False]])
>>> v = g[:, 0]
>>> v
<GenotypeVector shape=(3, 2) dtype=int64>
0/0 0/1 0/2
>>> v.is_call((0, 2))
array([False, False, True])
"""
# guard conditions
if not len(call) == self.shape[-1]:
raise ValueError('invalid call ploidy: %s', repr(call))
if self.ndim == 2:
call = np.asarray(call)[np.newaxis, :]
else:
call = np.asarray(call)[np.newaxis, np.newaxis, :]
out = np.all(self.values == call, axis=-1)
# handle mask
if self.mask is not None:
out &= ~self.mask
return out
def count_called(self, axis=None):
"""Count called genotypes.
Parameters
----------
axis : int, optional
Axis over which to count, or None to perform overall count.
"""
b = self.is_called()
return np.sum(b, axis=axis)
def count_missing(self, axis=None):
"""Count missing genotypes.
Parameters
----------
axis : int, optional
Axis over which to count, or None to perform overall count.
"""
b = self.is_missing()
return np.sum(b, axis=axis)
def count_hom(self, allele=None, axis=None):
"""Count homozygous genotypes.
Parameters
----------
allele : int, optional
Allele index.
axis : int, optional
Axis over which to count, or None to perform overall count.
"""
b = self.is_hom(allele=allele)
return np.sum(b, axis=axis)
def count_hom_ref(self, axis=None):
"""Count homozygous reference genotypes.
Parameters
----------
axis : int, optional
Axis over which to count, or None to perform overall count.
"""
b = self.is_hom_ref()
return np.sum(b, axis=axis)
def count_hom_alt(self, axis=None):
"""Count homozygous alternate genotypes.
Parameters
----------
axis : int, optional
Axis over which to count, or None to perform overall count.
"""
b = self.is_hom_alt()
return np.sum(b, axis=axis)
def count_het(self, allele=None, axis=None):
"""Count heterozygous genotypes.
Parameters
----------
allele : int, optional
Allele index.
axis : int, optional
Axis over which to count, or None to perform overall count.
"""
b = self.is_het(allele=allele)
return np.sum(b, axis=axis)
def count_call(self, call, axis=None):
"""Count genotypes with a given call.
Parameters
----------
call : array_like, int, shape (ploidy,)
The genotype call to find.
axis : int, optional
Axis over which to count, or None to perform overall count.
"""
b = self.is_call(call=call)
return np.sum(b, axis=axis)
def to_n_ref(self, fill=0, dtype='i1'):
"""Transform each genotype call into the number of
reference alleles.
Parameters
----------
fill : int, optional
Use this value to represent missing calls.
dtype : dtype, optional
Output dtype.
Returns
-------
out : ndarray, int8, shape (n_variants, n_samples)
Array of ref alleles per genotype call.
Notes
-----
By default this function returns 0 for missing genotype calls
**and** for homozygous non-reference genotype calls. Use the
`fill` argument to change how missing calls are represented.
Examples
--------
>>> import allel
>>> g = allel.GenotypeArray([[[0, 0], [0, 1]],
... [[0, 2], [1, 1]],
... [[2, 2], [-1, -1]]])
>>> g.to_n_ref()
array([[2, 1],
[1, 0],
[0, 0]], dtype=int8)
>>> g.to_n_ref(fill=-1)
array([[ 2, 1],
[ 1, 0],
[ 0, -1]], dtype=int8)
>>> v = g[:, 0]
>>> v
<GenotypeVector shape=(3, 2) dtype=int64>
0/0 0/2 2/2
>>> v.to_n_ref()
array([2, 1, 0], dtype=int8)
"""
# count number of alternate alleles
out = np.empty(self.shape[:-1], dtype=dtype)
np.sum(self.values == 0, axis=-1, out=out)
# fill missing calls
if fill != 0:
m = self.is_missing()
out[m] = fill
# handle mask
if self.mask is not None:
out[self.mask] = fill
return out
def to_n_alt(self, fill=0, dtype='i1'):
"""Transform each genotype call into the number of
non-reference alleles.
Parameters
----------
fill : int, optional
Use this value to represent missing calls.
dtype : dtype, optional
Output dtype.
Returns
-------
out : ndarray, int, shape (n_variants, n_samples)
Array of non-ref alleles per genotype call.
Notes
-----
This function simply counts the number of non-reference
alleles, it makes no distinction between different alternate
alleles.
By default this function returns 0 for missing genotype calls
**and** for homozygous reference genotype calls. Use the
`fill` argument to change how missing calls are represented.
Examples
--------
>>> import allel
>>> g = allel.GenotypeArray([[[0, 0], [0, 1]],
... [[0, 2], [1, 1]],
... [[2, 2], [-1, -1]]])
>>> g.to_n_alt()
array([[0, 1],
[1, 2],
[2, 0]], dtype=int8)
>>> g.to_n_alt(fill=-1)
array([[ 0, 1],
[ 1, 2],
[ 2, -1]], dtype=int8)
>>> v = g[:, 0]
>>> v
<GenotypeVector shape=(3, 2) dtype=int64>
0/0 0/2 2/2
>>> v.to_n_alt()
array([0, 1, 2], dtype=int8)
"""
# count number of alternate alleles
out = np.empty(self.shape[:-1], dtype=dtype)
np.sum(self.values > 0, axis=-1, out=out)
# fill missing calls
if fill != 0:
m = self.is_missing()
out[m] = fill
# handle mask
if self.mask is not None:
out[self.mask] = fill
return out
def to_allele_counts(self, | |
<reponame>taechanha/JORLDY<gh_stars>0
from collections import deque
import os
import numpy as np
import torch
import torch.nn.functional as F
from torch.distributions import Normal
from .base import BaseAgent
from core.network import Network
from core.optimizer import Optimizer
from core.buffer import ReplayBuffer
class MPO(BaseAgent):
"""Maximum A Posteriori Policy Optimization (MPO) agent.
Args:
state_size (int): dimension of state.
action_size (int): dimension of action.
hidden_size (int): dimension of hidden unit.
optim_config (dict): dictionary of the optimizer info.
(key: 'name', value: name of optimizer)
actor (str): key of actor network class in _network_dict.txt.
critic (str): key of critic network class in _network_dict.txt.
head (str): key of head in _head_dict.txt.
buffer_size (int): the size of the memory buffer.
batch_size (int): the number of samples in the one batch.
start_train_step (int): steps to start learning.
n_epoch (int): Number of epoch when optimizing the surrogate.
n_step (int): The number of steps to run for each environment per update.
clip_grad_norm (float): gradient clipping threshold.
gamma (float): discount factor.
device (str): device to use.
(e.g. 'cpu' or 'gpu'. None can also be used, and in this case, the cpu is used.)
num_workers: the number of agents in distributed learning.
critic_loss_type (str): type of critic loss. One of ['1step_TD', 'retrace'].
num_sample (int): the number of samples.
min_eta (float): minimum value of eta.
min_alpha_mu (float): minimum value of alpha_mu.
min_alpha_sigma (float): minimum value of alpha_sigma.
eps_eta (float): threshold of temperature loss term.
eps_alpha_mu (float): threshold of mean part of Gaussian-KL constraint term.
eps_alpha_sigma (float): threshold of variance part of Gaussian-KL constraint term.
eta (float): Lagrange multipliers of temperature loss term.
alpha_mu (float): Lagrange multipliers of mean part of Gaussian-KL constraint term (trust-region loss).
alpha_sigma (float): Lagrange multipliers of variance part of Gaussian-KL constraint term.
"""
def __init__(
self,
state_size,
action_size,
hidden_size=512,
optim_config={"name": "adam"},
actor="discrete_policy",
critic="dqn",
head="mlp",
buffer_size=50000,
batch_size=64,
start_train_step=2000,
n_epoch=64,
n_step=8,
clip_grad_norm=1.0,
gamma=0.99,
device=None,
num_workers=1,
# parameters unique to MPO
critic_loss_type="retrace", # one of ['1step_TD', 'retrace']
num_sample=30,
min_eta=1e-8,
min_alpha_mu=1e-8,
min_alpha_sigma=1e-8,
eps_eta=0.01,
eps_alpha_mu=0.01,
eps_alpha_sigma=5 * 1e-5,
eta=1.0,
alpha_mu=1.0,
alpha_sigma=1.0,
**kwargs,
):
self.device = (
torch.device(device)
if device
else torch.device("cuda" if torch.cuda.is_available() else "cpu")
)
self.head = head
self.action_type = actor.split("_")[0]
assert self.action_type in ["continuous", "discrete"]
self.action_size = action_size
self.actor = Network(
actor, state_size, action_size, D_hidden=hidden_size, head=head
).to(self.device)
self.target_actor = Network(
actor, state_size, action_size, D_hidden=hidden_size, head=head
).to(self.device)
self.target_actor.load_state_dict(self.actor.state_dict())
assert critic_loss_type in ["1step_TD", "retrace"]
self.critic_loss_type = critic_loss_type
self.critic = Network(
critic, state_size, action_size, D_hidden=hidden_size, head=head
).to(self.device)
self.target_critic = Network(
critic, state_size, action_size, D_hidden=hidden_size, head=head
).to(self.device)
self.target_critic.load_state_dict(self.critic.state_dict())
self.batch_size = batch_size
self.n_step = n_step if critic_loss_type == "retrace" else 1
self.clip_grad_norm = clip_grad_norm
self.num_learn = 0
self.time_t = 0
self.start_train_step = start_train_step
self.n_epoch = n_epoch
self.num_sample = num_sample
self.min_eta = torch.tensor(min_eta, device=self.device)
self.min_alpha_mu = torch.tensor(min_alpha_mu, device=self.device)
self.min_alpha_sigma = torch.tensor(min_alpha_sigma, device=self.device)
self.eps_eta = eps_eta
self.eps_alpha_mu = eps_alpha_mu
self.eps_alpha_sigma = eps_alpha_sigma
self.eta = torch.nn.Parameter(
torch.tensor(eta, requires_grad=True).to(self.device)
)
self.alpha_mu = torch.nn.Parameter(
torch.tensor(alpha_mu, requires_grad=True).to(self.device)
)
self.alpha_sigma = torch.nn.Parameter(
torch.tensor(alpha_sigma, requires_grad=True).to(self.device)
)
self.reset_lgr_muls()
self.actor_optimizer = Optimizer(
**optim_config,
params=list(self.actor.parameters())
+ [self.eta, self.alpha_mu, self.alpha_sigma],
)
self.critic_optimizer = Optimizer(
**optim_config, params=list(self.critic.parameters())
)
self.gamma = gamma
self.tmp_buffer = deque(maxlen=n_step)
self.memory = ReplayBuffer(buffer_size)
@torch.no_grad()
def act(self, state, training=True):
self.actor.train(training)
if self.action_type == "continuous":
mu, std = self.actor(self.as_tensor(state))
m = Normal(mu, std)
z = m.sample() if training else mu
action = torch.tanh(z)
action = action.data.cpu().numpy()
prob = m.log_prob(z).sum(axis=-1, keepdims=True)
prob = prob.exp().cpu().numpy()
else:
pi = self.actor(self.as_tensor(state))
action = (
torch.multinomial(pi, 1)
if training
else torch.argmax(pi, dim=-1, keepdim=True)
)
action = action.cpu().numpy()
prob = np.take(pi.cpu().numpy(), action)
return {
"action": action,
"prob": prob,
}
def learn(self):
transitions = self.memory.sample(self.batch_size)
for key in transitions.keys():
# reshape: (batch_size, len_tr, item_dim)
# -> (batch_size * len_tr, item_dim)
transitions[key] = self.as_tensor(transitions[key]).view(
-1, *transitions[key].shape[2:]
)
state = transitions["state"]
action = transitions["action"]
reward = transitions["reward"]
next_state = transitions["next_state"]
done = transitions["done"]
prob_b = transitions["prob"]
if self.action_type == "continuous":
mu, std = self.actor(state)
Q = self.critic(state, action)
m = Normal(mu, std)
z = torch.atanh(torch.clamp(action, -1 + 1e-7, 1 - 1e-7))
log_pi = m.log_prob(z)
log_prob = log_pi.sum(axis=-1, keepdims=True)
prob = torch.exp(log_prob)
with torch.no_grad():
mut, stdt = self.target_actor(state)
mt = Normal(mut, stdt)
zt = torch.atanh(torch.clamp(action, -1 + 1e-7, 1 - 1e-7))
log_pit = mt.log_prob(zt)
log_probt = log_pit.sum(axis=-1, keepdims=True)
mu_old = mut
std_old = stdt
prob_t = torch.exp(log_probt)
Qt_a = self.target_critic(state, action)
next_mu, next_std = self.actor(next_state)
mn = Normal(next_mu, next_std)
zn = mn.sample(
(self.num_sample,)
) # (num_sample, batch_size * len_tr, dim_action)
next_action = torch.tanh(zn)
Qt_next = self.target_critic(
next_state.unsqueeze(0).repeat_interleave(self.num_sample, dim=0),
next_action,
) # (num_sample, batch_size * len_tr, 1)
c = torch.clip(prob / (prob_b + 1e-6), max=1.0)
if self.critic_loss_type == "1step_TD":
Qret = reward + self.gamma * (1 - done) * Qt_next.mean(axis=0)
elif self.critic_loss_type == "retrace":
Qret = reward + self.gamma * Qt_next.mean(axis=0) * (1 - done)
# temporarily reshaping values
# (batch_size * len_tr, item_dim) -> (batch_size, len_tr, item_dim)
Qret = Qret.view(self.batch_size, -1, *Qret.shape[1:])
Qt_a = Qt_a.view(self.batch_size, -1, *Qt_a.shape[1:])
c = c.view(self.batch_size, -1, *c.shape[1:])
done = done.view(self.batch_size, -1, *done.shape[1:])
for i in reversed(range(Qret.shape[1] - 1)):
Qret[:, i] += (
self.gamma
* c[:, i + 1]
* (1 - done[:, i])
* (Qret[:, i + 1] - Qt_a[:, i + 1])
)
Qret = Qret.view(-1, *Qret.shape[2:])
zt_add = mt.sample(
(self.num_sample,)
) # (num_sample, batch_size * len_tr, dim_action)
action_add = torch.tanh(zt_add)
log_pi_add = m.log_prob(zt_add)
log_prob_add = log_pi_add.sum(axis=-1, keepdims=True)
Qt_add = self.target_critic(
state.unsqueeze(0).repeat_interleave(self.num_sample, dim=0), action_add
)
critic_loss = F.mse_loss(Q, Qret).mean()
# Calculate Vt_add, At_add using Qt_add
Vt_add = torch.mean(Qt_add, axis=0, keepdims=True)
At_add = Qt_add - Vt_add
At = At_add
""" variational distribution q uses exp(At / eta) instead of exp(Qt / eta), for stable learning"""
q = torch.softmax(At_add / self.eta, axis=0)
actor_loss = -torch.mean(torch.sum(q.detach() * log_prob_add, axis=0))
eta_loss = self.eta * self.eps_eta + self.eta * torch.mean(
torch.log(torch.exp((At_add) / self.eta).mean(axis=0))
)
ss = 1.0 / (std ** 2) # (batch_size * len_tr, action_dim)
ss_old = 1.0 / (std_old ** 2)
"""
KL-Divergence losses(related to alpha) implemented using methods introduced from V-MPO paper
https://arxiv.org/abs/1909.12238
"""
# mu
d_mu = mu - mu_old.detach() # (batch_size * len_tr, action_dim)
KLD_mu = 0.5 * torch.sum(d_mu * 1.0 / ss_old.detach() * d_mu, axis=-1)
mu_loss = torch.mean(
self.alpha_mu * (self.eps_alpha_mu - KLD_mu.detach())
+ self.alpha_mu.detach() * KLD_mu
)
# sigma
KLD_sigma = 0.5 * (
torch.sum(1.0 / ss * ss_old.detach(), axis=-1)
- ss.shape[-1]
+ torch.log(
torch.prod(ss, axis=-1) / torch.prod(ss_old.detach(), axis=-1)
)
)
sigma_loss = torch.mean(
self.alpha_sigma * (self.eps_alpha_sigma - KLD_sigma.detach())
+ self.alpha_sigma.detach() * KLD_sigma
)
alpha_loss = mu_loss + sigma_loss
else:
pi = self.actor(state) # pi,Q: (batch_size, len_tr, dim_action)
pi_next = self.actor(next_state)
Q = self.critic(state)
Q_a = Q.gather(1, action.long())
with torch.no_grad():
# calculate Q_ret using Retrace
Qt = self.target_critic(state) # Q_target
Qt_next = self.target_critic(next_state)
pit = self.target_actor(state)
Qt_a = Qt.gather(1, action.long())
prob_t = pi.gather(
1, action.long()
) # (batch_size * len_tr, 1), target policy probability
c = torch.clip(
prob_t / (prob_b + 1e-6), max=1.0
) # (batch_size * len_tr, 1), prod of importance ratio and gamma
if self.critic_loss_type == "1step_TD":
Qret = reward + self.gamma * (1 - done) * torch.sum(
pi_next * Qt_next, axis=-1, keepdim=True
)
elif self.critic_loss_type == "retrace":
Qret = reward + self.gamma * torch.sum(
pi_next * Qt_next, axis=-1, keepdim=True
) * (1 - done)
# temporarily reshaping values
# (batch_size * len_tr, item_dim) -> (batch_size, len_tr, item_dim)
Qret = Qret.view(self.batch_size, -1, *Qret.shape[1:])
Qt_a = Qt_a.view(self.batch_size, -1, *Qt_a.shape[1:])
c = c.view(self.batch_size, -1, *c.shape[1:])
done = done.view(self.batch_size, -1, *done.shape[1:])
for i in reversed(
range(Qret.shape[1] - 1)
): # along the trajectory length
Qret[:, i] += (
self.gamma
* c[:, i + 1]
* (Qret[:, i + 1] - Qt_a[:, i + 1])
* (1 - done[:, i])
)
Qret = Qret.view(-1, *Qret.shape[2:])
pi_old = pit
critic_loss = F.mse_loss(Q_a, Qret).mean()
# calculate V, Advantage of Qt
Vt = torch.sum(pi_old * Qt, axis=-1, keepdims=True)
At = Qt - Vt
""" variational distribution q uses exp(At / eta) instead of exp(Qt / eta), for stable learning"""
q = torch.softmax(At / self.eta, axis=-1)
actor_loss = -torch.mean(torch.sum(q.detach() * torch.log(pi), axis=-1))
eta_loss = self.eta * self.eps_eta + self.eta * torch.mean(
torch.log(torch.sum(pi_old * torch.exp(At / self.eta), axis=-1))
)
"""
KL-Divergence losses(related | |
as '-c annex.largefiles=' option to all git annex calls
in case largefiles setting is not yet defined in "git attributes"
**kwargs : dict, optional
to be passed into AnnexRepo
"""
if path is None:
path = realpath(curdir)
# TODO: commented out to ease developing for now
# self.repo = _call(AnnexRepo, path, **kwargs)
# TODO: backend -- should be fetched from the config I guess... or should we
# give that duty to the dataset initialization routine to change default backend?
# Well -- different annexifiers might have different ideas for the backend, but
# then those could be overriden via options
if exists(path):
if not exists(opj(path, '.git')):
if (len(listdir(path))) and (not allow_dirty):
raise RuntimeError("Directory %s is not empty." % path)
self.repo = (GitRepo if no_annex else AnnexRepo)(path, always_commit=False, **kwargs)
git_remotes = self.repo.get_remotes()
if special_remotes:
if no_annex: # isinstance(self.repo, GitRepo):
raise ValueError("Cannot have special remotes in a simple git repo")
# TODO: move under AnnexRepo with proper testing etc
repo_info_repos = [v for k, v in self.repo.repo_info().items()
if k.endswith(' repositories')]
annex_remotes = {r['description']: r for r in sum(repo_info_repos, [])}
for remote in special_remotes:
if remote not in git_remotes:
if remote in annex_remotes:
# Already known - needs only enabling
lgr.info("Enabling existing special remote %s" % remote)
self.repo.enable_remote(remote)
else:
init_datalad_remote(self.repo, remote, autoenable=True)
self.mode = mode
self.options = assure_list(options, copy=True)
self.auto_finalize = auto_finalize
self._states = set()
# TODO: may be should be a lazy centralized instance?
self._providers = Providers.from_config_files()
self.yield_non_updated = yield_non_updated
if largefiles:
repo_largefiles = self.repo.get_git_attributes().get('annex.largefiles', None)
if repo_largefiles is not None:
lgr.info(
"Not adding annex.largefiles=%s to git annex calls because "
"already defined to be %s", largefiles, repo_largefiles
)
else:
self.options += ["-c", "annex.largefiles=%s" % largefiles]
if (not allow_dirty) and self.repo.dirty:
raise RuntimeError("Repository %s is dirty. Finalize your changes before running this pipeline" % path)
self.statusdb = statusdb
self._statusdb = None # actual DB to be instantiated later
self.skip_problematic = skip_problematic
# def add(self, filename, url=None):
# # TODO: modes
# self.repo.add_url_to_file(filename, url, batch=True #, TODO backend
# )
# raise NotImplementedError()
#
# def addurl(self, url, filename):
# raise NotImplementedError()
# # TODO: register url within "The DB" after it was added
# self.register_url_in_db(url, filename)
#
def register_url_in_db(self, url, filename):
# might need to go outside -- since has nothing to do with self
raise NotImplementedError()
def reset(self):
if self._statusdb:
self._statusdb.reset()
@staticmethod
def _get_filename_from_url(url):
if url is None:
return None
filename = get_url_straight_filename(url)
# if still no filename
if not filename:
filename = get_url_disposition_filename(url)
if not filename:
raise ValueError("No filename was figured out for %s. "
"Please adjust pipeline to provide one" % url)
return filename
def _get_url_status(self, data, url):
"""A helper to return url_status if url_status is present in data
otherwise request a new one
"""
if 'url_status' in data:
return data['url_status']
else:
downloader = self._providers.get_provider(url).get_downloader(url)
return downloader.get_status(url)
def __call__(self, data): # filename=None, get_disposition_filename=False):
# some checks
assert (self.mode is not None)
stats = data.get('datalad_stats', ActivityStats())
url = data.get('url')
if url:
stats.urls += 1
fpath = self._get_fpath(data, stats, return_None=True)
url_status = None
if url:
try:
url_status = self._get_url_status(data, url)
except Exception:
if self.skip_problematic:
stats.skipped += 1
lgr.debug("Failed to obtain status for url %s" % url)
return
raise
if fpath is None:
# pick it from url_status and give for "reprocessing"
fpath = self._get_fpath(data, stats, filename=url_status.filename)
if not fpath:
if self.skip_problematic:
stats.skipped += 1
lgr.debug("Failed to figure out filename for url %s" % url)
return
raise ValueError("No filename was provided")
filepath = opj(self.repo.path, fpath)
lgr.debug("Request to annex %(url)s to %(fpath)s", locals())
# since filename could have come from url -- let's update with it
updated_data = updated(data, {'filename': ops(fpath)[1],
# TODO? 'filepath': filepath
})
if self.statusdb is not None and self._statusdb is None:
if isinstance(self.statusdb, string_types):
# initiate the DB
self._statusdb = {
'json': JsonFileStatusesDB,
'fileattr': PhysicalFileStatusesDB}[self.statusdb](annex=self.repo)
else:
# use provided persistent instance
self._statusdb = self.statusdb
statusdb = self._statusdb
if url:
if lexists(filepath):
# check if URL provides us updated content. If not -- we should do nothing
# APP1: in this one it would depend on local_status being asked first BUT
# may be for S3 support where statusdb would only record most recent
# modification time
# local_status = self.statusdb.get(fpath)
# remote_status = downloader.get_status(url, old_status=local_status)
# if remote_status == local_status: # WIP TODO not is_status_different(local_status, remote_status):
# APP2: no explicit local_status
# if self.mode != 'full' and fpath == '1-copy.dat':
# import pdb; pdb.set_trace()
# TODO: what if the file came from another url bearing the same mtime and size????
# unlikely but possible. We would need to provide URL for comparison(s)
if self.mode == 'relaxed' or (
statusdb is not None and not statusdb.is_different(fpath, url_status, url)):
# TODO: check if remote_status < local_status, i.e. mtime jumped back
# and if so -- warning or may be according to some config setting -- skip
# e.g. config.get('crawl', 'new_older_files') == 'skip'
lgr.debug("Skipping download. URL %s doesn't provide new content for %s. New status: %s",
url, filepath, url_status)
stats.skipped += 1
if self.yield_non_updated:
yield updated_data # there might be more to it!
return
else:
# just to mark file as still of interest to us so it doesn't get wiped out later
# as it should have happened if we removed creation/tracking of that file intentionally
if statusdb:
statusdb.get(fpath)
if not url:
lgr.debug("Adding %s to annex without url being provided" % filepath)
# so we have only filename
assert fpath
# just add into git directly for now
# TODO: tune add so we could use its json output, and may be even batch it
out_json = _call(self.repo.add, fpath, options=self.options)
# elif self.mode == 'full':
# # since addurl ignores annex.largefiles we need first to download that file and then
# # annex add it
# # see http://git-annex.branchable.com/todo/make_addurl_respect_annex.largefiles_option
# lgr.debug("Downloading %s into %s and adding to annex", url, filepath)
# def _download_and_git_annex_add(url, fpath):
# # Just to feed into _call for dry-run
# filepath_downloaded = downloader.download(url, filepath, overwrite=True, stats=stats)
# assert filepath_downloaded == filepath
# self.repo.add(fpath, options=self.options)
# # and if the file ended up under annex, and not directly under git -- addurl
# # TODO: better function which explicitly checks if file is under annex or either under git
# if self.repo.file_has_content(fpath):
# stats.add_annex += 1
# self.repo.add_url_to_file(fpath, url, batch=True)
# else:
# stats.add_git += 1
# _call(_download_and_git_annex_add, url, fpath)
else:
# !!!! If file shouldn't get under annex due to largefile setting -- we must download it!!!
# TODO: http://git-annex.branchable.com/todo/make_addurl_respect_annex.largefiles_option/#comment-b43ef555564cc78c6dee2092f7eb9bac
# we should make use of matchexpression command, but that might reincarnated
# above code so just left it commented out for now
annex_options = self.options
if self.mode == 'full':
lgr.debug("Downloading %s into %s and adding to annex" % (url, filepath))
else:
annex_options = annex_options + ["--%s" % self.mode]
lgr.debug("Pointing %s to %s within annex in %s mode" % (url, filepath, self.mode))
if lexists(filepath):
lgr.debug("Removing %s since it exists before fetching a new copy" % filepath)
if isdir(filepath):
# if directory - tricky, since we would want then to check if no
# staged changes under
_call(self._check_no_staged_changes_under_dir, filepath, stats=stats)
_call(rmtree, filepath)
else:
_call(unlink, filepath)
_call(stats.increment, 'overwritten')
else:
_call(self._check_non_existing_filepath, filepath, stats=stats)
# TODO: We need to implement our special remote here since no downloaders used
if self.mode == 'full' and url_status and url_status.size: # > 1024**2:
lgr.info("Need to download %s from %s. No progress indication will be reported"
% (naturalsize(url_status.size), url))
try:
out_json = try_multiple(
6, AnnexBatchCommandError, 3, # up to 3**5=243 sec sleep
_call,
self.repo.add_url_to_file, fpath, url,
options=annex_options, batch=True)
except AnnexBatchCommandError as exc:
if self.skip_problematic:
lgr.warning("Skipping %s due to %s", url, exc_str(exc))
return
else:
raise
added_to_annex = 'key' in out_json
if self.mode == 'full' or not added_to_annex:
# we need to adjust our download stats since addurl doesn't do that and we do
# not use our downloaders here
_call(stats.increment, 'downloaded')
_call(stats.increment, 'downloaded_size', _call(lambda: os.stat(filepath).st_size))
# | |
<filename>ro/determinist/algorithms/planner_MILP.py<gh_stars>1-10
# -*- coding: UTF-8 -*-
import math
import os
import time
import numpy as np
import pandas as pd
import gurobipy as gp
from gurobipy import GRB
from ro.utils import dump_file, build_observations, build_point_forecast
from root_project import ROOT_DIR
import matplotlib.pyplot as plt
from ro.ro_simulator_configuration import PARAMETERS
class Planner_MILP():
"""
MILP capacity firming formulation: binary variables to avoid simultaneous charge and discharge.
:ivar nb_periods: number of market periods (-)
:ivar period_hours: period duration (hours)
:ivar soc_ini: initial state of charge (kWh)
:ivar soc_end: final state of charge (kWh)
:ivar deadband_penalty: deadband deviation between production and nomination, % of the total installed capacity (kW)
constant for all market periods
:ivar pv_forecast: PV point forecasts (kW)
:ivar engagement: Nomination to the grid (injection > 0, withdrawal < 0) (kW)
shape = (nb_market periods,)
:ivar df_parameters: pd.DataFrame with price, deadband_nomination, min_nomination, max_nomination, min_production, max_production
shape = (nb_market periods, 6)
:ivar selling_price: selling price (€/ kWh)
different between of-peak and peak hours
:ivar deadband_nomination: deadband between two consecutive nominations, % of the total installed capacity (kW)
different between of-peak and peak hours
shape = (nb_market periods,)
:ivar model: a Gurobi model (-)
"""
def __init__(self, pv_forecast:np.array, engagement:np.array=None):
"""
Init the planner.
"""
self.parameters = PARAMETERS # simulation parameters
self.period_hours = PARAMETERS['period_hours'] # (hour)
self.nb_periods = int(24 / self.period_hours)
self.t_set = range(self.nb_periods)
self.pv_forecast = pv_forecast # (kW)
self.engagement = engagement # (kW)
self.PVcapacity = PARAMETERS['pv_capacity'] # (kWp)
self.tol_penalty = PARAMETERS['tol_penalty'] # (%)
self.deadband_penalty = self.tol_penalty * self.PVcapacity # (kW)
self.penalty_factor = PARAMETERS['penalty_factor'] # penalty factor
self.overproduction = PARAMETERS['OVERPRODUCTION'] # forbid overproduction
if all([item in PARAMETERS['df_params'].columns for item in ['price', 'deadband_nomination', 'min_nomination', 'max_nomination', 'min_production','max_production']]):
self.selling_price = PARAMETERS['df_params']['price'].values # (€/ kWh)
self.deadband_nomination = PARAMETERS['df_params']['deadband_nomination'].values # (kW/period)
self.min_nomination = PARAMETERS['df_params']['min_nomination'].values # (kW)
self.max_nomination = PARAMETERS['df_params']['max_nomination'].values # (kW)
self.min_production = PARAMETERS['df_params']['min_production'].values # (kW)
self.max_production = PARAMETERS['df_params']['max_production'].values # (kW)
else:
print("df_parameters is not ok ")
# BESS parameters
self.BESScapacity = PARAMETERS['BESS']['BESS_capacity'] # (kWh)
self.soc_ini = PARAMETERS['BESS']['soc_ini'] # (kWh)
self.soc_end = PARAMETERS['BESS']['soc_end'] # (kWh)
self.soc_min = PARAMETERS['BESS']['soc_min'] # (kWh)
self.soc_max = PARAMETERS['BESS']['soc_max'] # (kWh)
self.charge_eff = PARAMETERS['BESS']['charge_eff'] # (/)
self.discharge_eff = PARAMETERS['BESS']['discharge_eff'] # (/)
self.charge_power = PARAMETERS['BESS']['charge_power'] # (kW)
self.discharge_power = PARAMETERS['BESS']['discharge_power'] # (kW)
self.high_soc_price = PARAMETERS['BESS']['HIGH_SOC_PRICE'] # (euros/kWh) -> fictive price to incentivize to charge BESS
self.time_building_model = None
self.time_solving_model = None
# Create model
self.model = self.create_model()
# Solve model
self.solver_status = None
def create_model(self):
"""
Create the optimization problem.
"""
t_build = time.time()
# -------------------------------------------------------------------------------------------------------------
# 1. create model
model = gp.Model("planner_MILP_gurobi")
# -------------------------------------------------------------------------------------------------------------
# 2. create variables
# 2.1 First-stage variables -> x
x = model.addVars(self.nb_periods, lb=-GRB.INFINITY, ub=GRB.INFINITY, obj=0, vtype=GRB.CONTINUOUS, name="x") # Nomination at the grid coupling point (injection > 0, withdrawal < 0) (kW)
if self.engagement is not None:
for i in self.t_set:
x[i].setAttr("ub", self.engagement[i])
x[i].setAttr("lb", self.engagement[i])
# 2.2 Second-stage variables -> y
y_prod = model.addVars(self.nb_periods, lb=-GRB.INFINITY, ub=GRB.INFINITY, obj=-0, vtype=GRB.CONTINUOUS, name="y_prod") # Production at the grid coupling point (injection > 0, withdrawal < 0) (kW)
y_short_dev = model.addVars(self.nb_periods, lb=0, ub=GRB.INFINITY, obj=0, vtype=GRB.CONTINUOUS, name="y_short_dev") # y_short_dev >= - (y_prod - x-) with x- = x - deadband_deviation_kW
y_long_dev = model.addVars(self.nb_periods, lb=0, ub=GRB.INFINITY, obj=0, vtype=GRB.CONTINUOUS, name="y_long_dev") # y_long_dev >= - (x+ - y_prod) with x+ = x + deadband_deviation_kW
y_s = model.addVars(self.nb_periods, lb=0, ub=GRB.INFINITY, obj=0, vtype=GRB.CONTINUOUS, name="y_s") # State of charge of the battery (kWh)
y_charge = model.addVars(self.nb_periods, lb=0, ub=GRB.INFINITY, obj=0, vtype=GRB.CONTINUOUS, name="y_charge") # Charging power (kW)
y_discharge = model.addVars(self.nb_periods, lb=0, ub=GRB.INFINITY, obj=0, vtype=GRB.CONTINUOUS, name="y_discharge") # Discharging power (kW)
y_PV = model.addVars(self.nb_periods, lb=0, ub=GRB.INFINITY, obj=0, vtype=GRB.CONTINUOUS, name="y_PV") # PV generation (kW)
y_b = model.addVars(self.nb_periods, obj=0, vtype=GRB.BINARY, name="y_b") # binary variable -> y_b = 1 -> charge / y_b = 0 -> discharge
# -------------------------------------------------------------------------------------------------------------
# 3. create objective
objective = gp.quicksum(self.period_hours * self.selling_price[i] * (-y_prod[i] + self.penalty_factor * (y_short_dev[i] + y_long_dev[i])) - self.high_soc_price * y_s[i] for i in self.t_set)
model.setObjective(objective, GRB.MINIMIZE)
# -------------------------------------------------------------------------------------------------------------
# 4. create constraints
# 4.1 First stage constraints
# engagement min cst
model.addConstrs((x[i] >= self.min_nomination[i] for i in self.t_set), name='c_xmin')
# engagement max cst
model.addConstrs((x[i] <= self.max_nomination[i] for i in self.t_set), name='c_xmax')
# engagement ramping constraint up -> skip first period -> nb periods -1 constraints
model.addConstrs((x[i] - x[i - 1] <= self.deadband_nomination[i] for i in range(1, self.nb_periods)), name='c_x_rampingUp')
# engagement ramping constraint down -> skip first period -> nb periods -1 constraints
model.addConstrs((x[i - 1] - x[i] <= self.deadband_nomination[i] for i in range(1, self.nb_periods)), name='c_x_rampingDown')
# 4.2 Second-stage constraints
# max charge cst
model.addConstrs((y_charge[i] <= y_b[i] * self.charge_power for i in self.t_set), name='c_max_charge')
# max discharge cst
model.addConstrs((y_discharge[i] <= (1 - y_b[i]) * self.discharge_power for i in self.t_set), name='c_max_discharge')
# min soc cst
model.addConstrs((y_s[i] >= self.soc_min for i in self.t_set), name='c_min_s')
# min soc cst
model.addConstrs((y_s[i] <= self.soc_max for i in self.t_set), name='c_max_s')
# power balance equation
model.addConstrs((y_prod[i] - y_PV[i] - (y_discharge[i] - y_charge[i]) == 0 for i in self.t_set), name='c_power_balance_eq')
# min production
model.addConstrs((y_prod[i] >= self.min_production[i] for i in self.t_set), name='c_min_y_prod')
# max production
model.addConstrs((y_prod[i] <= self.max_production[i] for i in self.t_set), name='c_max_y_prod')
if self.overproduction:
# forbid overproduction
model.addConstrs((y_prod[i] <= (x[i] + self.deadband_penalty) for i in self.t_set), name='c_over_prod')
# BESS dynamics first period
model.addConstr((y_s[0] - self.period_hours * (self.charge_eff * y_charge[0] - y_discharge[0] / self.discharge_eff) == self.soc_ini), name='c_BESS_first_period')
# BESS dynamics from second to last periods
model.addConstrs((y_s[i] - y_s[i-1]- self.period_hours * (self.charge_eff * y_charge[i] - y_discharge[i] / self.discharge_eff) == 0 for i in range(1, self.nb_periods)), name='c_BESS_dynamics')
# BESS dynamics last period
model.addConstr((y_s[self.nb_periods-1] == self.soc_end ), name='c_BESS_last_period')
# Short penalty cst
model.addConstrs((y_short_dev[i] >= (x[i] - self.deadband_penalty) - y_prod[i] for i in self.t_set), name='c_short_penalty')
# Long penalty cst
model.addConstrs((y_long_dev[i] >= y_prod[i] - (x[i] + self.deadband_penalty) for i in self.t_set), name='c_long_penalty')
# PV generation cst
model.addConstrs((y_PV[i] <= self.pv_forecast[i] for i in self.t_set), name='c_PV_generation')
# -------------------------------------------------------------------------------------------------------------
# 5. Store variables
self.allvar = dict()
self.allvar['x'] = x
self.allvar['y_prod'] = y_prod
self.allvar['y_short_dev'] = y_short_dev
self.allvar['y_long_dev'] = y_long_dev
self.allvar['y_s'] = y_s
self.allvar['y_charge'] = y_charge
self.allvar['y_discharge'] = y_discharge
self.allvar['y_PV'] = y_PV
self.allvar['y_b'] = y_b
self.time_building_model = time.time() - t_build
# print("Time spent building the mathematical program: %gs" % self.time_building_model)
return model
def solve(self, LogToConsole:bool=False, logfile:str="", Threads:int=0, MIPFocus:int=0, TimeLimit:float=GRB.INFINITY):
t_solve = time.time()
self.model.setParam('LogToConsole', LogToConsole) # no log in the console if set to False
# self.model.setParam('OutputFlag', outputflag) # no log into console and log file if set to True
# self.model.setParam('MIPGap', 0.01)
self.model.setParam('TimeLimit', TimeLimit)
self.model.setParam('MIPFocus', MIPFocus)
# self.model.setParam('DualReductions', 0) # Model was proven to be either infeasible or unbounded. To obtain a more definitive conclusion, set the DualReductions parameter to 0 and reoptimize.
# If you are more interested in good quality feasible solutions, you can select MIPFocus=1.
# If you believe the solver is having no trouble finding the optimal solution, and wish to focus more attention on proving optimality, select MIPFocus=2.
# If the best objective bound is moving very slowly (or not at all), you may want to try MIPFocus=3 to focus on the bound.
self.model.setParam('LogFile', logfile) # no log in file if set to ""
self.model.setParam('Threads', Threads) # Default value = 0 -> use all threads
self.model.optimize()
self.solver_status = self.model.status
self.time_solving_model = time.time() - t_solve
def store_solution(self):
m = self.model
solution = dict()
solution['status'] = m.status
if solution['status'] == 2 or solution['status'] == 9:
solution['obj'] = m.objVal
# 1 dimensional variables
for var in ['x', 'y_prod', 'y_short_dev', 'y_long_dev', 'y_s', 'y_charge', 'y_discharge', 'y_PV', 'y_b']:
solution[var] = [self.allvar[var][t].X for t in self.t_set]
else:
print('WARNING planner MILP status %s -> problem not solved, objective is set to nan' %(solution['status']))
solution['obj'] = math.nan
# 3. Timing indicators
solution["time_building"] = self.time_building_model
solution["time_solving"] = self.time_solving_model
solution["time_total"] = self.time_building_model + self.time_solving_model
return solution
def export_model(self, filename):
"""
Export the pyomo model into a cpxlp format.
:param filename: directory and filename of the exported model.
"""
self.model.write("%s.lp" % filename)
# self.model.write("%s.mps" % filename)
# Validation set
VS = 'VS1' # 'VS1', 'VS2
if __name__ == "__main__":
# Set the working directory to the root of the project
print(os.getcwd())
os.chdir(ROOT_DIR)
print(os.getcwd())
dirname = 'ro/determinist/export/'
# load data
pv_solution = build_observations()
pv_dad = build_point_forecast()
# Select | |
#!/usr/bin/env python
# @HEADER
# ************************************************************************
#
# TriBITS: Tribal Build, Integrate, and Test System
# Copyright 2013 Sandia Corporation
#
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. 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.
#
# 3. Neither the name of the Corporation nor the names of the
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
# 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.
#
# ************************************************************************
# @HEADER
#
# General scripting support
#
# NOTE: Included first to check the version of python!
#
from GeneralScriptSupport import *
from CMakeBinaries import *
import glob
import re
import shutil
import string
import subprocess
import sys
import tarfile
import urllib
import zipfile
import socket
#
# Discover domain (detect if in .sandia.gov) if possible.
# Use it to set default_http_proxy value appropriately.
#
default_http_proxy = ""
hostname = ""
hostname = socket.getfqdn()
if hostname != '':
hostname = hostname.strip()
hostname = hostname.lower()
if hostname[-11:] == ".sandia.gov":
default_http_proxy = "http://wwwproxy.sandia.gov:80/"
#
# Detailed documentation
#
usageHelp = r"""download-cmake.py [--install-dir=$HOME/cmake ...]
Script that downloads and installs one of the verified versions of CMake for
building Trilinos. The verified versions of CMake and their available
installers are indicated by the files CMakeVersions.py and CMakeBinaries.py.
There are multiple verified versions: you can choose which one you want to use
by passing the --installer-type argument to this script.
Valid values for --installer-type are:
'min' - minimum required version of CMake that can build Trilinos
'release' - default / recommended version, may be same as min
'rc' - latest release candidate, may be same as release
'dev' - latest development build
If your computer is in the sandia.gov domain, this script should automatically
detect that and use the correct value for --http-proxy to enable downloading
files from the web with http. If you need to pass a proxy in manually, pass
the fully qualified form, as in: --http-proxy="http://wwwproxy.sandia.gov:80/"
If you do not specify an --http-proxy and one is not automatically set due to
sandia.gov domain detection, then the http_proxy environment variable is
honored.
By default, if you just type:
$ SOME_DIR/download-cmake.py
then the directory download_area will get created in the local working
directory. It will contain the extracted install tree of a pre-built
binary CMake suitable for this platform. That extracted install tree may
be used directly from the download_area directory, or you may move or
copy it to any location of your choosing.
This script will also pull down the list of available installers from the CMake
web site and detect the latest available installer for the v2.8 and development
builds. After running the detection phase of the script, a new CMakeVersions.py
is written in the download_area directory. Periodically as needed, this
generated CMakeVersions.py should be committed as the official CMakeVersions.py
file in the same directory with this script.
You can control various parts of the process with the options (see below). Call
this script with -h or --help for a list of possible options.
Example using the --install-dir option:
$ SOME_DIR/download-cmake.py --install-dir=$HOME/cmake
This usage would install CMake and the other executables in $HOME/cmake/bin.
NOTE: You will have to update your PATH variable to include whatever directory
you choose to install CMake in.
NOTE: If you need to use sudo to install in some place that requires root
privileges, or if you need to install to a directory that already exists, do:
$ ./download-cmake.py --skip-install [other options]
$ cd download_area
$ sudo cp -r cmake-2.8.0-Linux-i386/ /usr/local
Alternatively, if you have sudo access you can do the install in one shot as:
$ sudo ./download-cmake.py --install-dir=/usr/local
After you have done a successful install, you may remove the downloaded files:
$ rm -r download_area
Enjoy CMake!
"""
#
# Read in the commandline arguments
#
from optparse import OptionParser
clp = OptionParser(usage=usageHelp)
if sys.platform == 'darwin':
defInstallDir = "/Applications"
defSymlinksDir = "/usr/local/bin"
else:
defInstallDir = "/usr/local"
defSymlinksDir = ""
clp.add_option(
"--all-platforms", dest="allPlatforms", action="store_true", default=False,
help="Download and/or extract tarballs for all platforms (default = just this platform)" )
clp.add_option(
"--http-proxy", dest="httpProxy", type="string", default=default_http_proxy,
help="Proxy in the form 'http://server:port/' - use if you are behind a firewall with respect to downloading from http://www.cmake.org (default = \""+default_http_proxy+"\")." )
clp.add_option(
"--install-dir", dest="installDir", type="string", default=defInstallDir,
help="The install directory for CMake (default = "+defInstallDir+"." )
clp.add_option(
"--installer-type", dest="installerType", type="string", default="release",
help="Which CMake installer: min, release, rc, or dev (default = release)." )
clp.add_option(
"--skip-detect", dest="skipDetect", action="store_true", default=False,
help="Skip detecting the latest available builds" )
clp.add_option(
"--skip-download", dest="skipDownload", action="store_true", default=False,
help="Skip the download step" )
clp.add_option(
"--skip-extract", dest="skipExtract", action="store_true", default=False,
help="Skip the extract step" )
clp.add_option(
"--skip-install", dest="skipInstall", action="store_true", default=False,
help="Skip the install step" )
clp.add_option(
"--symlinks", dest="symlinks", action="store_true", default=False,
help="Create symlinks to the installed CMake executables in --symlinks-dir" )
clp.add_option(
"--symlinks-dir", dest="symlinksDir", type="string", default=defSymlinksDir,
help="The directory in which to create symlinks to CMake executables (default = "+defSymlinksDir+")." )
(options, args) = clp.parse_args()
# "Latest available CMake build" is defined as the most recent build on the
# server in vdir with pre-built binary tarballs available for Mac, Linux and
# Windows.
#
def DetectLatestCMakeBuilds(basedir, baseurl, vdir):
url = ''.join([baseurl, "/", vdir, "/?C=M;O=D"])
filename = ''.join([basedir, "/CMake_", vdir, ".html"])
try:
createDir(basedir)
except:
if not os.path.exists(basedir):
raise
print("Querying " + url + "...")
proxies = None # if None, use proxy from env var http_proxy
if not options.httpProxy == "":
proxies = {'http': options.httpProxy}
opener = urllib.FancyURLopener(proxies=proxies)
opener.retrieve(url, filename)
print("Detecting ...")
lines = []
regex = re.compile(
"href.*cmake-[0-9.]+(-rc[0-9]+)*(-g[0-9a-fA-F]+)*-(Darwin-universal.tar.gz|Linux-i386.tar.gz|win32-x86.zip)"
)
f = open(filename)
alllines = f.readlines()
for line in alllines:
if regex.search(line):
lines.append(line)
count = 0
found = 0
version_iterator = ""
versionRegEx = re.compile(r'.*-([0-9.]+-rc[0-9]+|[0-9.]+-g[0-9a-fA-F]+|[0-9.]+)-.*')
dateRegEx = re.compile(r'^[0-9].[0-9].([0-9.]+-rc[0-9]+|[0-9.]+-g[0-9a-fA-F]+|[0-9.]+)$')
hrefRegEx = re.compile(r'^.*href="([^"]+)".*$')
for line in lines:
version = versionRegEx.match(line).group(1)
if version == "" or version == line:
print("error: line does not match version extraction regex")
print(" line: [" + line + "]")
sys.exit(1)
date = dateRegEx.match(version).group(1)
# l, m, w == found an installer for Linux, Mac, Windows respectively
# When encountering a new version, reset back to zeroes...
#
if(version_iterator != version):
version_iterator = version
l = 0
m = 0
w = 0
lhref = ""
mhref = ""
whref = ""
href = hrefRegEx.match(line).group(1)
if re.search('Linux', line) != None:
lhref = href
l = 1
elif re.search('Darwin', line) != None:
mhref = href
m = 1
elif re.search('win32', line) != None:
whref = href
w = 1
else:
print("error: unexpected non-matching line")
sys.exit(1)
count = count + 1
if l == 1 and m == 1 and w == 1:
found = 1
print("Detected latest available CMake " + vdir + " build: " + version)
break
if not found:
print("error: could not find a " + vdir + " version with all 3 platforms available")
return ()
return (('linux2', lhref, version), ('darwin', mhref, version), ('win32', whref, version))
def Download(basedir, url):
cmps = url.rsplit("/", 1)
href = cmps[1]
filename = ''.join([basedir, "/", href])
print('Downloading ' + href + '...')
try:
createDir(basedir)
except:
if not os.path.exists(basedir):
raise
proxies = None # if None, use proxy from env var http_proxy
if not options.httpProxy == "":
proxies = {'http': options.httpProxy}
opener = urllib.FancyURLopener(proxies=proxies)
opener.retrieve(url, filename)
def Extract(basedir, url):
cmps = url.rsplit("/", 1)
href = cmps[1]
filename = ''.join([basedir, "/", href])
print('Extracting ' + href + '...')
if href[-4:] == ".zip":
| |
changer does not suppor this operation.")
# It is possible that the following code does work. However, the
# error messages should be changed from STK to IBM if that is
# the case.
"""
__pychecker__ = "unusednames=i"
#do drive cleaning cycle
Trace.log(e_errors.INFO, 'mc:ticket='+repr(inTicket))
classTicket = { 'mcSelf' : self }
try:
drive = inTicket['moverConfig']['mc_device']
except KeyError:
Trace.log(e_errors.ERROR, 'mc:no device field found in ticket.')
status = 37
return e_errors.DOESNOTEXIST, status, "no device field found in ticket"
driveType = drive[:2] # ... need device type, not actual device
try:
if self.driveCleanTime:
cleanTime = self.driveCleanTime[driveType][0] # clean time in seconds
driveCleanCycles = self.driveCleanTime[driveType][1] # number of cleaning cycles
else:
cleanTime = 60
driveCleanCycles = 1
except KeyError:
cleanTime = 60
driveCleanCycles = 1
vcc = volume_clerk_client.VolumeClerkClient(self.csc)
min_remaining_bytes = 1
vol_veto_list = []
first_found = 0
libraryManagers = inTicket['moverConfig']['library']
if type(libraryManagers) == types.StringType:
lm = libraryManagers
library = string.split(libraryManagers,".")[0]
elif type(libraryManagers) == types.ListType:
lm = libraryManagers[0]
library = string.split(libraryManagers[0],".")[0]
else:
Trace.log(e_errors.ERROR, 'mc: library_manager field not found in ticket.')
status = 37
return e_errors.DOESNOTEXIST, status, "no library_manager field found in ticket"
lm_info = self.csc.get(lm)
if not lm_info.has_key('CleanTapeVolumeFamily'):
Trace.log(e_errors.ERROR, 'mc: no CleanTapeVolumeFamily field found in ticket.')
status = 37
return e_errors.DOESNOTEXIST, status, "no CleanTapeVolumeFamily field found in ticket"
cleanTapeVolumeFamily = lm_info['CleanTapeVolumeFamily']
v = vcc.next_write_volume(library,
min_remaining_bytes, cleanTapeVolumeFamily,
vol_veto_list, first_found, exact_match=1) # get which volume to use
if v["status"][0] != e_errors.OK:
Trace.log(e_errors.ERROR,"error getting cleaning volume:%s %s"%
(v["status"][0],v["status"][1]))
status = 37
return v["status"][0], 0, v["status"][1]
for i in range(driveCleanCycles):
Trace.log(e_errors.INFO, "STK clean drive %s, vol. %s"%(drive,v['external_label']))
#rt = self.load(v['external_label'], drive, v['media_type'])
rt = self.retry_function(self.mount, v['external_label'],
drive, v['media_type'])
status = rt[0]
if status != e_errors.OK: # mount returned error
return status, 0, None
time.sleep(cleanTime) # wait cleanTime seconds
#rt = self.unload(v['external_label'], drive, v['media_type'])
rt = self.retry_function(self.dismount, v['external_label'],
drive, v['media_type'])
status = rt[0]
if status != e_errors.OK:
return status, 0, None
Trace.log(e_errors.INFO,"STK Clean returned %s"%(rt,))
retTicket = vcc.get_remaining_bytes(v['external_label'])
remaining_bytes = retTicket['remaining_bytes']-1
vcc.set_remaining_bytes(v['external_label'],remaining_bytes,'\0', None)
return (e_errors.OK, 0, None)
"""
def query_robot(self, ticket):
__pychecker__ = "no-argsused" # When fixed remove this pychecker line.
return (e_errors.NOT_SUPPORTED, 0,
"IBM media changer does not suppor this operation.")
def listDrives(self, ticket):
# build the command, and what to look for in the response
command = "/usr/bin/smc -h %s -l %s -q D" % (self.rmchost, self.device,)
#answer_lookfor = ""
# execute the command and read the response
# FIXME - what if this hangs?
# efb (dec 22, 2005) - up timeout from 10 to 60 as the queries are hanging
#status,response, delta = self.timed_command(command,4,10)
status,response, delta = self.timed_command(command,2,60)
if status != 0:
E=4
msg = "QUERY_DRIVE %i: %s => %i,%s" % (E,command,status,response)
Trace.log(e_errors.ERROR, msg)
return ("ERROR", E, response, "", msg)
drive_list = []
for line in response:
if len(line) > 1:
rc = line.split()
name = rc[0]
state = "N/A"
status = rc[2]
if status.find("loaded") != -1:
volume = rc[3]
else:
volume = ""
drive_type = "LTO3"
drive_list.append({"name" : name,
"state" : state,
"status" : status,
"volume" : volume,
"type" : drive_type,
})
ticket['drive_list'] = drive_list
return (e_errors.OK, 0, None, "", "")
def listVolumes(self, ticket):
#When implementing this function, remember to set ticket['no_reply']
# to 1 to prevent WorkDone() from sending the reponse again.
__pychecker__ = "no-argsused" # When fixed remove this pychecker line.
return (e_errors.NOT_SUPPORTED, 0,
"IBM media changer does not support this operation.")
def list_volumes2(self, ticket):
ticket['work'] = "list_volumes" #Use old method for IBM.
ticket['function'] = "listVolume"
return self.listVolumes(ticket)
def listClean(self, ticket):
#When implementing this function, remember to set ticket['no_reply']
# to 1 to prevent WorkDone() from sending the reponse again.
__pychecker__ = "no-argsused" # When fixed remove this pychecker line.
return (e_errors.NOT_SUPPORTED, 0,
"IBM media changer does not support this operation.")
def listSlots(self, ticket):
__pychecker__ = "no-argsused" # When fixed remove this pychecker line.
return (e_errors.NOT_SUPPORTED, 0,
"IBM media changer does not support this operation.")
#########################################################################
# These functions are internal functions specific to IBM media changer.
#########################################################################
def query(self, volume, media_type=""):
__pychecker__ = "unusednames=media_type"
# build the command, and what to look for in the response
#command = "query vol %s" % (volume,)
#answer_lookfor = "%s " % (volume,)
command = "/usr/bin/smc -h %s -l %s -q V -V '%s'" % (self.rmchost,self.device,volume,)
answer_lookfor = "%s" % (volume,)
# execute the command and read the response
# efb (dec 22, 2005) - up timeout from 10 to 60 as the queries are hanging
#status,response, delta = self.timed_command(command,4,10)
status,response, delta = self.timed_command(command,1,60)
if status != 0:
E=1
msg = "QUERY %i: %s => %i,%s" % (E,command,status,response)
Trace.log(e_errors.ERROR, msg)
return ("ERROR", E, response, '', msg)
# got response, parse it and put it into the standard form
answer = string.strip(response[0])
if string.find(answer, answer_lookfor,0) != 0:
E=2
msg = "QUERY %i: %s => %i,%s" % (E,command,status,response)
Trace.log(e_errors.ERROR, msg)
return ("ERROR", E, response, '', msg)
elif string.find(answer,'slot') != -1:
msg = "%s => %i,%s" % (command,status,answer)
Trace.log(e_errors.INFO, msg)
return (e_errors.OK,0,answer, 'O', msg) # occupied
elif string.find(answer,'drive') != -1:
msg = "%s => %i,%s" % (command,status,answer)
Trace.log(e_errors.INFO, msg)
return (e_errors.OK,0,answer, 'M', msg) # mounted
else:
E=3
msg = "QUERY %i: %s => %i,%s" % (E,command,status,response)
Trace.log(e_errors.ERROR, msg)
return ("ERROR", E, answer, '', msg)
def query_drive(self,drive):
# build the command, and what to look for in the response
#command = "query drive %s" % (drive,)
#answer_lookfor = "%s " % (drive,)
command = "/usr/bin/smc -h %s -l %s -q D -D %s" % (self.rmchost, self.device, drive,)
answer_lookfor = "%s" % (drive,)
# execute the command and read the response
# FIXME - what if this hangs?
# efb (dec 22, 2005) - up timeout from 10 to 60 as the queries are hanging
#status,response, delta = self.timed_command(command,4,10)
status,response, delta = self.timed_command(command,1,60)
if status != 0:
E=4
msg = "QUERY_DRIVE %i: %s => %i,%s" % (E,command,status,response)
Trace.log(e_errors.ERROR, msg)
return ("ERROR", E, response, '', msg)
# got response, parse it and put it into the standard form
answer = string.strip(response[0])
answer = string.replace(answer,', ',',') # easier to part drive id
if string.find(answer, answer_lookfor,0) != 0:
E=5
msg = "QUERY_DRIVE %i: %s => %i,%s" % (E,command,status,answer)
Trace.log(e_errors.ERROR, msg)
return ("ERROR", E, answer, '', msg)
# elif string.find(answer,' online ') == -1:
# E=6
# msg = "QUERY_DRIVE %i: %s => %i,%s" % (E,command,status,answer)
# Trace.log(e_errors.ERROR, msg)
# return ("ERROR", E, answer, '', msg)
elif string.find(answer,'free') != -1:
msg = "%s => %i,%s" % (command,status,answer)
Trace.log(e_errors.INFO, msg)
return (e_errors.OK,0,answer, '', msg) # empty
elif string.find(answer,'loaded') != -1:
loc = string.find(answer,'loaded')
volume = string.split(answer[loc+7:])[0]
msg = "%s => %i,%s" % (command,status,answer)
Trace.log(e_errors.INFO, msg)
return (e_errors.OK,0,answer, volume, msg) # mounted
else:
E=7
msg = "QUERY_DRIVE %i: %s => %i,%s" % (E,command,status,answer)
Trace.log(e_errors.ERROR, msg)
return ("ERROR", E, answer, '', msg)
def mount(self,volume, drive, media_type="",view_first=1):
# build the command, and what to look for in the response
# smc command is mute on success, and only says something on failure
command = "/usr/bin/smc -h %s -l %s -m -D %s -V %s" % \
(self.rmchost, self.device, drive, volume)
# check if tape is in the storage location or somewhere else
if view_first:
status,stat,response,attrib,com_sent = self.query(volume, media_type)
if stat!=0:
E=e_errors.MC_FAILCHKVOL
msg = "MOUNT %i: %s => %i,%s" % (E,command,stat,response)
Trace.log(e_errors.ERROR, msg)
return ("ERROR", E, response, "", msg)
if attrib != "O": # look for tape in tower (occupied="O")
E=e_errors.MC_VOLNOTHOME
msg = "MOUNT %i: Tape is not in home position. %s => %s,%s" % (E,command,status,response)
Trace.log(e_errors.ERROR, msg)
return ("ERROR", E, response, "", msg)
# check if any tape is mounted in this drive
status,stat,response,volser,com_sent = self.query_drive(drive)
if stat!=0:
E=e_errors.MC_FAILCHKDRV
msg = "MOUNT %i: %s => %i,%s" % (E,command,stat,response)
Trace.log(e_errors.ERROR, msg)
return ("ERROR", E, response, "", msg)
if volser != "": # look for any tape mounted in this drive
E=e_errors.MC_DRVNOTEMPTY
msg = "MOUNT %i: Drive %s is not empty =>. %s => %s,%s" % (E,drive,command,status,response)
Trace.log(e_errors.ERROR, msg)
return ("ERROR", E, response, "", msg)
# execute the command and read the response
status,response, delta = self.timed_command(command,1,60*10)
if status != 0:
E=12
msg = "MOUNT %i: %s => %i,%s" % (E,command,status,response)
| |
import sys
import os
import subprocess
import asyncio
import time
import json
import websockets
import threading
import queue
import gi
gi.require_version('WebKit2', '4.0')
from gi.repository import Gdk, WebKit2, Gtk
from gi.repository import GObject
import sqlite3
from diode.db_scripts.sql_to_json import MetaFetcher
from dace.codegen.instrumentation.papi import PAPIInstrumentation
class RenderedGraphHTML5:
""" HTML5-based SDFG renderer. """
def __init__(self, on_click):
self.drawing_area = None
self.on_click_cb = on_click
self.websocket = None
self.sdfg = None
self.render_queue = []
self.restore_render_queue = [] # Render queue copy
self.command_queue = [
] # Similar to render_queue, but for everything except SDFGs.
self.command_queue_roofline = []
self.comm_queue_lock_roofline = threading.Lock()
self.restore_command_queue = [] # Command queue copy
threading.Thread(target=self.run_asyncio, daemon=True).start()
threading.Thread(target=self.run_asyncio_roofline, daemon=True).start()
self.comm_queue_lock = threading.Lock()
self.db_request_queue = queue.Queue()
self.max_db_request_threads = 3 # Sets the amount of threads that may be committed to serve performance results.
def wrapper():
self.async_request_handler()
threading.Thread(target=wrapper, daemon=True).start()
# data_source determines if data should be rendered from canned data or fresh data.
self.data_source = "fresh" # Normally, use results directly from the full results
self.canned_data_programid = None
def set_click_cb(self, func):
self.on_click_cb = func
def center_highlights(self):
# TODO
return
def save_buttons(self, default_name="recorded_"):
""" Request the remote to download a summary file once all data is present """
self.add_to_command_queue(
'{ "type": "save-images", "name": "%s" }' % default_name)
# The following functions highlight nodes
def get_element_by_id(self, id):
return id
def highlight_element(self, elem):
state, node = elem.split('_')
state = state[1:] # strip the 's' from the state number.
self.command_queue.append(
'{ "type": "highlight-element", "node-id": %d, "sdfg-id": %d }' %
(int(node), int(state)))
return
def clear_highlights(self):
self.command_queue.append('{ "type": "clear-highlights" }')
return
def open_canned_data(self, can_path, forProgramID=1):
if can_path is None or can_path == "":
raise ValueError("Cannot open can from path " + str(can_path))
# Just set the data source accordingly
self.data_source = can_path
# Open the database
with sqlite3.connect(can_path) as conn:
c = conn.cursor()
# Read and draw the SDFG with the lowest index
c.execute(
"""
SELECT
forProgramID, json
FROM
`SDFGs`
WHERE
forProgramID = ?
""", (forProgramID, ))
f = c.fetchall()
if len(f) == 0:
# No sdfg has been found in the CAN
raise ValueError(
"The file specified is corrupted or contains no valid data"
)
# Extract the json data
forProgramID, sdfg_json = f[0]
# Call for a rendering (will clear other pending data)
self.render_sdfg(sdfg_json)
# Now request drawing of the selected programID as well
self.render_performance_data(
mode="all",
data_source_path=self.data_source,
forProgramID=forProgramID)
def run_asyncio_roofline(self):
self.impl_run_asyncio(port=8024, handler=self.ConnHandler_roofline)
def run_asyncio(self):
self.impl_run_asyncio(port=8023, handler=self.ConnHandler)
def impl_run_asyncio(self, port, handler):
try:
loop = asyncio.SelectorEventLoop()
asyncio.set_event_loop(loop)
asyncio.get_event_loop().run_until_complete(
websockets.serve(handler, 'localhost', port, timeout=0.0001))
asyncio.get_event_loop().run_forever()
except Exception as e:
pass
async def ConnHandler_roofline(self, websocket, path):
while (True):
try:
msg = ""
try:
msg = await asyncio.wait_for(
websocket.recv(), timeout=0.01)
except asyncio.TimeoutError:
# Timeouts are expected
pass
if len(msg) > 0:
m = json.loads(msg)
self.message_handler_roofline(m)
# Lock to ensure correct operation (commands can be added asynchronously)
with self.comm_queue_lock_roofline:
for cmd in self.command_queue_roofline:
await websocket.send(cmd)
self.command_queue_roofline.clear()
except websockets.ConnectionClosed:
print("Roofline connection closed.")
break
async def ConnHandler(self, websocket, path):
self.websocket = websocket
print("Client connected!")
print("render queue is " + str(len(self.render_queue)) +
" elements long")
for sdfg in self.render_queue:
json = ""
# Allow directly rendering strings
if isinstance(sdfg, str):
json = sdfg
else:
json = sdfg.to_json()
await websocket.send(json)
self.render_queue.clear()
while (True):
try:
msg = ""
try:
msg = await asyncio.wait_for(
websocket.recv(), timeout=0.01)
except asyncio.TimeoutError:
# Timeouts are expected to happen
pass
if len(msg) > 0:
self.message_handler(msg)
for sdfg in self.render_queue:
if isinstance(sdfg, str):
json = sdfg
else:
json = sdfg.to_json()
await websocket.send(json)
self.render_queue.clear()
# Lock to ensure correct operation (commands can be added asynchronously)
with self.comm_queue_lock:
for cmd in self.command_queue:
# The difference in the command queue: All data must already be in JSON format
await websocket.send(cmd)
self.command_queue.clear()
except websockets.ConnectionClosed:
# If the connection was closed, probably a refresh was
# requested. This also means that we have to re-queue
print("Restoring render queue after abort")
self.render_queue = self.restore_render_queue.copy()
self.command_queue = self.restore_command_queue.copy()
break
def add_to_command_queue(self, x):
with self.comm_queue_lock as l:
self.command_queue.append(x)
def message_handler_roofline(self, m):
""" Handles roofline-specific commands """
if m["command"] == "connected" or m["command"] == "get-data":
# We should respond with the data for each value
pass
print("Can data requested")
if self.data_source == "fresh":
print(
"[FAIL] Data source is fresh, there are no results to be compared"
)
return
else:
retdict = PAPIInstrumentation.get_roofline_data(
self.data_source)
with self.comm_queue_lock_roofline:
self.command_queue_roofline.append(json.dumps(retdict))
elif m["command"] == "select-program":
# We should draw the requested program from the CAN.
programID = m["programID"]
# Request it.
self.open_canned_data(self.data_source, programID)
elif m["command"] == "":
pass
def run_async_request(self, task):
""" Run a request asynchronously """
self.db_request_queue.put(task)
def async_request_handler(self):
spawned_threads = []
while True:
request_handler = self.db_request_queue.get()
transself = self
def consumer_thread():
request_handler()
# Keep running if there are others waiting, otherwise, end the thread to free some resources
try:
while True:
elem = transself.db_request_queue.get_nowait()
elem()
except:
pass
newthread = threading.Thread(target=consumer_thread, daemon=True)
if len(spawned_threads) < self.max_db_request_threads:
spawned_threads.append(newthread)
spawned_threads[-1].start()
else:
# Wait until any of the previous tasks has finished
while True:
started = False
for i, t in enumerate(spawned_threads):
if not t.is_alive():
# Thread is dead, replace it
spawned_threads[i] = newthread
spawned_threads[i].start()
started = True
break
if started:
break
else:
request_handler()
break
def message_handler(self, msg):
db_path = "perfdata.db"
if self.data_source != "fresh":
db_path = self.data_source
local_data_source = self.data_source
dbg_print = False
m = json.loads(msg)
if m["msg_type"] == "info":
pass
elif m["msg_type"] == "roofline":
resp = self.message_handler_roofline(m)
if resp is not None:
self.add_to_command_queue(json.dumps(resp))
elif m["msg_type"] == "click":
def mainthread_click_cb():
self.on_click_cb(m["clicked_elements"])
return False
GObject.idle_add(mainthread_click_cb)
elif m["msg_type"] == "heartbeat":
pass # Ignored, this unblocks the recv() call
elif m["msg_type"] == "fetcher":
if dbg_print:
print("Lazy fetch request received")
seqid = m["seqid"]
method = m["msg"]["method"]
params = m["msg"]["params"]
synchronous_execution = method != "Analysis"
if synchronous_execution:
conn = sqlite3.connect(db_path, check_same_thread=False)
c = conn.cursor()
# Attach a default scratch space to every connection such that we can write temporary dbs concurrently
c.execute("ATTACH DATABASE ':memory:' AS scratch_default;")
if method == "getSuperSectionCount":
ma = MetaFetcher(local_data_source, self.canned_data_programid)
d = ma.getSuperSectionCount(c, *params)
resp = '{ "type": "fetcher", "seqid": %d, "msg": %s }' % (
int(seqid), str(d))
self.add_to_command_queue(resp)
elif method == "getAllSectionStateIds":
def taskrunner():
conn = sqlite3.connect(db_path, check_same_thread=False)
c = conn.cursor()
# Attach a default scratch space to every connection such that we can write temporary dbs concurrently
c.execute("ATTACH DATABASE ':memory:' AS scratch_default;")
ma = MetaFetcher(local_data_source,
self.canned_data_programid)
if dbg_print:
print("params: " + str(params))
d = ma.getAllSectionStateIds(c, *params)
resp = '{ "type": "fetcher", "seqid": %d, "msg": %s }' % (
int(seqid), str(d))
self.add_to_command_queue(resp)
conn.close()
# Run asynchronously
self.run_async_request(taskrunner)
elif method == "getAllSectionNodeIds":
def taskrunner():
conn = sqlite3.connect(db_path, check_same_thread=False)
c = conn.cursor()
# Attach a default scratch space to every connection such that we can write temporary dbs concurrently
c.execute("ATTACH DATABASE ':memory:' AS scratch_default;")
ma = MetaFetcher(local_data_source,
self.canned_data_programid)
if dbg_print:
print("params: " + str(params))
d = ma.getAllSectionNodeIds(c, *params)
resp = '{ "type": "fetcher", "seqid": %d, "msg": %s }' % (
int(seqid), str(d))
self.add_to_command_queue(resp)
conn.close()
# Run asynchronously
#threading.Thread(target=taskrunner).start()
self.run_async_request(taskrunner)
elif method == "Analysis":
# Any analysis, name given in params[0]
cname = params[0]
params = params[1:]
transself = self
def taskrunner():
if dbg_print:
print("Running analysis " + cname)
print("Params: " + str(params))
conn = sqlite3.connect(db_path, check_same_thread=False)
c = conn.cursor()
# Attach a default scratch space to every connection such that we can write temporary dbs concurrently
c.execute("ATTACH DATABASE ':memory:' AS scratch_default;")
if local_data_source == "fresh":
def my_import(name):
components = name.split('.')
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
_module = my_import("diode.db_scripts.sql_to_json")
_cl = getattr(_module, cname)
_instance = _cl()
d = _instance.query_values(c, *params)
respval = json.dumps(d)
if d is None:
# Special case of undefined
d = "null"
else: # Canned data
# This is easier as in: The results can be read from a database directly
argparams = [*params]
query_ss = True
if cname == "CriticalPathAnalysis":
# This has split IDs (instead of the unified id)
tmp = [*params]
if tmp[0] is None:
tmp[0] = 0x0FFFF
# Recreate the correct pair and remove the supersection part from the query
argparams = [
(int(tmp[1]) << 16) | (int(tmp[0]) & 0xFFFF)
]
query_ss = False
if argparams[0] == -1 or | |
<gh_stars>10-100
import os
import struct
import maya.cmds as cmds
import maya.mel as mel
import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
import pymel.core
from process import Process
# Will be populated as materials are registered with Maya
materialNodeTypes = []
#
# XML formatted printing
#
def writeElementText(element, depth=0):
#print( "element : %s" % str(element) )
if element in [{}, None]:
return ""
if 'attributes' in element:
attributes = element['attributes']
else:
attributes = {}
if 'children' in element:
children = element['children']
else:
children = []
typeName = element['type']
spacing = '\t'*depth
elementText = ""
elementText += spacing + "<%s" % typeName
for key, value in attributes.iteritems():
elementText += " %s=\"%s\"" % (key, value)
if children:
elementText += ">\n"
for child in children:
#print( "child : %s" % str(child) )
elementText += writeElementText(child, depth+1)
#element += "\n"
elementText += spacing + "</%s>\n" % typeName
else:
elementText += "/>\n"
# Simple formatting cheat to make the files a little more readable
if depth == 1:
elementText += "\n"
return elementText
# Other options to be provided later
def writeElement(outFile, element, depth=0):
elementText = writeElementText(element, depth)
outFile.write(elementText)
#
# IO functions
#
#
# General functionality
#
# Returns the surfaceShader node for a piece of geometry (geom)
def getSurfaceShader(geom):
shapeNode = cmds.listRelatives(geom, children=True, shapes=True, fullPath=True)[0]
sg = cmds.listConnections(shapeNode, type="shadingEngine")[0]
shader = cmds.listConnections(sg+".surfaceShader")
#if shader is None:
# shader = cmds.listConnections(sg+".volumeShader")
if shader:
shader = shader[0]
return shader
def getVolumeShader(geom):
shapeNode = cmds.listRelatives(geom, children=True, shapes=True, fullPath=True)[0]
sg = cmds.listConnections(shapeNode, type="shadingEngine")[0]
shader = cmds.listConnections(sg+".volumeShader")
if shader:
shader = shader[0]
return shader
def listToMitsubaText(list):
return " ".join( map(str, list) )
def booleanToMisubaText(b):
if b:
return "true"
else:
return "false"
#
# Scene Element representation
#
class SceneElement(dict):
def __init__(self, elementType, attributes=None, *args):
dict.__init__(self, args)
self.children = []
self.attributes = {}
dict.__setitem__(self, 'children', self.children )
dict.__setitem__(self, 'attributes', self.attributes )
dict.__setitem__(self, 'type', elementType )
if attributes:
for key, value in attributes.iteritems():
self.attributes[key] = value
def addChild(self, child):
self.children.append( child )
def addChildren(self, children):
self.children.extend( children )
def getChild(self, index):
return self.children[index]
def addAttribute(self, key, value):
self.attributes[key] = value
def removeAttribute(self, key):
if key in self.attributes:
del( self.attributes[key] )
def getAttribute(self, key):
if key in self.attributes:
return self.attributes[key]
else:
return None
def BooleanParameter(name, value):
return SceneElement('boolean', {'name':name, 'value':booleanToMisubaText(value)} )
def IntegerParameter(name, value):
return SceneElement('integer', {'name':name, 'value':str(value)} )
def FloatParameter(name, value):
return SceneElement('float', {'name':name, 'value':str(value)} )
def VectorParameter(name, x, y, z):
return SceneElement('vector', {'name':name, 'x':str(x), 'y':str(y), 'z':str(z)} )
def PointParameter(name, x, y, z):
return SceneElement('point', {'name':name, 'x':str(x), 'y':str(y), 'z':str(z)} )
def StringParameter(name, value):
return SceneElement('string', {'name':name, 'value':str(value)} )
def ColorParameter(name, value, colorspace='rgb'):
return SceneElement(colorspace, {'name':name, 'value':listToMitsubaText(value)} )
def SpectrumParameter(name, value):
if isinstance(value, basestring):
element = SceneElement('spectrum', {'name':name, 'filename':str(value)} )
else:
element = SceneElement('spectrum', {'name':name, 'value':str(value)} )
return element
def RotateElement(axis, angle):
return SceneElement('rotate', { axis:str(1), 'angle':str(angle) } )
def TranslateElement(x, y, z):
return SceneElement('translate', { 'x':str(x), 'y':str(y), 'z':str(z) } )
def Scale2Element(x, y):
return SceneElement('scale', { 'x':x, 'y':y } )
def LookAtElement(aim, origin, up):
return SceneElement('lookat', { 'target':listToMitsubaText(aim),
'origin':listToMitsubaText(origin), 'up':listToMitsubaText(up) } )
def createSceneElement(typeAttribute=None, id=None, elementType='scene'):
element = SceneElement(elementType)
if typeAttribute:
element.addAttribute('type', typeAttribute)
if id:
element.addAttribute('id', id)
return element
def BSDFElement(typeAttribute=None, id=None):
return createSceneElement(typeAttribute, id, 'bsdf')
def PhaseElement(typeAttribute=None, id=None):
return createSceneElement(typeAttribute, id, 'phase')
def MediumElement(typeAttribute=None, id=None):
return createSceneElement(typeAttribute, id, 'medium')
def ShapeElement(typeAttribute=None, id=None):
return createSceneElement(typeAttribute, id, 'shape')
def EmitterElement(typeAttribute=None, id=None):
return createSceneElement(typeAttribute, id, 'emitter')
def SubsurfaceElement(typeAttribute=None, id=None):
return createSceneElement(typeAttribute, id, 'subsurface')
def IntegratorElement(typeAttribute=None, id=None):
return createSceneElement(typeAttribute, id, 'integrator')
def FilmElement(typeAttribute=None, id=None):
return createSceneElement(typeAttribute, id, 'film')
def SensorElement(typeAttribute=None, id=None):
return createSceneElement(typeAttribute, id, 'sensor')
def SamplerElement(typeAttribute=None, id=None):
return createSceneElement(typeAttribute, id, 'sampler')
def TransformElement(typeAttribute=None, id=None):
return createSceneElement(typeAttribute, id, 'transform')
def RefElement(typeAttribute=None, id=None):
return createSceneElement(typeAttribute, id, 'ref')
def VolumeElement(name, volumePath=None, typeAttribute='gridvolume'):
element = createSceneElement(typeAttribute, elementType='volume')
element.addAttribute('name', name)
if volumePath:
element.addChild( StringParameter('filename', volumePath) )
return element
def NestedBSDFElement(material, connectedAttribute="bsdf", useDefault=True):
hasNestedBSDF = False
shaderElement = None
connections = cmds.listConnections(material, connections=True)
for i in range(len(connections)):
if i%2==1:
connection = connections[i]
connectionType = cmds.nodeType(connection)
if connectionType in materialNodeTypes and connections[i-1]==(material.split('|')[-1] + "." + connectedAttribute):
#We've found the nested bsdf, so build a structure for it
shaderElement = writeShader(connection, connection)
# Remove the id so there's no chance of this embedded definition conflicting with another
# definition of the same BSDF
shaderElement.removeAttribute('id')
hasNestedBSDF = True
if useDefault and not hasNestedBSDF:
bsdf = cmds.getAttr(material + "." + connectedAttribute)
shaderElement = BSDFElement('diffuse')
shaderElement.addChild( ColorParameter('reflectance', bsdf[0], colorspace='rgb') )
return shaderElement
def getTextureFile(material, connectionAttr):
connections = cmds.listConnections(material, connections=True)
fileTexture = None
for i in range(len(connections)):
if i%2==1:
connection = connections[i]
connectionType = cmds.nodeType(connection)
if connectionType == "file" and connections[i-1]==(material.split('|')[-1]+"."+connectionAttr):
fileTexture = cmds.getAttr(connection+".fileTextureName")
#print( "Found texture : %s" % fileTexture )
animatedTexture = cmds.getAttr("%s.%s" % (connection, "useFrameExtension"))
if animatedTexture:
textureFrameNumber = cmds.getAttr("%s.%s" % (connection, "frameExtension"))
# Should make this an option at some point
tokens = fileTexture.split('.')
tokens[-2] = str(textureFrameNumber).zfill(4)
fileTexture = '.'.join(tokens)
#print( "Animated texture path : %s" % fileTexture )
#else:
# print "Source can only be an image file"
return fileTexture
def TextureElement(name, texturePath, scale=None):
textureElementDict = createSceneElement('bitmap', elementType='texture')
textureElementDict.addChild( StringParameter('filename', texturePath) )
if scale:
scaleElementDict = createSceneElement('scale', elementType='texture')
scaleElementDict.addChild( FloatParameter('scale', scale) )
scaleElementDict.addChild( textureElementDict )
textureElementDict = scaleElementDict
textureElementDict.addAttribute('name', name)
return textureElementDict
def TexturedColorAttributeElement(material, attribute, mitsubaParameter=None, colorspace='rgb', scale=None):
if not mitsubaParameter:
mitsubaParameter = attribute
fileTexture = getTextureFile(material, attribute)
if fileTexture:
extension = os.path.splitext(fileTexture)[-1]
if extension.lower() == ".spd":
element = SpectrumParameter(mitsubaParameter, fileTexture )
else:
element = TextureElement(mitsubaParameter, fileTexture, scale)
else:
value = cmds.getAttr(material + "." + attribute)
element = ColorParameter(mitsubaParameter, value[0], colorspace )
return element
def TexturedFloatAttributeElement(material, attribute, mitsubaParameter=None, scale=None):
if not mitsubaParameter:
mitsubaParameter = attribute
fileTexture = getTextureFile(material, attribute)
if fileTexture:
element = TextureElement(mitsubaParameter, fileTexture, scale)
else:
value = cmds.getAttr(material + "." + attribute)
element = FloatParameter(mitsubaParameter, value )
return element
def TexturedVolumeAttributeElement(material, attribute, mitsubaParameter=None):
if not mitsubaParameter:
mitsubaParameter = attribute
fileTexture = getTextureFile(material, attribute)
if fileTexture:
element = VolumeElement(mitsubaParameter, fileTexture)
else:
value = cmds.getAttr(material + "." + attribute)
element = SpectrumParameter('value', value)
volumeWrapperElement = VolumeElement(mitsubaParameter, typeAttribute='constvolume')
volumeWrapperElement.addChild( element )
element = volumeWrapperElement
return element
# UI to API name mappings
conductorUIToPreset = {
"100\% reflecting mirror" : "none",
"Amorphous carbon" : "a-C",
"Silver" : "Ag",
"Aluminium" : "Al",
"Cubic aluminium arsenide" : "AlAs",
"Cubic aluminium antimonide" : "AlSb",
"Gold" : "Au",
"Polycrystalline beryllium" : "Be",
"Chromium" : "Cr",
"Cubic caesium iodide" : "CsI",
"Copper" : "Cu",
"Copper (I) oxide" : "Cu2O",
"Copper (II) oxide" : "CuO",
"Cubic diamond" : "d-C",
"Mercury" : "Hg",
"Mercury telluride" : "HgTe",
"Iridium" : "Ir",
"Polycrystalline potassium" : "K",
"Lithium" : "Li",
"Magnesium oxide" : "MgO",
"Molybdenum" : "Mo",
"Sodium" : "Na_palik",
"Niobium" : "Nb",
"Nickel" : "Ni_palik",
"Rhodium" : "Rh",
"Selenium" : "Se",
"Hexagonal silicon carbide" : "SiC",
"Tin telluride" : "SnTe",
"Tantalum" : "Ta",
"Trigonal tellurium" : "Te",
"Polycryst. thorium (IV) fuoride" : "ThF4",
"Polycrystalline titanium carbide" : "TiC",
"Titanium nitride" : "TiN",
"Tetragonal titan. dioxide" : "TiO2",
"Vanadium carbide" : "VC",
"Vanadium" : "V_palik",
"Vanadium nitride" : "VN",
"Tungsten" : "W",
}
distributionUIToPreset = {
"Beckmann" : "beckmann",
"GGX" : "ggx",
"Phong" : "phong",
"<NAME>" : "as",
}
iorMaterialUIToPreset = {
"Vacuum" : "vacuum",
"Helum" : "helium",
"Hydrogen" : "hydrogen",
"Air" : "air",
"Carbon Dioxide" : "carbon dioxide",
"Water" : "water",
"Acetone" : "acetone",
"Ethanol" : "ethanol",
"Carbon Tetrachloride" : "carbon tetrachloride",
"Glycerol" : "glycerol",
"Benzene" : "benzene",
"Silicone Oil" : "silicone oil",
"Bromine" : "bromine",
"Water Ice" : "water ice",
"Fused Quartz" : "fused quartz",
"Pyrex" : "pyrex",
"Acrylic Glass" : "acrylic glass",
"Polypropylene" : "polypropylene",
"BK7" : "bk7",
"Sodium Chloride" : "sodium chloride",
"Amber" : "amber",
"Pet" : "pet",
"Diamond" : "diamond",
}
wardVariantUIToPreset = {
"Ward" : "ward",
"Ward-Duer" : "ward-duer",
"Balanced" : "balanced",
}
mediumMaterialUIToPreset = {
"Apple" : "Apple",
"Cream" : "Cream",
"Skimmilk" : "Skimmilk",
"Spectralon" : "Spectralon",
"Chicken1" : "Chicken1",
"Ketchup" : "Ketchup",
"Skin1" : "Skin1",
"Wholemilk" : "Wholemilk",
"Chicken2" : "Chicken2",
"Potato" : "Potato",
"Skin2" : "Skin2",
"Lowfat Milk" : "Lowfat Milk",
"Reduced Milk" : "Reduced Milk",
"Regular Milk" : "Regular Milk",
"Espresso" : "Espresso",
"Mint Mocha Coffee" : "Mint Mocha Coffee",
"Lowfat Soy Milk" : "Lowfat Soy Milk",
"Regular Soy Milk" : "Regular Soy Milk",
"Lowfat Chocolate Milk" : "Lowfat Chocolate Milk",
"Regular Chocolate Milk" : "Regular Chocolate Milk",
"Coke" : "Coke",
"Pepsi Sprite" : "Pepsi Sprite",
"Gatorade" : "Gatorade",
"Chardonnay" : "Chardonnay",
"White Zinfandel" : | |
1500000000000000000000),
("0x4adbf4aae0e3ef44f7dd4d8985cfaf096ec48e98", 150000000000000000000),
("0x9a633fcd112cceeb765fe0418170732a9705e79c", 18200000000000000000),
("0x292f228b0a94748c8eec612d246f989363e08f08", 185000000000000000000),
("0x9f3497f5ef5fe63095836c004eb9ce02e9013b4b", 633424000000000000000),
("0x0e6dfd553b2e873d2aec15bd5fbb3f8472d8d394", 12000000000000000000000),
("0x74ebf4425646e6cf81b109ce7bf4a2a63d84815f", 40000000000000000000),
("0x8ce5e3b5f591d5eca38abf228f2e3c35134bdac0", 2319920000000000000000),
("0x90c41eba008e20cbe927f346603fc88698125969", 42000000000000000000),
("0x382ba76db41b75606dd48a48f0137e9174e031b6", 20000000000000000000),
("0x5d24bdbc1c47f0eb83d128cae48ac33c4817e91f", 1000000000000000000000),
("0xa64e5ffb704c2c9139d77ef61d8cdfa31d7a88e9", 143000000000000000000),
("0xa18360e985f2062e8f8efe02ad2cbc91ad9a5aad", 3000000000000000000000),
("0xd251f903ae18727259eee841a189a1f569a5fd76", 10000000000000000000000),
("0xefa6b1f0db603537826891b8b4bc163984bb40cd", 985000000000000000000),
("0x47fff42c678551d141eb75a6ee398117df3e4a8d", 100010000000000000000),
("0xf2294adbb6f0dcc76e632ebef48ab49f124dbba4", 1443690000000000000000),
("0x53700d53254d430f22781a4a76a463933b5d6b08", 1970000000000000000000),
("0xb14a7aaa8f49f2fb9a8102d6bbe4c48ae7c06fb2", 8000000000000000000000),
("0x9ed4e63f526542d44fddd34d59cd25388ffd6bda", 3885000000000000000000),
("0x4cac91fb83a147d2f76c3267984b910a79933348", 2167000000000000000000),
("0x9b32cf4f5115f4b34a00a64c617de06387354323", 105501000000000000000),
("0xb8bedd576a4b4c2027da735a5bc3f533252a1808", 2000000000000000000000),
("0xc5a3b98e4593fea0b38c4f455a5065f051a2f815", 20309030000000000000000),
("0xeaf52388546ec35aca6f6c6393d8d609de3a4bf3", 20000000000000000000),
("0x4c423c76930d07f93c47a5cc4f615745c45a9d72", 100000000000000000000),
("0x9052f2e4a3e3c12dd1c71bf78a4ec3043dc88b7e", 267400000000000000000),
("0x2bade91d154517620fd4b439ac97157a4102a9f7", 4000000000000000000000),
("0xda698d64c65c7f2b2c7253059cd3d181d899b6b7", 295500000000000000000),
("0xc6d8954e8f3fc533d2d230ff025cb4dce14f3426", 400000000000000000000),
("0x349a816b17ab3d27bbc0ae0051f6a070be1ff29d", 10000000000000000000000),
("0xff4d9c8484c43c42ff2c5ab759996498d323994d", 4000000000000000000000),
("0x22944fbca9b57963084eb84df7c85fb9bcdfb856", 4649845000000000000000),
("0xbfd93c90c29c07bc5fb5fc49aeea55a40e134f35", 28000000000000000000000),
("0x3caedb5319fe806543c56e5021d372f71be9062e", 40000000000000000000000),
("0x9a079c92a629ca15c8cafa2eb28d5bc17af82811", 500000000000000000000),
("0x7d2a52a7cf0c8436a8e007976b6c26b7229d1e15", 438040000000000000000),
("0xcf89f7460ba3dfe83c5a1d3a019ee1250f242f0f", 985177000000000000000),
("0x577bfe64e3a1e3800e94db1c6c184d8dc8aafc66", 1498000000000000000000),
("0x7ffd02ed370c7060b2ae53c078c8012190dfbb75", 10000000000000000000000),
("0x90b62f131a5f29b45571513ee7a74a8f0b232202", 158000000000000000000),
("0x6e8212b722afd408a7a73ed3e2395ee6454a0330", 159000000000000000000),
("0x515f30bc90cdf4577ee47d65d785fbe2e837c6bc", 10166128000000000000000),
("0xc27376f45d21e15ede3b26f2655fcee02ccc0f2a", 20000000000000000000),
("0x3da39ce3ef4a7a3966b32ee7ea4ebc2335a8f11f", 2000000000000000000000),
("0x25259d975a21d83ae30e33f800f53f37dfa01938", 20000000000000000000),
("0x8ed143701f2f72280fd04a7b4164281979ea87c9", 14000000000000000000),
("0x5ac99ad7816ae9020ff8adf79fa9869b7cea6601", 21000000000000000000000),
("0xf51fded80acb502890e87369741f3722514cefff", 20000042000000000000000),
("0xf657fcbe682eb4e8db152ecf892456000b513d15", 1940000000000000000000),
("0x62c37c52b97f4b040b1aa391d6dec152893c4707", 1000000000000000000000),
("0x89fc8e4d386b0d0bb4a707edf3bd560df1ad8f4e", 2955000000000000000000),
("0x53c0bb7fc88ea422d2ef7e540e2d8f28b1bb8183", 20000000000000000000),
("0x56f493a3d108aaa2d18d98922f8efe1662cfb73d", 2020000000000000000000),
("0xe9458f68bb272cb5673a04f781b403556fd3a387", 61000000000000000000),
("0xbe525a33ea916177f17283fca29e8b350b7f530b", 2638000000000000000000),
("0x4feb846be43041fd6b34202897943e3f21cb7f04", 83226000000000000000),
("0x15aa530dc36958b4edb38eee6dd9e3c77d4c9145", 2000000000000000000000),
("0x2458d6555ff98a129cce4037953d00206eff4287", 197000000000000000000),
("0x8035fe4e6b6af27ae492a578515e9d39fa6fa65b", 4000000000000000000000),
("0x296b71c0015819c242a7861e6ff7eded8a5f71e3", 1999800000000000000000),
("0x8f1952eed1c548d9ee9b97d0169a07933be69f63", 1000000000000000000000),
("0xa421dbb89b3a07419084ad10c3c15dfe9b32d0c2", 20000000000000000000000),
("0x554336ee4ea155f9f24f87bca9ca72e253e12cd2", 100000000000000000000),
("0xffc5fc4b7e8a0293ff39a3a0f7d60d2646d37a74", 2000000000000000000000),
("0xea2c197d26e98b0da83e1b72c787618c979d3db0", 19700000000000000000),
("0x96aa573fed2f233410dbae5180145b23c31a02f0", 1730000000000000000000),
("0xc23b2f921ce4a37a259ee4ad8b2158d15d664f59", 25403000000000000000),
("0xd874b9dfae456a929ba3b1a27e572c9b2cecdfb3", 170000000000000000000),
("0xbf8b8005d636a49664f74275ef42438acd65ac91", 200000000000000000000),
("0x441a52001661fac718b2d7b351b7c6fb521a7afd", 400000000000000000000),
("0x812a55c43caedc597218379000ce510d548836fd", 18200000000000000000),
("0x5e90c85877198756b0366c0e17b28e52b446505a", 374288000000000000000),
("0xda3017c150dd0dce7fcf881b0a48d0d1c756c4c7", 100014000000000000000),
("0x6baf7a2a02ae78801e8904ad7ac05108fc56cff6", 1000000000000000000000),
("0x177dae78bc0113d8d39c4402f2a641ae2a105ab8", 1818320000000000000000),
("0x01b5b5bc5a117fa08b34ed1db9440608597ac548", 200000000000000000000),
("0xaae732eda65988c3a00c7f472f351c463b1c968e", 2000000000000000000000),
("0xd95342953c8a21e8b635eefac7819bea30f17047", 94160000000000000000000),
("0x8d616b1eee77eef6f176e0698db3c0c141b2fc8f", 500000000000000000000),
("0x12d20790b7d3dbd88c81a279b812039e8a603bd0", 1604400000000000000000),
("0x3734cb187491ede713ae5b3b2d12284af46b8101", 3000000000000000000000),
("0xdd967c4c5f8ae47e266fb416aad1964ee3e7e8c3", 7750000000000000000000),
("0x3dcef19c868b15d34eda426ec7e04b18b6017002", 1999800000000000000000),
("0xce9d21c692cd3c01f2011f505f870036fa8f6cd2", 400000000000000000000),
("0xd44f6ac3923b5fd731a4c45944ec4f7ec52a6ae4", 10000000000000000000000),
("0xb424d68d9d0d00cec1938c854e15ffb880ba0170", 200000000000000000000),
("0x1f2186ded23e0cf9521694e4e164593e690a9685", 300000000000000000000),
("0x7f4b5e278578c046cceaf65730a0e068329ed5b6", 1880000000000000000000),
("0x8c50aa2a9212bcde56418ae261f0b35e7a9dbb82", 400000000000000000000),
("0x1953313e2ad746239cb2270f48af34d8bb9c4465", 2000000000000000000000),
("0xa15025f595acdbf3110f77c5bf24477e6548f9e8", 2000000000000000000000),
("0x53af32c22fef99803f178cf90b802fb571c61cb9", 3880000000000000000000),
("0xd0a8abd80a199b54b08b65f01d209c27fef0115b", 6525979000000000000000),
("0x2b68306ba7f8daaf73f4c644ef7d2743c0f26856", 864800000000000000000),
("0x96924191b7df655b3319dc6d6137f481a73a0ff3", 4020000000000000000000),
("0x6fa72015fa78696efd9a86174f7f1f21019286b1", 1337000000000000000000),
("0x0b119df99c6b8de58a1e2c3f297a6744bf552277", 2000000000000000000000),
("0x61733947fab820dbd351efd67855ea0e881373a0", 20000000000000000000),
("0x8ae6f80b70e1f23c91fbd5a966b0e499d95df832", 197000000000000000000),
("0x01a7d9fa7d0eb1185c67e54da83c2e75db69e39f", 7623900000000000000000),
("0x9932ef1c85b75a9b2a80057d508734c51085becc", 50170000000000000000),
("0xaefcfe88c826ccf131d54eb4ea9eb80e61e1ee25", 340000000000000000000),
("0xc21fa6643a1f14c02996ad7144b75926e87ecb4b", 20000000000000000000000),
("0x97d9e46a7604d7b5a4ea4ee61a42b3d2350fc3ed", 2000000000000000000000),
("0x3cafaf5e62505615068af8eb22a13ad8a9e55070", 1999600000000000000000),
("0x22f2dcff5ad78c3eb6850b5cb951127b659522e6", 13700000000000000000),
("0xaaad1baade5af04e2b17439e935987bf8c2bb4b9", 2000000000000000000000),
("0x298887bab57c5ba4f0615229d7525fa113b7ea89", 40000000000000000000),
("0x7539333046deb1ef3c4daf50619993f444e1de68", 1182000000000000000000),
("0x9752d14f5e1093f071711c1adbc4e3eb1e5c57f3", 2000000000000000000000),
("0xed641e06368fb0efaa1703e01fe48f4a685309eb", 200000000000000000000),
("0xd0ee4d02cf24382c3090d3e99560de3678735cdf", 2400000000000000000000),
("0x47e25df8822538a8596b28c637896b4d143c351d", 80500000000000000000000),
("0x559706c332d20779c45f8a6d046a699159b74921", 380123000000000000000),
("0x3a4da78dce05aeb87de9aead9185726da1926798", 200000000000000000000),
("0x3041445a33ba158741160d9c344eb88e5c306f94", 60000000000000000000),
("0x08d4311c9c1bbaf87fabe1a1d01463828d5d98ce", 90000000000000000000000),
("0x6bd3e59f239fafe4776bb9bddd6bee83ba5d9d9f", 1000000000000000000000),
("0x29eaae82761762f4d2db53a9c68b0f6b0b6d4e66", 2000000000000000000000),
("0x0b7d339371e5be6727e6e331b5821fa24bdb9d5a", 857738000000000000000),
("0x4714cfa4f46bd6bd70737d75878197e08f88e631", 11792000000000000000000),
("0xad92ca066edb7c711dfc5b166192d1edf8e77185", 36000000000000000000000),
("0xf97b56ebd5b77abc9fbacbabd494b9d2c221cd03", 1970000000000000000000),
("0x591bef3171d1c5957717a4e98d17eb142c214e56", 20000000000000000000000),
("0x899b3c249f0c4b81df75d212004d3d6d952fd223", 2000000000000000000000),
("0xa819d2ece122e028c8e8a04a064d02b9029b08b9", 1000000000000000000000),
("0xe341642d40d2afce2e9107c67079ac7a2660086c", 400000000000000000000),
("0x0329188f080657ab3a2afa522467178279832085", 216700000000000000000),
("0x03317826d1f70aa4bddfa09be0c4105552d2358b", 38800000000000000000),
("0x3ac9dc7a436ae98fd01c7a9621aa8e9d0b8b531d", 1790000000000000000000),
("0x93c88e2d88621e30f58a9586bed4098999eb67dd", 31200000000000000000000),
("0xcd1e66ed539dd92fc40bbaa1fa16de8c02c14d45", 230000000000000000000),
("0xe6c81ffcecb47ecdc55c0b71e4855f3e5e97fc1e", 334250000000000000000),
("0x50f8fa4bb9e2677c990a4ee8ce70dd1523251e4f", 26030000000000000000),
("0x4f64a85e8e9a40498c0c75fceb0337fb49083e5e", 1000000000000000000000),
("0x4b29437c97b4a844be71cca3b648d4ca0fdd9ba4", 150200000000000000000),
("0x1eee6cbee4fe96ad615a9cf5857a647940df8c78", 19400000000000000000),
("0x29f0edc60338e7112085a1d114da8c42ce8f55d6", 2958000000000000000000),
("0x23b1c4917fbd93ee3d48389306957384a5496cbf", 4000086000000000000000),
("0x1767525c5f5a22ed80e9d4d7710f0362d29efa33", 400000000000000000000),
("0x3064899a963c4779cbf613cd6980846af1e6ec65", 6999908000000000000000),
("0x68531f4dda808f5320767a03113428ca0ce2f389", 19400000000000000000),
("0x1db9ac9a9eaeec0a523757050c71f47278c72d50", 1337000000000000000000),
("0x7592c69d067b51b6cc639d1164d5578c60d2d244", 20000000000000000000),
("0xcf3fbfa1fd32d7a6e0e6f8ef4eab57be34025c4c", 1063120000000000000000),
("0x8efec058cc546157766a632775404a334aaada87", 1999000000000000000000),
("0xfaf5f0b7b6d558f5090d9ea1fb2d42259c586078", 6401000000000000000000),
("0x19ecf2abf40c9e857b252fe1dbfd3d4c5d8f816e", 2000000000000000000000),
("0x6e8a26689f7a2fdefd009cbaaa5310253450daba", 2049982000000000000000),
("0xe2f40d358f5e3fe7463ec70480bd2ed398a7063b", 20000000000000000000),
("0xfa19d6f7a50f4f079893d167bf14e21d0073d196", 530000000000000000000),
("0x3e2ca0d234baf607ad466a1b85f4a6488ef00ae7", 89505000000000000000),
("0xf8a49ca2390c1f6d5c0e62513b079571743f7cc6", 3000000000000000000000),
("0x5d3f3b1f7130b0bb21a0fd32396239179a25657f", 62474000000000000000000),
("0xf332c0f3e05a27d9126fd0b641a8c2d4060608fd", 5001041000000000000000),
("0xe304a32f05a83762744a9542976ff9b723fa31ea", 1576256000000000000000),
("0xf768f321fd6433d96b4f354d3cc1652c1732f57f", 10000000000000000000000),
("0x147af46ae9ccd18bb35ca01b353b51990e49dce1", 4000000000000000000000),
("0x21eae6feffa9fbf4cd874f4739ace530ccbe5937", 5000000000000000000000),
("0x6994fb3231d7e41d491a9d68d1fa4cae2cc15960", 4000000000000000000000),
("0x51126446ab3d8032557e8eba65597d75fadc815c", 322000000000000000000),
("0x24daaaddf7b06bbcea9b80590085a88567682b4e", 319008000000000000000),
("0xcd020f8edfcf524798a9b73a640334bbf72f80a5", 133700000000000000000),
("0x56febf9e1003af15b1bd4907ec089a4a1b91d268", 200000000000000000000),
("0x3c79c863c3d372b3ff0c6f452734a7f97042d706", 176000000000000000000),
("0xe1203eb3a723e99c2220117ca6afeb66fa424f61", 9461996000000000000000),
("0x18fb09188f27f1038e654031924f628a2106703d", 2000000000000000000000),
("0x2eba0c6ee5a1145c1c573984963a605d880a7a20", 500000000000000000000),
("0x4cefbe2398e47d52e78db4334c8b697675f193ae", 4011000000000000000000),
("0xc02471e3fc2ea0532615a7571d493289c13c36ef", 20000000000000000000),
("0xba469aa5c386b19295d4a1b5473b540353390c85", 2000000000000000000000),
("0x7b11673cc019626b290cbdce26046f7e6d141e21", 500000000000000000000),
("0x26784ade91c8a83a8e39658c8d8277413ccc9954", 6000000000000000000000),
("0x57d3df804f2beee6ef53ab94cb3ee9cf524a18d3", 393606000000000000000),
("0xccae0d3d852a7da3860f0636154c0a6ca31628d4", 106560000000000000000),
("0xbfe3a1fc6e24c8f7b3250560991f93cba2cf8047", 80000000000000000000000),
("0x724ce858857ec5481c86bd906e83a04882e5821d", 3000000000000000000000),
("0xfb37cf6b4f81a9e222fba22e9bd24b5098b733cf", 38800000000000000000),
("0x9b22a80d5c7b3374a05b446081f97d0a34079e7f", 3000000000000000000000),
("0x0a29a8a4d5fd950075ffb34d77afeb2d823bd689", 200000000000000000000),
("0xd01af9134faf5257174e8b79186f42ee354e642d", 1000000000000000000000),
("0x7f1619988f3715e94ff1d253262dc5581db3de1c", 900000000000000000000),
("0x6f137a71a6f197df2cbbf010dcbd3c444ef5c925", 2000000000000000000000),
("0x11efb8a20451161b644a8ccebbc1d343a3bbcb52", 3200000000000000000000),
("0x46504e6a215ac83bccf956befc82ab5a679371c8", 518898000000000000000),
("0xb523fff9749871b35388438837f7e6e0dea9cb6b", 2000000000000000000000),
("0xc5c6a4998a33feb764437a8be929a73ba34a0764", 50000000000000000000000),
("0x3cd7f7c7c2353780cde081eeec45822b25f2860c", 200000000000000000000),
("0xb3050beff9de33c80e1fa15225e28f2c413ae313", 700000000000000000000),
("0x59268171b833e0aa13c54b52ccc0422e4fa03aeb", 3000000000000000000000),
("0x7169724ee72271c534cad6420fb04ee644cb86fe", 410164000000000000000),
("0x6e6d5bbbb9053b89d744a27316c2a7b8c09b547d", 909831000000000000000),
("0x3f3f46b75cabe37bfacc8760281f4341ca7f463d", 602709000000000000000),
("0x7a33834e8583733e2d52aead589bd1affb1dd256", 1000000000000000000000),
("0xe94ded99dcb572b9bb1dcba32f6dee91e057984e", 394000000000000000000),
("0x19336a236ded755872411f2e0491d83e3e00159e", 940000000000000000000),
("0x63ac545c991243fa18aec41d4f6f598e555015dc", 600000000000000000000),
("0xcfee05c69d1f29e7714684c88de5a16098e91399", 1970000000000000000000),
("0x77be6b64d7c733a436adec5e14bf9ad7402b1b46", 1000000000000000000000),
("0x233bdddd5da94852f4ade8d212885682d9076bc6", 4000000000000000000000),
("0x952c57d2fb195107d4cd5ca300774119dfad2f78", 2000000000000000000000),
("0xe237baa4dbc9926e32a3d85d1264402d54db012f", 2000000000000000000000),
("0xaa91237e740d25a92f7fa146faa18ce56dc6e1f3", 925000000000000000000),
("0x2339e9492870afea2537f389ac2f838302a33c06", 2000000000000000000000),
("0x1d45586eb803ca2190650bf748a2b174312bb507", 1400000000000000000000),
("0xc61446b754c24e3b1642d9e51765b4d3e46b34b6", 2000000000000000000000),
("0xac28b5edea05b76f8c5f97084541277c96696a4c", 1000000000000000000000),
("0x1a1c9a26e0e02418a5cf687da75a275c622c9440", 5000000000000000000000),
("0x299368609042a858d1ecdf1fc0ada5eaceca29cf", 2000000000000000000000),
("0x095f5a51d06f6340d80b6d29ea2e88118ad730fe", 2000200000000000000000),
("0x751a2ca34e7187c163d28e3618db28b13c196d26", 500000000000000000000),
("0x75b0e9c942a4f0f6f86d3f95ff998022fa67963b", 1490000000000000000000),
("0xd1b37f03cb107424e9c4dd575ccd4f4cee57e6cd", 2000000000000000000000),
("0x7f993ddb7e02c282b898f6155f680ef5b9aff907", 20000000000000000000000),
("0xa3d583a7b65b23f60b7905f3e4aa62aac87f4227", 1046779000000000000000),
("0x526bb533b76e20c8ee1ebf123f1e9ff4148e40be", 197000000000000000000),
("0x2160b4c02cac0a81de9108de434590a8bfe68735", 1970000000000000000000),
("0x010007394b8b7565a1658af88ce463499135d6b7", 100000000000000000000),
("0x64457fa33b0832506c4f7d1180dce48f46f3e0ff", 2000000000000000000000),
("0xb51e558eb5512fbcfa81f8d0bd938c79ebb5242b", 715000000000000000000),
("0x94f13f9f0836a3ee2437a84922d2984dc0f7d53b", 2999916000000000000000),
("0x6bd457ade051795df3f2465c3839aed3c5dee978", 999925000000000000000),
("0xf3dbcf135acb9dee1a489c593c024f03c2bbaece", 2000000000000000000000),
("0x61b902c5a673885826820d1fe14549e4865fbdc2", 334703000000000000000),
("0x2acc9c1a32240b4d5b2f777a2ea052b42fc1271c", 41764000000000000000000),
("0x6ddfef639155daab0a5cb4953aa8c5afaa880453", 1820000000000000000000),
("0x96ff6f509968f36cb42cba48db32f21f5676abf8", 1970000000000000000000),
("0xb4c8170f7b2ab536d1d9a25bdd203ae1288dc3d5", 200000000000000000000),
("0x78d4f8c71c1e68a69a98f52fcb45da8af56ea1a0", 2000000000000000000000),
("0xdec99e972fca7177508c8e1a47ac22d768acab7c", 2000000000000000000000),
("0xa07aa16d74aee8a9a3288d52db1551d593883297", 600000000000000000000),
("0xcf1169041c1745e45b172435a2fc99b49ace2b00", 31960000000000000000),
("0x526cb09ce3ada3672eec1deb46205be89a4b563e", 2468000000000000000000),
("0xee6959de2b67967b71948c891ab00d8c8f38c7dc", 118200000000000000000),
("0xca7ba3ff536c7e5f0e153800bd383db8312998e0", 169600000000000000000),
("0x1ed06ee51662a86c634588fb62dc43c8f27e7c17", 200000000000000000000),
("0x730447f97ce9b25f22ba1afb36df27f9586beb9b", 820000000000000000000),
("0xae5c9bdad3c5c8a1220444aea5c229c1839f1d64", 477500000000000000000),
("0xa38306cb70baa8e49186bd68aa70a83d242f2907", 2000000000000000000000),
("0x71213fca313404204ecba87197741aa9dfe96338", 60000000000000000000),
("0x10e390ad2ba33d82b37388d09c4544c6b0225de5", 200000000000000000000),
("0x3b6e814f770748a7c3997806347605480a3fd509", 2000000000000000000000),
("0xfd452c3969ece3801c542020f1cdcaa1c71ed23d", 100000000000000000000000),
("0xe742b1e6069a8ffc3c4767235defb0d49cbed222", 800000000000000000000),
("0xd7225738dcf3578438f8e7c8b3837e42e04a262f", 445860000000000000000),
("0xcd0b0257e783a3d2c2e3ba9d6e79b75ef98024d4", 2945500000000000000000),
("0xe80e7fef18a5db15b01473f3ad6b78b2a2f8acd9", 500000000000000000000),
("0x261575e9cf59c8226fa7aaf91de86fb70f5ac3ae", 300022000000000000000),
("0x7e71171f2949fa0c3ac254254b1f0440e5e6a038", 40000000000000000000),
("0x96ea6ac89a2bac95347b51dba63d8bd5ebdedce1", 2000000000000000000000),
("0xe6ec5cf0c49b9c317e1e706315ef9eb7c0bf11a7", 17200000000000000000000),
("0x2b99b42e4f42619ee36baa7e4af2d65eacfcba35", 40000000000000000000000),
("0xc6e4cc0c7283fc1c85bc4813effaaf72b49823c0", 276926000000000000000),
("0xdbc1ce0e49b1a705d22e2037aec878ee0d75c703", 250000000000000000000),
("0x806f44bdeb688037015e84ff218049e382332a33", 1999000000000000000000),
("0x1a3a330e4fcb69dbef5e6901783bf50fd1c15342", 4200000000000000000000),
("0xd2a84f75675c62d80c88756c428eee2bcb185421", 1200000000000000000000),
("0xc593b546b7698710a205ad468b2c13152219a342", 1550000000000000000000),
("0x3f627a769e6a950eb87017a7cd9ca20871136831", 13790000000000000000000),
("0xf2d5763ce073127e2cedde6faba786c73ca94141", 7900000000000000000000),
("0x162110f29eac5f7d02b543d8dcd5bb59a5e33b73", 2000000000000000000000),
("0x59473cd300fffae240f5785626c65dfec792b9af", 20000000000000000000),
("0x4dcd11815818ae29b85d01367349a8a7fb12d06b", 7900000000000000000000),
("0x9329ffdc268babde8874b366406c81445b9b2d35", 422415000000000000000),
("0x0ab4281ebb318590abb89a81df07fa3af904258a", 500000000000000000000),
("0x875061ee12e820041a01942cb0e65bb427b00060", 2800000000000000000000),
("0xc9b698e898d20d4d4f408e4e4d061922aa856307", 40000000000000000000),
("0xca49a5f58adbefae23ee59eea241cf0482622eaa", 1430000000000000000000),
("0x196e85df7e732b4a8f0ed03623f4db9db0b8fa31", 21165000000000000000),
("0x4c760cd9e195ee4f2d6bce2500ff96da7c43ee91", 60000000000000000000000),
("0x024a098ae702bef5406c9c22b78bd4eb2cc7a293", 4000000000000000000000),
("0x9d81aea69aed6ad07089d61445348c17f34bfc5b", 300000000000000000000),
("0x76ab87dd5a05ad839a4e2fc8c85aa6ba05641730", 2000000000000000000000),
("0xc6e2f5af979a03fd723a1b6efa728318cf9c1800", 668500000000000000000),
("0x5db69fe93e6fb6fbd450966b97238b110ad8279a", 40000000000000000000000),
("0xa4259f8345f7e3a8b72b0fec2cf75e321fda4dc2", 1910000000000000000000),
("0x095030e4b82692dcf8b8d0912494b9b378ec9328", 1340000000000000000000),
("0x4b470f7ba030bc7cfcf338d4bf0432a91e2ea5ff", 2000000000000000000000),
("0x99c9f93e45fe3c1418c353e4c5ac3894eef8121e", 101870000000000000000),
("0xffac3db879a6c7158e8dec603b407463ba0d31cf", 1970000000000000000000),
("0xac8e87ddda5e78fcbcb9fa7fc3ce038f9f7d2e34", 2000000000000000000000),
("0x7a0589b143a8e5e107c9ac66a9f9f8597ab3e7ab", 1510990000000000000000),
("0xb7d581fe0af1ec383f3b3c416783f385146a7612", 20000000000000000000000),
("0xbb3fc0a29c034d710812dcc775c8cab9d28d6975", 1066806000000000000000),
("0x2c603ff0fe93616c43573ef279bfea40888d6ae7", 4740000000000000000000),
("0x15f2b7b16432ee50a5f55b41232f6334ed58bdc0", 400000000000000000000),
("0x7f3d7203c8a447f7bf36d88ae9b6062a5eee78ae", 6000000000000000000000),
("0xf067e1f1d683556a4cc4fd0c0313239f32c4cfd8", 1000000000000000000000),
("0x52738c90d860e04cb12f498d96fdb5bf36fc340e", 30000000000000000000),
("0x45781bbe7714a1c8f73b1c747921df4f84278b70", 2000000000000000000000),
("0x4a97e8fcf4635ea7fc5e96ee51752ec388716b60", 546000000000000000000),
("0x54939ff08921b467cf2946751d856378296c63ed", 1000000000000000000000),
("0x6485470e61db110aebdbafd536769e3c599cc908", 600000000000000000000),
("0xe20d1bcb71286dc7128a9fc7c6ed7f733892eef5", 1003400000000000000000),
("0xd6eea898d4ae2b718027a19ce9a5eb7300abe3ca", 27475000000000000000),
("0x014974a1f46bf204944a853111e52f1602617def", 2000000000000000000000),
("0x6aa5732f3b86fb8c81efbe6b5b47b563730b06c8", 1000000000000000000000),
("0x6107d71dd6d0eefb11d4c916404cb98c753e117d", 2000000000000000000000),
("0xdd7bcda65924aaa49b80984ae173750258b92847", 10000000000000000000000),
("0x4e7b54474d01fefd388dfcd53b9f662624418a05", 8000000000000000000000),
("0x24fc73d20793098e09ddab5798506224fa1e1850", 200000000000000000000),
("0x2b8488bd2d3c197a3d26151815b5a798d27168dc", 6680000000000000000000),
("0x949131f28943925cfc97d41e0cea0b262973a730", 2800000000000000000000),
("0x60b8d6b73b79534fb08bb8cbcefac7f393c57bfe", 1760000000000000000000),
("0xd6acc220ba2e51dfcf21d443361eea765cbd35d8", 20000000000000000000),
("0xc4c6cb723dd7afa7eb535615e53f3cef14f18118", 1999999000000000000000),
("0x4c9a862ad115d6c8274ed0b944bdd6a5500510a7", 100000000000000000000),
("0x85732c065cbd64119941aed430ac59670b6c51c4", 731345000000000000000),
("0x0126e12ebc17035f35c0e9d11dd148393c405d7a", 1999600000000000000000),
("0x472048cc609aeb242165eaaa8705850cf3125de0", 1000000000000000000000),
("0xd2edd1ddd6d86dc005baeb541d22b640d5c7cae5", 20000000000000000000),
("0x4549b15979255f7e65e99b0d5604db98dfcac8bf", 4000000000000000000000),
("0xc6c7c191379897dd9c9d9a33839c4a5f62c0890d", 4000085000000000000000),
("0xd367009ab658263b62c2333a1c9e4140498e1389", 2000000000000000000000),
("0x143f5f1658d9e578f4f3d95f80c0b1bd3933cbda", 1490000000000000000000),
("0x1a09fdc2c7a20e23574b97c69e93deba67d37220", 1998000000000000000000),
("0xac8b509aefea1dbfaf2bb33500d6570b6fd96d51", 1820000000000000000000),
("0x16ffac84032940f0121a09668b858a7e79ffa3bb", 3879210000000000000000),
("0xf338459f32a159b23db30ac335769ab2351aa63c", 30000000000000000000000),
("0xd82251456dc1380f8f5692f962828640ab9f2a03", 4879980000000000000000),
("0x47f4696bd462b20da09fb83ed2039818d77625b3", 149000000000000000000),
("0x3dde8b15b3ccbaa5780112c3d674f313bba68026", 1773000000000000000000),
("0xf70d637a845c06db6cdc91e6371ce7c4388a628e", 20000000000000000000),
("0x68295e8ea5afd9093fc0a465d157922b5d2ae234", 19982000000000000000),
("0x614e8bef3dd2c59b59a4145674401018351884ea", 20000000000000000000),
("0x4737d042dc6ae73ec73ae2517acea2fdd96487c5", 1000000000000000000000),
("0xcec6fc65853f9cce5f8e844676362e1579015f02", 2000000000000000000000),
("0xae47e2609cfafe369d66d415d939de05081a9872", 27060000000000000000000),
("0x09a928d528ec1b3e25ffc83e218c1e0afe8928c7", 18200000000000000000),
("0x9b444fd337e5d75293adcfff70e1ea01db023222", 100000000000000000000),
("0x168bdec818eafc6d2992e5ef54aa0e1601e3c561", 1000110000000000000000),
("0x353dbec42f92b50f975129b93c4c997375f09073", 1999000000000000000000),
("0x6fcc2c732bdd934af6ccd16846fb26ef89b2aa9b", 10001242000000000000000),
("0x6f2576da4de283bbe8e3ee69ddd66e5e711db3f5", 1260800000000000000000),
("0x3a3dd104cd7eb04f21932fd433ea7affd39369f5", 357500000000000000000),
("0xd44f4ac5fad76bdc1537a3b3af6472319b410d9d", 1600000000000000000000),
("0x3d9d6be57ff83e065985664f12564483f2e600b2", 2041600000000000000000),
("0x88f1045f19f2d3191816b1df18bb6e1435ad1b38", 240000000000000000000),
("0xddab75fb2ff9fecb88f89476688e2b00e367ebf9", 19400000000000000000000),
("0x092e815558402d67f90d6bfe6da0b2fffa91455a", 60000000000000000000),
("0xa7024cfd742c1ec13c01fea18d3042e65f1d5dee", 11272229000000000000000),
("0x7f46bb25460dd7dae4211ca7f15ad312fc7dc75c", 6685000000000000000000),
("0x93f18cd2526040761488c513174d1e7963768b2c", 2416500000000000000000),
("0x352f25babf4a690673e35195efa8f79d05848aad", 66800000000000000000000),
("0xf7b151cc5e571c17c76539dbe9964cbb6fe5de79", 2148000000000000000000),
("0xff3eee57c34d6dae970d8b311117c53586cd3502", 1700000000000000000000),
("0xae6f0c73fdd77c489727512174d9b50296611c4c", 6000000000000000000000),
("0x7819b0458e314e2b53bfe00c38495fd4b9fdf8d6", 20000000000000000000),
("0x7fdba031c78f9c096d62d05a369eeab0bccc55e5", 2800000000000000000000),
("0x735e328666ed5637142b3306b77ccc5460e72c3d", 1968682000000000000000),
("0x0bfbb6925dc75e52cf2684224bbe0550fea685d3", 1970000000000000000000),
("0x6be16313643ebc91ff9bb1a2e116b854ea933a45", 500000000000000000000),
("0xd6acffd0bfd99c382e7bd56ff0e6144a9e52b08e", 160000000000000000000),
("0x276a006e3028ecd44cdb62ba0a77ce94ebd9f10f", 1800000000000000000000),
("0x10711c3dda32317885f0a2fd8ae92e82069b0d0b", 4000000000000000000000),
("0x43cb9652818c6f4d6796b0e89409306c79db6349", 2000000000000000000000),
("0x7109dd011d15f3122d9d3a27588c10d77744508b", 2000000000000000000000),
("0x3497dd66fd118071a78c2cb36e40b6651cc82598", 109600000000000000000),
("0x9bf672d979b36652fc5282547a6a6bc212ae4368", 656000000000000000000),
("0xeaed16eaf5daab5bf0295e5e077f59fb8255900b", 4000000000000000000000),
("0x7ac58f6ffc4f8107ae6e30378e4e9f99c57fbb24", 40000000000000000000),
("0x45a570dcc2090c86a6b3ea29a60863dde41f13b5", 232500000000000000000),
("0x433a3b68e56b0df1862b90586bbd39c840ff1936", 2000000000000000000000),
("0xe8eaf12944092dc3599b3953fa7cb1c9761cc246", 1800000000000000000000),
("0xec11362cec810985d0ebbd7b73451444985b369f", 30000047000000000000000),
("0x78e83f80b3678c7a0a4e3e8c84dccde064426277", 1790000000000000000000),
("0x0cc67f8273e1bae0867fd42e8b8193d72679dbf8", 500000000000000000000),
("0xc70d856d621ec145303c0a6400cd17bbd6f5eaf7", 20000000000000000000),
("0xf468906e7edf664ab0d8be3d83eb7ab3f7ffdc78", 1700000000000000000000),
("0x3c286cfb30146e5fd790c2c8541552578de334d8", 10203000000000000000000),
("0xc401c427cccff10decb864202f36f5808322a0a8", 3329300000000000000000),
("0xafd019ff36a09155346b69974815a1c912c90aa4", 2000000000000000000000),
("0x96fe59c3dbb3aa7cc8cb62480c65e56e6204a7e2", 20000000000000000000000),
("0xa47779d8bc1c7bce0f011ccb39ef68b854f8de8f", 2000000000000000000000),
("0x58c650ced40bb65641b8e8a924a039def46854df", 18500000000000000000),
("0x86f4f40ad984fbb80933ae626e0e42f9333fdd41", 1000000000000000000000),
("0xb22d5055d9623135961e6abd273c90deea16a3e7", 1400000000000000000000),
("0xee3564f5f1ba0f94ec7bac164bddbf31c6888b55", 100000000000000000000),
("0xcf26b47bd034bc508e6c4bcfd6c7d30034925761", 1800000000000000000000),
("0xe87dbac636a37721df54b08a32ef4959b5e4ff82", 2000000000000000000000),
("0x3bf86ed8a3153ec933786a02ac090301855e576b", 450000000000000000000000),
("0xcfd2728dfb8bdbf3bf73598a6e13eaf43052ea2b", 170000000000000000000),
("0x85b16f0b8b34dff3804f69e2168a4f7b24d1042b", 317000000000000000000),
("0x84db1459bb00812ea67ecb3dc189b72187d9c501", 148851000000000000000),
("0x8c3a9ee71f729f236cba3867b4d79d8ceee25dbc", 100000000000000000000),
("0xe677c31fd9cb720075dca49f1abccd59ec33f734", 7800000000000000000000),
("0x8889448316ccf14ed86df8e2f478dc63c4338340", 15200000000000000000),
("0xb279c7d355c2880392aad1aa21ee867c3b3507df", 1261000000000000000000),
("0x12b5e28945bb2969f9c64c63cc05b6f1f8d6f4d5", 7722162000000000000000),
("0x8d2303341e1e1eb5e8189bde03f73a60a2a54861", 100000000000000000000),
("0x94d81074db5ae197d2bb1373ab80a87d121c4bd3", 9400000000000000000000),
("0x752c9febf42f66c4787bfa7eb17cf5333bba5070", 1966448000000000000000),
("0x16816aac0ede0d2d3cd442da79e063880f0f1d67", 2000000000000000000000),
("0xdaac91c1e859d5e57ed3084b50200f9766e2c52b", 400000000000000000000),
("0x32c2fde2b6aabb80e5aea2b949a217f3cb092283", 5614827000000000000000),
("0xcdab46a5902080646fbf954204204ae88404822b", 544942000000000000000),
("0xfdf42343019b0b0c6bf260b173afab7e45b9d621", 1999944000000000000000),
("0x791f6040b4e3e50dcf3553f182cd97a90630b75d", 4000000000000000000000),
("0x4b762166dd1118e84369f804c75f9cd657bf730c", 500000000000000000000),
("0xa76d3f156251b72c0ccf4b47a3393cbd6f49a9c5", 1337000000000000000000),
("0xc5eb42295e9cadeaf2af12dede8a8d53c579c469", 3820000000000000000000),
("0xdb9371b30c4c844e59e03e924be606a938d1d310", 2000000000000000000000),
("0x2cd39334ac7eac797257abe3736195f5b4b5ce0f", 99964000000000000000),
("0xad44357e017e244f476931c7b8189efee80a5d0a", 300000000000000000000),
("0x4ca7b717d9bc8793b04e051a8d23e1640f5ba5e3", 1248980000000000000000),
("0x73e4a2b60cf48e8baf2b777e175a5b1e4d0c2d8f", 100000000000000000000),
("0x5a1d2d2d1d520304b6208849570437eb3091bb9f", 1970000000000000000000),
("0x53047dc8ac9083d90672e8b3473c100ccd278323", 40000000000000000000),
("0x26fe174cbf526650e0cd009bd6126502ce8e684d", 11640000000000000000000),
("0xe2df23f6ea04becf4ab701748dc0963184555cdb", 2000000000000000000000),
("0xc1170dbaadb3dee6198ea544baec93251860fda5", 1200000000000000000000),
("0x8bbeacfc29cfe93402db3c41d99ab759662e73ec", 2000000000000000000000),
("0x165305b787322e25dc6ad0cefe6c6f334678d569", 2000000000000000000000),
("0x095457f8ef8e2bdc362196b9a9125da09c67e3ab", 200000000000000000000),
("0x702802f36d00250fab53adbcd696f0176f638a49", 2000000000000000000000),
("0x489334c2b695c8ee0794bd864217fb9fd8f8b135", 18200000000000000000),
("0xfa8cf4e627698c5d5788abb7880417e750231399", 4244640000000000000000),
("0x3329eb3baf4345d600ced40e6e9975656f113742", 4999711000000000000000),
("0xb4dd5499daeb2507fb2de12297731d4c72b16bb0", 20000000000000000000),
("0x88c2516a7cdb09a6276d7297d30f5a4db1e84b86", 4000000000000000000000),
("0x612ced8dc0dc9e899ee46f7962333315f3f55e44", 338830000000000000000),
("0xd71e43a45177ad51cbe0f72184a5cb503917285a", 200000000000000000000),
("0x2fb566c94bbba4e3cb67cdda7d5fad7131539102", 2000000000000000000000),
("0x03be5b4629aefbbcab9de26d39576cb7f691d764", 200550000000000000000),
("0x025367960304beee34591118e9ac2d1358d8021a", 2000000000000000000000),
("0xa5d5b8b62d002def92413710d13b6ff8d4fc7dd3", 400000000000000000000),
("0xdf3b72c5bd71d4814e88a62321a93d4011e3578b", 4000000000000000000000),
("0x3588895ac9fbafec012092dc05c0c302d90740fa", 3000000000000000000000),
("0x6021e85a8814fce1e82a41abd1d3b2dad2faefe0", 2000000000000000000000),
("0x17ee9f54d4ddc84d670eff11e54a659fd72f4455", 16000000000000000000000),
("0x873c6f70efb6b1d0f2bbc57eebcd70617c6ce662", 1013478000000000000000),
("0x1fcc7ce6a8485895a3199e16481f72e1f762defe", 1000000000000000000000),
("0xd0a7209b80cf60db62f57d0a5d7d521a69606655", 160000000000000000000),
("0xa514d00edd7108a6be839a638db2415418174196", 30000000000000000000000),
("0x046377f864b0143f282174a892a73d3ec8ec6132", 191000000000000000000),
("0xc126573d87b0175a5295f1dd07c575cf8cfa15f2", 10000000000000000000000),
("0x0e123d7da6d1e6fac2dcadd27029240bb39052fe", 1000000000000000000000),
("0xad5a8d3c6478b69f657db3837a2575ef8e1df931", 36990000000000000000),
("0xdb882eacedd0eff263511b312adbbc59c6b8b25b", 9100000000000000000000),
("0x0b43bd2391025581d8956ce42a072579cbbfcb14", 18800000000000000000),
("0xaffea0473722cb7f0e0e86b9e11883bf428d8d54", 1940000000000000000000),
("0xe32b1c4725a1875449e98f970eb3e54062d15800", 200000000000000000000),
("0x98f4af3af0aede5fafdc42a081ecc1f89e3ccf20", 9400000000000000000000),
("0x3b4768fd71e2db2cbe7fa050483c27b4eb931df3", 2000000000000000000000),
("0xd5f7c41e07729dfa6dfc64c4423160a22c609fd3", 1790000000000000000000),
("0xd944c8a69ff2ca1249690c1229c7192f36251062", 1970000000000000000000),
("0x5ae64e853ba0a51282cb8db52e41615e7c9f733f", 2000000000000000000000),
("0xb13f93af30e8d7667381b2b95bc1a699d5e3e129", 420000000000000000000),
("0x8a20e5b5cee7cd1f5515bace3bf4f77ffde5cc07", 80000000000000000000),
("0x2448596f91c09baa30bc96106a2d37b5705e5d28", 2000000000000000000000),
("0xccca24d8c56d6e2c07db086ec07e585be267ac8d", 200000000000000000000),
("0xf67bb8e2118bbcd59027666eedf6943ec9f880a5", 4000000000000000000000),
("0x7ae659eb3bc46852fa86fac4e21c768d50388945", 286000000000000000000),
("0x467e0ed54f3b76ae0636176e07420815a021736e", 2000000000000000000000),
("0xa46cd237b63eea438c8e3b6585f679e4860832ac", 1000000000000000000000),
("0x6b760d4877e6a627c1c967bee451a8507ddddbab", 910000000000000000000),
("0x593044670faeff00a55b5ae051eb7be870b11694", 133700000000000000000),
("0x533c06928f19d0a956cc28866bf6c8d8f4191a94", 292320000000000000000),
("0x262dc1364ccf6df85c43268ee182554dae692e29", 4927600000000000000000),
("0xe4368bc1420b35efda95fafbc73090521916aa34", 4000000000000000000000),
("0xfeb92d30bf01ff9a1901666c5573532bfa07eeec", 1000000000000000000000),
("0xee25b9a7032679b113588ed52c137d1a053a1e94", 199820000000000000000),
("0x20134cbff88bfadc466b52eceaa79857891d831e", 1000000000000000000000),
("0x07b1a306cb4312df66482c2cae72d1e061400fcd", 20000000000000000000000),
("0xe791d585b89936b25d298f9d35f9f9edc25a2932", 2000000000000000000000),
("0x2e6933543d4f2cc00b5350bd8068ba9243d6beb0", 2000000000000000000000),
("0xdae0d33eaa341569fa9ff5982684854a4a328a6e", 1000000000000000000000),
("0x125cc5e4d56b2bcc2ee1c709fb9e68fb177440bd", 2000000000000000000000),
("0xec99e95dece46ffffb175eb6400fbebb08ee9b95", 100000000000000000000),
("0xc538a0ff282aaa5f4b75cfb62c70037ee67d4fb5", 2000000000000000000000),
("0x60676d1fa21fca052297e24bf96389c5b12a70d7", 241500000000000000000),
("0x4b3dfbdb454be5279a3b8addfd0ed1cd37a9420d", 2000000000000000000000),
("0xcdb597299030183f6e2d238533f4642aa58754b6", 400000000000000000000),
("0x1ef2dcbfe0a500411d956eb8c8939c3d6cfe669d", 776000000000000000000),
("0xa7247c53d059eb7c9310f628d7fc6c6a0a773f08", 500000000000000000000),
("0x9799ca21dbcf69bfa1b3f72bac51b9e3ca587cf9", 1700000000000000000000),
("0xddf95c1e99ce2f9f5698057c19d5c94027ee4a6e", 6000000000000000000000),
("0x83563bc364ed81a0c6da3b56ff49bbf267827a9c", 17332000000000000000000),
("0xa192698007cc11aa603d221d5feea076bcf7c30d", 2000000000000000000000),
("0x0134ff38155fabae94fd35c4ffe1d79de7ef9c59", 985000000000000000000),
("0x80977316944e5942e79b0e3abad38da746086519", 38800000000000000000),
("0x193d37ed347d1c2f4e35350d9a444bc57ca4db43", 60000000000000000000),
("0x009a6d7db326679b77c90391a7476d238f3ba33e", 200200000000000000000),
("0x337b3bdf86d713dbd07b5dbfcc022b7a7b1946ae", 3980000000000000000000),
("0x7de7fe419cc61f91f408d234cc80d5ca3d054d99", 20000000000000000000),
("0xf47bb134da30a812d003af8dccb888f44bbf5724", 5190000000000000000000),
("0xfd920f722682afb5af451b0544d4f41b3b9d5742", 2330200000000000000000),
("0x0a917f3b5cb0b883047fd9b6593dbcd557f453b9", 1000000000000000000000),
("0xce9786d3712fa200e9f68537eeaa1a06a6f45a4b", 1790000000000000000000),
("0x9ab98d6dbb1eaae16d45a04568541ad3d8fe06cc", 272451000000000000000),
("0x0b7bb342f01bc9888e6a9af4a887cbf4c2dd2caf", 16000000000000000000000),
("0x4c0b1515dfced7a13e13ee12c0f523ae504f032b", 50000000000000000000000),
("0xac2889b5966f0c7f9edb42895cb69d1c04f923a2", 5000000000000000000000),
("0xd008513b27604a89ba1763b6f84ce688b346945b", 1000000000000000000000),
("0xa4b09de6e713dc69546e76ef0acf40b94f0241e6", 322656000000000000000),
("0xb153f828dd076d4a7c1c2574bb2dee1a44a318a8", 400000000000000000000),
("0x02ade5db22f8b758ee1443626c64ec2f32aa0a15", 20000000000000000000000),
("0x0a0650861f785ed8e4bf1005c450bbd06eb48fb6", 3066860000000000000000),
("0xb75149e185f6e3927057739073a1822ae1cf0df2", 4000086000000000000000),
("0x84cb7da0502df45cf561817bbd2362f451be02da", 1337000000000000000000),
("0xc91bb562e42bd46130e2d3ae4652b6a4eb86bc0f", 540000000000000000000),
("0xb234035f7544463ce1e22bc553064684c513cd51", 249750000000000000000),
("0xe5e33800a1b2e96bde1031630a959aa007f26e51", 1337000000000000000000),
("0xae5ce3355a7ba9b332760c0950c2bc45a85fa9a0", 400000000000000000000),
("0xe6f5eb649afb99599c414b27a9c9c855357fa878", 2674000000000000000000),
("0x7010be2df57bd0ab9ae8196cd50ab0c521aba9f9", 1970000000000000000000),
("0xca4288014eddc5632f5facb5e38517a8f8bc5d98", 340000000000000000000),
("0x2784903f1d7c1b5cd901f8875d14a79b3cbe2a56", 22388000000000000000000),
("0xf8dce867f0a39c5bef9eeba609229efa02678b6c", 2000000000000000000000),
("0xe020e86362b487752836a6de0bc02cd8d89a8b6a", 6000000000000000000000),
("0xc4088c025f3e85013f5439fb3440a17301e544fe", 2325000000000000000000),
("0xbefb448c0c5f683fb67ee570baf0db5686599751", 1970000000000000000000),
("0x2f187d5a704d5a338c5b2876a090dce964284e29", 4000000000000000000000),
("0xec0e18a01dc4dc5daae567c3fa4c7f8f9b590205", 315900000000000000000),
("0x637f5869d6e4695f0eb9e27311c4878aff333380", 1969212000000000000000),
("0xd1100dd00fe2ddf18163ad964d0b69f1f2e9658a", 5959598000000000000000),
("0x17ef4acc1bf147e326749d10e677dcffd76f9e06", 39980000000000000000000),
("0x200dfc0b71e359b2b465440a36a6cdc352773007", 1500000000000000000000),
("0xefe0675da98a5dda70cd96196b87f4e726b43348", 1164000000000000000000),
("0xd5bd5e8455c130169357c471e3e681b7996a7276", 841500000000000000000),
("0x9c7b6dc5190fe2912963fcd579683ec7395116b0", 776000000000000000000),
("0xb105dd3d987cffd813e9c8500a80a1ad257d56c6", 1999944000000000000000),
("0x145250b06e4fa7cb2749422eb817bdda8b54de5f", 219000000000000000000),
("0xd96db33b7b5a950c3efa2dc31b10ba10a532ef87", 2000000000000000000000),
("0xaf529bdb459cc185bee5a1c58bf7e8cce25c150d", 197000000000000000000),
("0x185546e8768d506873818ac9751c1f12116a3bef", 200000000000000000000),
("0x51d24bc3736f88dd63b7222026886630b6eb878d", 2000000000000000000000),
("0x69af28b0746cac0da17084b9398c5e36bb3a0df2", 1004700000000000000000),
("0x76f83ac3da30f7092628c7339f208bfc142cb1ee", 2842600000000000000000),
("0x00f463e137dcf625fbf3bca39eca98d2b968cf7f", 5910000000000000000000),
("0x2084fce505d97bebf1ad8c5ff6826fc645371fb2", 30000000000000000000),
("0x53a714f99fa00fef758e23a2e746326dad247ca7", 1490000000000000000000),
("0x0bf064428f83626722a7b5b26a9ab20421a7723e", 133700000000000000000),
("0xac6f68e837cf1961cb14ab47446da168a16dde89", 1337000000000000000000),
("0x4b3c7388cc76da3d62d40067dabccd7ef0433d23", 100076000000000000000),
("0xdeb9a49a43873020f0759185e20bbb4cf381bb8f", 211628000000000000000),
("0x5bf9f2226e5aeacf1d80ae0a59c6e38038bc8db5", 6000000000000000000000),
("0x9d0e7d92fb305853d798263bf15e97c72bf9d7e0", 1000000000000000000000),
("0x2b5c60e84535eeb4d580de127a12eb2677ccb392", 20000000000000000000000),
("0xd8d65420c18c2327cc5af97425f857e4a9fd51b3", 1760000000000000000000),
("0x30ec9392244a2108c987bc5cdde0ed9f837a817b", 1560562000000000000000),
("0x56a1d60d40f57f308eebf087dee3b37f1e7c2cba", 1159600000000000000000),
("0xa9a1cdc33bfd376f1c0d76fb6c84b6b4ac274d68", 5000000000000000000000),
("0xa67f38819565423aa85f3e3ab61bc763cbab89dd", 2130000000000000000000),
("0x62d5cc7117e18500ac2f9e3c26c86b0a94b0de15", 105000000000000000000),
("0x4970d3acf72b5b1f32a7003cf102c64ee0547941", 140000000000000000000000),
("0x76628150e2995b5b279fc83e0dd5f102a671dd1c", 40000000000000000000000),
("0x3d8f39881b9edfe91227c33fa4cdd91e678544b0", 86111000000000000000),
("0xff0b7cb71da9d4c1ea6ecc28ebda504c63f82fd1", 1043000000000000000000),
("0x8d795c5f4a5689ad62da961671f028065286d554", 2048000000000000000000),
("0xbe2346a27ff9b702044f500deff2e7ffe6824541", 20000000000000000000),
("0x0dbd417c372b8b0d01bcd944706bd32e60ae28d1", 340000000000000000000),
("0x467fbf41441600757fe15830c8cd5f4ffbbbd560", 10000000000000000000000),
("0x090cd67b60e81d54e7b5f6078f3e021ba65b9a1e", 1000000000000000000000),
("0x55a4cac0cb8b582d9fef38c5c9fff9bd53093d1f", 1970000000000000000000),
("0x3b7b4f53c45655f3dc5f017edc23b16f9bc536fa", 100000000000000000000),
("0xd508d39c70916f6abc4cc7f999f011f077105802", 100470000000000000000),
("0x037dd056e7fdbd641db5b6bea2a8780a83fae180", 140000000000000000000),
("0x660557bb43f4be3a1b8b85e7df7b3c5bcd548057", 6000000000000000000000),
("0x02089361a3fe7451fb1f87f01a2d866653dc0b07", 39976000000000000000),
("0xc4bec96308a20f90cab18399c493fd3d065abf45", 14000000000000000000000),
("0xcca07bb794571d4acf041dad87f0d1ef3185b319", 2000000000000000000000),
("0xf2d0e986d814ea13c8f466a0538c53dc922651f0", 1380000000000000000000),
("0x662cfa038fab37a01745a364e1b98127c503746d", 3940000000000000000000),
("0x3336c3ef6e8b50ee90e037b164b7a8ea5faac65d", 272712000000000000000),
("0x30e33358fc21c85006e40f32357dc8895940aaf0", 1910000000000000000000),
("0x41a9a404fc9f5bfee48ec265b12523338e29a8bf", 388000000000000000000),
("0x6af235d2bbe050e6291615b71ca5829658810142", 3000000000000000000000),
("0xfd5a63157f914fd398eab19c137dd9550bb7715c", 100000000000000000000),
("0x8a4314fb61cd938fc33e15e816b113f2ac89a7fb", 432800000000000000000),
("0xb216dc59e27c3d7279f5cd5bb2becfb2606e14d9", 400000000000000000000),
("0xf5a5459fcdd5e5b273830df88eea4cb77ddadfb9", 74500000000000000000),
("0xdf31025f5649d2c6eea41ed3bdd3471a790f759a", 20000000000000000000),
("0x721f9d17e5a0e74205947aeb9bc6a7938961038f", 51900000000000000000),
("0x08d0864dc32f9acb36bf4ea447e8dd6726906a15", 2000200000000000000000),
("0x54575c3114751e3c631971da6a2a02fd3ffbfcc8", 1940000000000000000000),
("0x8f60895fbebbb5017fcbff3cdda397292bf25ba6", 429177000000000000000),
("0x91fe8a4c6164df8fa606995d6ba7adcaf1c893ce", 17000000000000000000000),
("0x889087f66ff284f8b5efbd29493b706733ab1447", 9850000000000000000000),
("0x051633080d07a557adde319261b074997f14692d", 5800000000000000000000),
("0x59a12df2e3ef857aceff9306b309f6a500f70134", 1000000000000000000000),
("0x9f64a8e8dacf4ade30d10f4d59b0a3d5abfdbf74", 1000060000000000000000),
("0x8846928d683289a2d11df8db7a9474988ef01348", 10000000000000000000000),
("0xdff1b220de3d8e9ca4c1b5be34a799bcded4f61c", 385428000000000000000),
("0x7e7c1e9a61a08a83984835c70ec31d34d3eaa87f", 191000000000000000000),
("0xfe210b8f04dc6d4f76216acfcbd59ba83be9b630", 20000000000000000000),
("0xdc8c2912f084a6d184aa73638513ccbc326e0102", 1295000000000000000000),
("0xdddd7b9e6eab409b92263ac272da801b664f8a57", 500000000000000000000000),
("0x86a5f8259ed5b09e188ce346ee92d34aa5dd93fa", 200000000000000000000),
("0xdc1f1979615f082140b8bb78c67b27a1942713b1", 60000000000000000000),
("0xea66e7b84dcdbf36eea3e75b85382a75f1a15d96", 1729135000000000000000),
("0x039e7a4ebc284e2ccd42b1bdd60bd6511c0f7706", 17300000000000000000),
("0x36bfe1fa3b7b70c172eb042f6819a8972595413e", 1000000000000000000000),
("0x039ef1ce52fe7963f166d5a275c4b1069fe3a832", 400008000000000000000),
("0xf1df55dcc34a051012b575cb968bc9c458ea09c9", 4000000000000000000000),
("0x168b5019b818691644835fe69bf229e17112d52c", 28000000000000000000000),
("0xf60bd735543e6bfd2ea6f11bff627340bc035a23", 2000000000000000000000),
("0x2cbb0c73df91b91740b6693b774a7d05177e8e58", 1850000000000000000000),
("0x9ffcf5ef46d933a519d1d16c6ba3189b27496224", 1000000000000000000000),
("0x0e11d77a8977fac30d268445e531149b31541a24", 2000000000000000000000),
("0xdfb1626ef48a1d7d7552a5e0298f1fc23a3b482d", 1713860000000000000000),
("0xcc943be1222cd1400a2399dd1b459445cf6d54a9", 12530000000000000000000),
("0xb37c2b9f50637bece0ca959208aefee6463ba720", 400000000000000000000),
("0x96b906ea729f4655afe3e57d35277c967dfa1577", 1000000000000000000000),
("0x7995bd8ce2e0c67bf1c7a531d477bca1b2b97561", 5945100000000000000000),
("0x96f820500b70f4a3e3239d619cff8f222075b135", 200000000000000000000),
("0xad3565d52b688added08168b2d3872d17d0a26ae", 100000000000000000000),
("0x9e7c2050a227bbfd60937e268cea3e68fea8d1fe", 100000000000000000000),
("0x7e59dc60be8b2fc19abd0a5782c52c28400bce97", 1000000000000000000000),
("0x01ed5fba8d2eab673aec042d30e4e8a611d8c55a", 2000000000000000000000),
("0x59a087b9351ca42f58f36e021927a22988284f38", 18500000000000000000),
("0x2fe0023f5722650f3a8ac01009125e74e3f82e9b", 3000000000000000000000),
("0xbd1803370bddb129d239fd16ea8526a6188ae58e", 500000000000000000000),
("0xc70527d444c490e9fc3f5cc44e66eb4f306b380f", 4000000000000000000000),
("0x0f206e1a1da7207ea518b112418baa8b06260328", 600000000000000000000),
("0x6e1a046caf5b4a57f4fd4bc173622126b4e2fd86", 1790000000000000000000),
("0x84008a72f8036f3feba542e35078c057f32a8825", 100000000000000000000),
("0x246291165b59332df5f18ce5c98856fae95897d6", 1700000000000000000000),
("0x7e99dfbe989d3ba529d19751b7f4317f8953a3e2", 400000000000000000000),
("0x748c285ef1233fe4d31c8fb1378333721c12e27a", 2000000000000000000000),
("0x3dd12e556a603736feba4a6fa8bd4ac45d662a04", 167450000000000000000000),
("0xd0ae735d915e946866e1fea77e5ea466b5cadd16", 2000000000000000000000),
("0x4f767bc8794aef9a0a38fea5c81f14694ff21a13", 512200000000000000000),
("0x0e2f8e28a681f77c583bd0ecde16634bdd7e00cd", 95060000000000000000),
("0xd74a6e8d6aab34ce85976814c1327bd6ea0784d2", 100000000000000000000000),
("0x629be7ab126a5398edd6da9f18447e78c692a4fd", 2000000000000000000000),
("0x2e46fcee6a3bb145b594a243a3913fce5dad6fba", 10000000000000000000000),
("0xe39b11a8ab1ff5e22e5ae6517214f73c5b9b55dc", 2000000000000000000000),
("0x119aa64d5b7d181dae9d3cb449955c89c1f963fa", 700000000000000000000),
("0xce079f51887774d8021cb3b575f58f18e9acf984", 180000000000000000000),
("0x550c306f81ef5d9580c06cb1ab201b95c748a691", 665800000000000000000),
("0x06dc7f18cee7edab5b795337b1df6a9e8bd8ae59", 400000000000000000000),
("0xe21c778ef2a0d7f751ea8c074d1f812243863e4e", 5308559000000000000000),
("0x45d4b54d37a8cf599821235f062fa9d170ede8a4", 324000000000000000000),
("0x893a6c2eb8b40ab096b4f67e74a897b840746e86", 1730000000000000000000),
("0xd44d81e18f46e2cfb5c1fcf5041bc8569767d100", 36381800000000000000000),
("0xc5de1203d3cc2cea31c82ee2de5916880799eafd", 5000000000000000000000),
("0x7f0f04fcf37a53a4e24ede6e93104e78be1d3c9e", 2000000000000000000000),
("0x3ce1dc97fcd7b7c4d3a18a49d6f2a5c1b1a906d7", 200000000000000000000),
("0xac4ee9d502e7d2d2e99e59d8ca7d5f00c94b4dd6", | |
<reponame>jepegit/cellpy
# -*- coding: utf-8 -*-
"""easyplot module for cellpy. It provides easy plotting of any cellpy-readable data using matplotlib.
Author: <NAME>
Date: 01.07.2021
"""
import logging
import os
import warnings
from pathlib import Path
from re import S
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib import lines
from matplotlib.artist import kwdoc
from matplotlib.lines import Line2D
from matplotlib.scale import LogScale
from matplotlib.ticker import FuncFormatter
import cellpy
from cellpy import log
from cellpy.utils.batch_tools.batch_journals import LabJournal
from cellpy.parameters.internal_settings import (
get_headers_journal,
keys_journal_session,
)
hdr_journal = get_headers_journal()
# Dictionary of all possible user input arguments(as keys) with example values of correct type
# Value is a tuple (immutable) of type and default value.
USER_PARAMS = {
"cyclelife_plot": (bool, True),
"cyclelife_separate_data": (
bool,
False,
), # will plot each cyclelife datafile in separate plots
"cyclelife_percentage": (bool, False),
"cyclelife_coulombic_efficiency": (bool, False),
"cyclelife_coulombic_efficiency_ylabel": (str, "Coulombic efficiency [%]"),
"cyclelife_charge_c_rate": (bool, False),
"cyclelife_discharge_c_rate": (bool, False),
"cyclelife_c_rate_ylabel": (str, "Effective C-rate"),
"cyclelife_ir": (bool, False), # Allows user to plot IR data aswell
"cyclelife_xlabel": (str, "Cycles"),
"cyclelife_ylabel": (str, r"Capacity $\left[\frac{mAh}{g}\right]$"),
"cyclelife_ylabel_percent": (str, "Capacity retention [%]"),
"cyclelife_legend_outside": (
bool,
False,
), # if True, the legend is placed outside the plot
"cyclelife_degradation_slope": (
bool,
False,
), # Adds simple degradation slope regression to plot
"capacity_determination_from_ratecap": (
bool,
False,
), # If True, uses the ratecap and capacity to determine the exp capacity
"galvanostatic_plot": (bool, True),
"galvanostatic_potlim": (tuple, None), # min and max limit on potential-axis
"galvanostatic_caplim": (tuple, None),
"galvanostatic_xlabel": (str, r"Capacity $\left[\frac{mAh}{g}\right]$"),
"galvanostatic_ylabel": (str, "Cell potential [V]"),
"galvanostatic_normalize_capacity": (
bool,
False,
), # Normalizes all cycles' capacity to 1.
"dqdv_plot": (bool, False),
"dqdv_potlim": (tuple, None), # min and max limit on potential-axis
"dqdv_dqlim": (tuple, None),
"dqdv_xlabel": (
str,
r"dQ/dV $\left[\frac{mAh}{gV}\right]$",
), # TODO what unit? jees
"dqdv_ylabel": (str, "Cell potential [V]"),
"specific_cycles": (list, None),
"exclude_cycles": (list, None),
"all_in_one": (
bool,
False,
), # Decides if everything should be plotted in the same plot in GC and dQdV plot
"only_dischg": (bool, False), # Only show discharge curves
"only_chg": (bool, False), # Only show charge curves
"outpath": (str, "./"),
"outtype": (str, ".png"), # What file format to save in
"outname": (str, None), # Overrides the automatic filename generation
"figsize": (tuple, (6, 4)), # 6 inches wide, 4 inches tall
"figres": (int, 100), # Dots per Inch
"figtitle": (str, "Title"), # None = original filepath
"save_figures": (bool, True),
"save_journal": (bool, False), # Save journal
}
def help():
"""Method of the EasyPlot class which prints some helptext in addition to all supported params."""
## Prints out help page of this module
help_str = (
"The easyplot extension to cellpy aims to easily plot data in a pretty manner.\n"
"In order to use this function, you must import cellpy, and easyplot from cellpy.utils.\n"
"\n"
"Usage:\n"
"Create list of datafiles you want to plot on the following format:\n"
"\n"
"files = [\n"
"\t'./folder/filename.ext',\n"
"\t'./folder/filename2.ext',\n"
"\t]\n"
"\n"
"And then call the easyplot.plot function with the files list as the first parameter, and any optional keyword arguments.\n"
"Here is an example of the use of all keyword arguments:\n"
)
for kw in USER_PARAMS:
if type(USER_PARAMS[kw][1]) == str:
insert = "'" + USER_PARAMS[kw][1] + "'"
else:
insert = str(USER_PARAMS[kw][1])
help_str += "\t" + kw + " = " + insert + ",\n"
print(help_str)
class EasyPlot:
"""Main easyplot class.
Takes all the inputs from the user in its kwargs upon object initialization.
Gathers data, handles and plots it when object.plot() is called.
Help: type easyplot.help()
"""
def __init__(self, files=None, nicknames=None, journal=None, **kwargs):
"""Initialization function of the EasyPlot class.
Input parameters:
filenames (list of strings).
nicknames (list of strings), must match length of filenames.
journal (str or pathlib.Path object): journal file name (should not be used if files is given).
any kwargs: use easyplot.help() to print all kwargs to terminal.
Returns:
easyplot object
Most basic usage:
ezpltobj = easyplot.EasyPlot(["name1", "name2"], None)"""
# Make all user input variables of self
self.files = files
self.nicknames = nicknames
self.kwargs = kwargs
# More needed variables
self.figs = []
self.file_data = []
self.use_arbin_sql = False
if journal is not None:
self.journal_file = Path(journal)
else:
self.journal_file = None
self.journal = None
# Dictionary of all possible user input arguments(as keys) with example values of correct type
# Value is a tuple (immutable) of type and default value.
self.user_params = USER_PARAMS
# Create 'empty' attributes for later use
self.outpath = None
self.masses = None
self.labels = None
self.nom_caps = None
self.colors = None
# List of available colors
# Fill in the rest of the variables from self.user_params if the user didn't specify
self.fill_input()
# Verify that the user input is sufficient
self.verify_input()
self._generate_list_of_available_colors()
def _generate_list_of_available_colors(self):
if 19 >= len(self.files) > 10:
self.colors = [
"#e6194b",
"#3cb44b",
"#ffe119",
"#4363d8",
"#f58231",
"#911eb4",
"#46f0f0",
"#f032e6",
"#bcf60c",
"#fabebe",
"#008080",
"#e6beff",
"#9a6324",
"#fffac8",
"#800000",
"#aaffc3",
"#808000",
"#ffd8b1",
"#000075",
"#808080",
"#000000",
]
warnings.warn(
"You inserted more than 10 datafiles! In a desperate attempt to keep "
"the plots tidy, another colorpalette with 19 distinct colors were chosen."
)
elif len(self.files) > 19:
warnings.warn(
"You inserted more than 19 datafiles! We do not have that "
"many colors in the palette, this some colors are beeing recycled. "
"Keep track of the filenames and legends and make sure this doesn't confuse you."
)
else:
self.colors = [
"tab:blue",
"tab:orange",
"tab:green",
"tab:red",
"tab:purple",
"tab:brown",
"tab:pink",
"tab:gray",
"tab:olive",
"tab:cyan",
] * 5
def plot(self):
"""This is the method the user calls on his/hers easyplot object in order to gather the data and plot it.
Usage: object.plot()"""
# Load all cellpy files
logging.debug("starting plotting")
for file in self.files:
if isinstance(file, (list, tuple)):
logging.debug("linked files provided - need to merge")
linked_files = True
else:
linked_files = False
# If using arbin sql
if self.use_arbin_sql:
cpobj = cellpy.get(
filename=file, instrument="arbin_sql"
) # Initiate cellpy object
else: # Not Arbin SQL? Then its probably a local file
# Check that file(s) exist
if linked_files:
file_name = "_".join(file)
for _f in file:
if not os.path.isfile(_f):
logging.error("File not found: " + str(_f))
raise FileNotFoundError
else:
file_name = file
if not os.path.isfile(file):
logging.error("File not found: " + str(file))
print(os.getcwd())
raise FileNotFoundError
cpobj = cellpy.get(filename=file) # Load regular file
# Check that we get data
if cpobj is None:
warnings.warn(
f"File reader returned no data for filename {file}. Please make sure that the file exists or "
f"that the data exists in an eventual database."
)
# Get ID of all cycles
cyc_nums = cpobj.get_cycle_numbers()
# Only get the cycles which both exist in data, and that the user want
if self.kwargs["specific_cycles"] is not None:
cyc_not_available = (
set(cyc_nums) ^ set(self.kwargs["specific_cycles"])
) & set(self.kwargs["specific_cycles"])
if len(cyc_not_available) > 0:
warn_str = (
f"You want to plot cycles which are not available in the data! Datafile(s): "
f"{file}"
f", Cycle(s): {str(cyc_not_available)}"
)
warnings.warn(warn_str)
cyc_nums = list(
set(cyc_nums).intersection(self.kwargs["specific_cycles"])
)
if self.kwargs["exclude_cycles"] is not None:
cyc_nums = list(set(cyc_nums) - set(self.kwargs["exclude_cycles"]))
color = self.give_color() # Get a color for the data
self.file_data.append((cpobj, cyc_nums, color, file_name))
# Check kwargs/input parameters to see what plots to make
if self.kwargs["cyclelife_plot"]:
self.plot_cyclelife()
if self.kwargs["galvanostatic_plot"] and not self.kwargs["dqdv_plot"]:
self.plot_gc()
if self.kwargs["dqdv_plot"] and not self.kwargs["galvanostatic_plot"]:
self.plot_dQdV()
if self.kwargs["galvanostatic_plot"] and self.kwargs["dqdv_plot"]:
self.plot_gc_and_dQdV()
if self.kwargs["capacity_determination_from_ratecap"]:
self.plot_cap_from_rc()
self._wrap_up()
def _wrap_up(self):
# saving journal file
if self.kwargs["save_journal"]:
if self.journal is not None:
if self.outpath is not None:
journal_file_path = Path(self.outpath) / self.journal_file.name
else:
journal_file_path = self.journal_file.name
# if we want to enforce that the file will be a xlsx file:
# journal_file_path = journal_file_path.with_suffix(".xlsx")
journal_file_path = journal_file_path.with_suffix(".json")
self.journal.to_file(
file_name=journal_file_path, paginate=False, to_project_folder=False
)
xlsx_journal_file_path = journal_file_path.with_name(
f"{journal_file_path.stem}.xlsx"
)
self.journal.to_file(
file_name=xlsx_journal_file_path,
paginate=False,
to_project_folder=False,
)
def verify_input(self):
"""Verifies that the users' input to the object is correct."""
# Check that output dir exist (or create one)
self.outpath = self.handle_outpath() # Takes care of the output path
# Check the nicknames
if self.nicknames:
if len(self.nicknames) != len(self.files):
logging.error(
"Use nicknames = None, or specify exactly one nickname per datafile. You have specified "
+ str(len(self.nicknames))
+ " nicknames while inputting "
+ str(len(self.files))
+ | |
\
+ 0*If(_id_72, 0, 1 ) \
+ 0*If(wish_list, 0, 1 ) \
+ 0*If(wish_list_saved_after_session, 0, 1 ) \
+ 1*If(email_wish_list, 0, 1 ) \
+ 0*If(_id_73, 0, 1 ) \
+ 0*If(permissions, 0, 1 ) \
+ 1*If(_id_75, 0, 1 ) \
+ 0*If(_id_76, 0, 1 ) \
+ 0*If(_id_77, 0, 1 ) \
+ 1*If(buy_paths, 0, 1 ) \
+ 0*If(_id_78, 0, 1 ) \
+ 0*If(_id_79, 0, 1 ) \
+ 0*If(_id_80, 0, 1 ) \
+ 1*If(_id_81, 0, 1 ) \
+ 1*If(_id_82, 0, 1 ) \
+ 1*If(_id_83, 0, 1 ) \
+ 0*If(_id_84, 0, 1 ) \
+ 1*If(registered_checkout, 0, 1 ) \
+ 1*If(quick_checkout, 0, 1 ) \
+ 0*If(_id_86, 0, 1 ) \
+ 1*If(_id_87, 0, 1 ) \
+ 1*If(shipping_options, 0, 1 ) \
+ 1*If(_id_88, 0, 1 ) \
+ 1*If(_id_89, 0, 1 ) \
+ 0*If(_id_90, 0, 1 ) \
+ 0*If(_id_91, 0, 1 ) \
+ 0*If(_id_92, 0, 1 ) \
+ 1*If(_id_93, 0, 1 ) \
+ 0*If(_id_95, 0, 1 ) \
+ 1*If(_id_96, 0, 1 ) \
+ 0*If(_id_98, 0, 1 ) \
+ 0*If(_id_99, 0, 1 ) \
+ 0*If(_id_100, 0, 1 ) \
+ 1*If(_id_101, 0, 1 ) \
+ 1*If(shipping_2, 0, 1 ) \
+ 0*If(_id_102, 0, 1 ) \
+ 0*If(_id_103, 0, 1 ) \
+ 0*If(_id_105, 0, 1 ) \
+ 0*If(_id_106, 0, 1 ) \
+ 0*If(_id_107, 0, 1 ) \
+ 1*If(_id_108, 0, 1 ) \
+ 1*If(_id_110, 0, 1 ) \
+ 0*If(_id_111, 0, 1 ) \
+ 0*If(_id_112, 0, 1 ) \
+ 0*If(_id_114, 0, 1 ) \
+ 0*If(_id_115, 0, 1 ) \
+ 1*If(_id_116, 0, 1 ) \
+ 0*If(_id_117, 0, 1 ) \
+ 0*If(_id_118, 0, 1 ) \
+ 0*If(_id_120, 0, 1 ) \
+ 0*If(_id_121, 0, 1 ) \
+ 0*If(_id_122, 0, 1 ) \
+ 0*If(_id_123, 0, 1 ) \
+ 1*If(_id_124, 0, 1 ) \
+ 0*If(_id_125, 0, 1 ) \
+ 1*If(_id_126, 0, 1 ) \
+ 0*If(_id_127, 0, 1 ) \
+ 0*If(_id_128, 0, 1 ) \
+ 1*If(_id_129, 0, 1 ) \
+ 1*If(_id_130, 0, 1 ) \
+ 1*If(_id_132, 0, 1 ) \
+ 0*If(_id_133, 0, 1 ) \
+ 1*If(_id_134, 0, 1 ) \
+ 0*If(_id_135, 0, 1 ) \
+ 0*If(_id_136, 0, 1 ) \
+ 1*If(_id_137, 0, 1 ) \
+ 0*If(_id_138, 0, 1 ) \
+ 1*If(_id_139, 0, 1 ) \
+ 1*If(_id_141, 0, 1 ) \
+ 1*If(_id_142, 0, 1 ) \
+ 0*If(_id_143, 0, 1 ) \
+ 0*If(_id_144, 0, 1 ) \
+ 0*If(buy_paths_288_289, 0, 1 ) \
+ 0*If(buy_paths_288_289_290, 0, 1 ) \
+ 1*If(buy_paths_288_289_291, 0, 1 ) \
+ 1*If(customer_service, 0, 1 ) \
+ 1*If(_id_146, 0, 1 ) \
+ 0*If(_id_147, 0, 1 ) \
+ 1*If(_id_148, 0, 1 ) \
+ 0*If(_id_149, 0, 1 ) \
+ 0*If(_id_150, 0, 1 ) \
+ 1*If(_id_152, 0, 1 ) \
+ 1*If(_id_153, 0, 1 ) \
+ 0*If(_id_154, 0, 1 ) \
+ 0*If(_id_155, 0, 1 ) \
+ 0*If(_id_156, 0, 1 ) \
+ 0*If(_id_158, 0, 1 ) \
+ 1*If(_id_159, 0, 1 ) \
+ 1*If(user_behaviour_tracking, 0, 1 ) \
+ 0*If(_id_160, 0, 1 ) \
+ 1*If(locally_visited_pages, 0, 1 ) \
+ 0*If(external_referring_pages, 0, 1 ) \
+ 1*If(behaviour_tracked_previous_purchases, 0, 1 ) \
+ 0*If(business_management, 0, 1 ) \
+ 1*If(_id_162, 0, 1 ) \
+ 1*If(_id_163, 0, 1 ) \
+ 1*If(physical_goods_fulfillment, 0, 1 ) \
+ 0*If(warehouse_management, 0, 1 ) \
+ 1*If(shipping, 0, 1 ) \
+ 0*If(_id_166, 0, 1 ) \
+ 0*If(_id_167, 0, 1 ) \
+ 0*If(_id_168, 0, 1 ) \
+ 1*If(_id_169, 0, 1 ) \
+ 0*If(_id_171, 0, 1 ) \
+ 0*If(_id_172, 0, 1 ) \
+ 1*If(_id_173, 0, 1 ) \
+ 0*If(_id_174, 0, 1 ) \
+ 1*If(_id_175, 0, 1 ) \
+ 0*If(_id_177, 0, 1 ) \
+ 0*If(_id_178, 0, 1 ) \
+ 1*If(_id_179, 0, 1 ) \
+ 1*If(_id_180, 0, 1 ) \
+ 0*If(_id_181, 0, 1 ) \
+ 0*If(eletronic_goods_fulfillment, 0, 1 ) \
+ 1*If(_id_182, 0, 1 ) \
+ 0*If(_id_183, 0, 1 ) \
+ 0*If(services_fulfillment, 0, 1 ) \
+ 0*If(_id_184, 0, 1 ) \
+ 0*If(_id_185, 0, 1 ) \
+ 1*If(_id_186, 0, 1 ) \
+ 1*If(_id_187, 0, 1 ) \
+ 1*If(customer_preferences, 0, 1 ) \
+ 1*If(_id_189, 0, 1 ) \
+ 0*If(_id_190, 0, 1 ) \
+ 0*If(targeting_criteria_previous_purchases, 0, 1 ) \
+ 1*If(_id_191, 0, 1 ) \
+ 1*If(wish_list_content, 0, 1 ) \
+ 1*If(previously_visited_pages, 0, 1 ) \
+ 0*If(_id_192, 0, 1 ) \
+ 1*If(_id_193, 0, 1 ) \
+ 0*If(_id_194, 0, 1 ) \
+ 1*If(_id_196, 0, 1 ) \
+ 1*If(_id_197, 0, 1 ) \
+ 0*If(_id_199, 0, 1 ) \
+ 1*If(_id_200, 0, 1 ) \
+ 1*If(_id_201, 0, 1 ) \
+ 1*If(_id_203, 0, 1 ) \
+ 1*If(_id_204, 0, 1 ) \
+ 1*If(_id_205, 0, 1 ) \
+ 1*If(_id_206, 0, 1 ) \
+ 1*If(_id_207, 0, 1 ) \
+ 0*If(discounts, 0, 1 ) \
+ 1*If(_id_208, 0, 1 ) \
+ 0*If(_id_209, 0, 1 ) \
+ 0*If(_id_210, 0, 1 ) \
+ 0*If(_id_211, 0, 1 ) \
+ 1*If(_id_212, 0, 1 ) \
+ 1*If(_id_214, 0, 1 ) \
+ 1*If(_id_215, 0, 1 ) \
+ 1*If(_id_216, 0, 1 ) \
+ 0*If(_id_217, 0, 1 ) \
+ 1*If(_id_218, 0, 1 ) \
+ 1*If(_id_219, 0, 1 ) \
+ 0*If(_id_220, 0, 1 ) \
+ 0*If(_id_222, 0, 1 ) \
+ 0*If(_id_223, 0, 1 ) \
+ 1*If(_id_224, 0, 1 ) \
+ 1*If(_id_225, 0, 1 ) \
+ 1*If(_id_226, 0, 1 ) \
+ 0*If(_id_228, 0, 1 ) \
+ 1*If(_id_229, 0, 1 ) \
+ 0*If(_id_230, 0, 1 ) \
+ 0*If(_id_231, 0, 1 ) \
+ 0*If(_id_232, 0, 1 ) \
+ 0*If(_id_233, 0, 1 ) \
+ 0*If(_id_235, 0, 1 ) \
+ 0*If(_id_236, 0, 1 ) \
+ 0*If(_id_237, 0, 1 ) \
+ 1*If(personalized_emails, 0, 1 ) \
+ 0*If(_id_238, 0, 1 ) \
+ 1*If(_id_239, 0, 1 ) \
+ 0*If(_id_240, 0, 1 ) \
+ 1*If(_id_241, 0, 1 ) \
+ 0*If(_id_242, 0, 1 ) \
+ 1*If(inventory_tracking, 0, 1 ) \
+ 1*If(_id_243, 0, 1 ) \
+ 1*If(procurement, 0, 1 ) \
+ 1*If(_id_244, 0, 1 ) \
+ 0*If(_id_245, 0, 1 ) \
+ 1*If(automatic, 0, 1 ) \
+ 1*If(_id_246, 0, 1 ) \
+ 1*If(reporting_and_analysis, 0, 1 ) \
+ 0*If(_id_247, 0, 1 ) \
+ 0*If(_id_248, 0, 1 ) \
+ 1*If(_id_249, 0, 1 ) \
+ 0*If(_id_250, 0, 1 ) \
+ 1*If(fulfillment_system, 0, 1 ) \
+ 0*If(_id_252, 0, 1 ) \
+ 1*If(procurement_system, 0, 1 ) \
+ 1*If(_id_253, 0, 1 ) \
+ 0*If(_id_254, 0, 1 ) \
+ 0*If(_id_255, 0, 1 ) \
+ 0*If(_id_256, 0, 1 ) \
+ 1*If(_id_257, 0, 1 ) \
+ 1*If(_id_258, 0, 1 ) \
+ 1*If(_id_259, 0, 1 ) \
+ 1*If(_id_260, 0, 1 ) \
+ 0*If(_id_261, 0, 1 ) \
+ 0*If(_id_262, 0, 1 ) \
+ 0*If(_id_263, 0, 1 ) \
)
s.add(total_FeatureCount== 1*If(eShop, 0, 1 ) \
+ 1*If(store_front, 0, 1 ) \
+ 1*If(homepage, 0, 1 ) \
+ 1*If(_id_1, 0, 1 ) \
+ 1*If(_id_2, 0, 1 ) \
+ 1*If(_id_3, 0, 1 ) \
+ 1*If(_id_5, 0, 1 ) \
+ 1*If(special_offers, 0, 1 ) \
+ 1*If(_id_6, 0, 1 ) \
+ 1*If(_id_8, 0, 1 ) \
+ 1*If(_id_9, 0, 1 ) \
+ 1*If(registration, 0, 1 ) \
+ 1*If(registration_enforcement, 0, 1 ) \
+ 1*If(_id_11, 0, 1 ) \
+ 1*If(register_to_buy, 0, 1 ) \
+ 1*If(_id_12, 0, 1 ) \
+ 1*If(_id_13, 0, 1 ) \
+ 1*If(_id_14, 0, 1 ) \
+ 1*If(shipping_address, 0, 1 ) \
+ 1*If(_id_15, 0, 1 ) \
+ 1*If(_id_16, 0, 1 ) \
+ 1*If(_id_17, 0, 1 ) \
+ 1*If(_id_18, 0, 1 ) \
+ 1*If(_id_19, 0, 1 ) \
+ 1*If(_id_20, 0, 1 ) \
+ 1*If(_id_21, 0, 1 ) \
+ 1*If(_id_22, 0, 1 ) \
+ 1*If(_id_23, 0, 1 ) \
+ 1*If(_id_25, 0, 1 ) \
+ 1*If(_id_26, 0, 1 ) \
+ 1*If(_id_27, 0, 1 ) \
+ 1*If(_id_28, 0, 1 ) \
+ 1*If(_id_29, 0, 1 ) \
+ 1*If(preferences, 0, 1 ) \
+ 1*If(_id_31, 0, 1 ) \
+ 1*If(_id_32, 0, 1 ) \
+ 1*If(_id_33, 0, 1 ) \
+ 1*If(_id_34, 0, 1 ) \
+ 1*If(quick_checkout_profile, 0, 1 ) \
+ 1*If(_id_35, 0, 1 ) \
+ 1*If(user_behaviour_tracking_info, 0, 1 ) \
+ 1*If(catalog, 0, 1 ) \
+ 1*If(product_information, 0, 1 ) \
+ 1*If(product_type, 0, 1 ) \
+ 1*If(eletronic_goods, 0, 1 ) \
+ 1*If(physical_goods, 0, 1 ) \
+ 1*If(services, 0, 1 ) \
+ 1*If(basic_information, 0, 1 ) \
+ 1*If(detailed_information, 0, 1 ) \
+ 1*If(warranty_information, 0, 1 ) \
+ 1*If(customer_reviews, 0, 1 ) \
+ 1*If(associated_assets, 0, 1 ) \
+ 1*If(_id_38, 0, 1 ) \
+ 1*If(_id_39, 0, 1 ) \
+ 1*If(_id_41, 0, 1 ) \
+ 1*If(_id_43, 0, 1 ) | |
\n \n'REGISTER FD05RYT Joe Bloggs'"
bb_sms_handler.send_sms_notification(SMSTo, SMSFrom, message)
return "<Response></Response>"
def notEnoughDeRegistrationDetails(SMSTo, SMSFrom):
logger.debug("Returning: Not Enough Details Provided")
message = "You have not provided enough details. Please use format: \n \n'UNREGISTER FD05RYT'"
bb_sms_handler.send_sms_notification(SMSTo, SMSFrom, message)
return "<Response></Response>"
def notEnoughBlockDetails(SMSTo, SMSFrom):
logger.debug("Returning: Not Enough Details Provided")
message = "You have not provided enough details. Please use format: \n \n'BLOCK FD05RYT' \n \nwith the registration as a single word."
bb_sms_handler.send_sms_notification(SMSTo, SMSFrom, message)
return "<Response></Response>"
def send_not_registered_SMS(SMSTo, SMSFrom):
logger.debug("Returning: Please Register To Use This Service")
message = "Please register to use BlockBuster. \n \nSimply text 'REGISTER YourNumberPlate Firstname Surname'."
bb_sms_handler.send_sms_notification(SMSTo, SMSFrom, message)
return None
# Method is run when a PUSH command is received from a user
def push(SMSTo, SMSFrom, SMSList):
bb_dbconnector_factory.DBConnectorInterfaceFactory().create().add_analytics_record("Count", "Command-PUSH", instancename)
if len(SMSList) > 1:
if SMSList[1].upper() == "OFF":
logger.debug("User requested that push notifications are disabled")
message = bb_dbconnector_factory.DBConnectorInterfaceFactory().create().turn_push_notifications_off(SMSFrom)
bb_sms_handler.send_sms_notification(SMSTo, SMSFrom, message)
return
elif SMSList[1].upper() == "ON":
logger.debug("User requested that push notifications are enabled")
message = bb_dbconnector_factory.DBConnectorInterfaceFactory().create().turn_push_notifications_on(SMSFrom)
bb_sms_handler.send_sms_notification(SMSTo, SMSFrom, message)
return
else:
pushover_token = SMSList[1]
logger.debug("Using Pushover token " + pushover_token)
logger.debug("Setting Pushover token for user")
message = bb_dbconnector_factory.DBConnectorInterfaceFactory().create().add_pushover_token_for_user(SMSFrom, pushover_token)
bb_sms_handler.send_sms_notification(SMSTo, SMSFrom, message)
else:
return
def send_push_notification_if_appropriate(service_number, mobile, title, message):
pushover_token = bb_dbconnector_factory.DBConnectorInterfaceFactory().create().get_pushover_user_token_from_mobile(mobile)
if pushover_token != "":
send_push_notification(pushover_token, message, title, service_number)
def whois(SMSTo, SMSFrom, SMSList):
bb_dbconnector_factory.DBConnectorInterfaceFactory().create().add_analytics_record("Count", "Command-WHOIS", instancename)
if len(SMSList) > 1:
upper_case_reg = SMSList[1].upper()
logger.debug("Using Registration Plate: " + upper_case_reg)
response = cardetails(upper_case_reg)
else:
response = respond_noregistrationspecified(SMSTo, SMSFrom)
bb_sms_handler.send_sms_notification(SMSTo, SMSFrom, response)
def register(SMSTo, SMSFrom, SMSList, location):
bb_dbconnector_factory.DBConnectorInterfaceFactory().create().add_analytics_record("Count", "Command-REGISTER", instancename)
if len(SMSList) < 4:
return notEnoughRegistrationDetails(SMSTo, SMSFrom)
registration = SMSList[1].upper()
firstname = SMSList[2]
surname = SMSList[3]
mobile = SMSFrom
location = location
message = bb_dbconnector_factory.DBConnectorInterfaceFactory()\
.create()\
.register_new_car(registration,
firstname,
surname,
mobile,
location)
bb_sms_handler.send_sms_notification(SMSTo, SMSFrom, message)
return
def move(service_number, requester_number, SMSList):
bb_dbconnector_factory.DBConnectorInterfaceFactory().create().add_analytics_record("Count", "Command-MOVE", instancename)
def get_landline_number_string(reg):
try:
alt_contact_text = bb_dbconnector_factory.DBConnectorInterfaceFactory().create().get_landline_from_reg(reg)
if alt_contact_text != "":
return str(alt_contact_text) + "\n"
else:
return ""
except Exception as e:
bb_auditlogger.BBAuditLoggerFactory().create().logException(e)
return ""
# Method to send SMS messages to both blocker and blockee where the MOVE command is for a specific car
def request_single_car_move(reg):
# Search the database for the registration plate provided
if checkifregexists(reg):
# Try and retrieve details from the database for both the blockEE and blockER
try:
dict_blocker = bb_dbconnector_factory.DBConnectorInterfaceFactory().create()\
.get_user_dict_from_reg(blocking_reg)
print(dict_blocker)
dict_blockee = bb_dbconnector_factory.DBConnectorInterfaceFactory().create()\
.get_user_dict_from_mobile(requester_number)
print(dict_blockee)
except Exception as e:
bb_auditlogger.BBAuditLoggerFactory().create().logException(e)
pass
# If the blocker has a Mobile number (and therefore is registered with BlockBuster) then do this
if dict_blocker['Mobile'] != "" and dict_blocker['Mobile'] != None:
# If the blockee is registered with BlockBuster then do this
if dict_blockee:
message = dict_blockee['FirstName'] + " " + dict_blockee['Surname'] + \
" needs you to move your car, please.\n\n" \
"Text 'OK' to confirm that you have received this."
subject = "Please move your car"
bb_sms_handler.send_sms_notification(service_number, dict_blocker['Mobile'], message)
# Send a push notification if that user wants them
send_push_notification_if_appropriate(service_number, dict_blocker['Mobile'], subject, message)
# Ask the notification handler to send out the appropriate notifications
bb_notification_handler.send_notifications(dict_blocker['Mobile'], subject, message)
# Open a move request for that blocker / blockee combination
add_move_request(dict_blocker['Mobile'], requester_number)
landline_string = get_landline_number_string(blocking_reg)
logger.debug(landline_string)
blocker_name = dict_blocker['FirstName'] + " " + dict_blocker['Surname']
blocker_mobile = dict_blocker['Mobile']
blocker_reg = reg
list_of_names = blocker_name + " (" + \
blocker_reg + ")\n" + \
include_mobile_number(blocker_mobile) + \
get_landline_number_string(blocker_reg) + "\n"
send_move_blockee_message(service_number,requester_number, list_of_names)
# The blockee is not registered with BlockBuster
# so advise them to register with the service before trying to use it
else:
bb_sms_handler.send_sms_notification(service_number, requester_number, "Sorry - please register this mobile number to use "
"this BlockBuster service. \n \n Text '?' for help.")
# The blockER is not registered with BlockBuster
# so provide them the name of the car owner
else:
bb_sms_handler.send_sms_notification(service_number, requester_number, "Sorry - this car belongs to " + dict_blocker['FirstName'] + " "
+ dict_blocker['Surname'] + " but they do not have a mobile "
"number registered.")
else:
# If the MOVE command was sent on its own (therefore searching for existing blocks)
if len(SMSList) < 2:
bb_sms_handler.send_sms_notification(service_number, requester_number, "Sorry - cannot find any current blocks for you.")
# In which case it must have been sent with a registration plate as a parameter
else:
bb_sms_handler.send_sms_notification(service_number, requester_number, "Sorry - vehicle not registered with BlockBuster.")
return "<Response></Response>"
# Method to send MOVE response to blockee where there is a list of blockers who have been informed.
def send_move_blockee_message(service_number2, requester_number2, names_list):
messageblocker = "I've asked these people to move: \n\n" + names_list
bb_sms_handler.send_sms_notification(service_number2, requester_number2, messageblocker)
def include_mobile_number(mobile):
share_mobile = bb_dbconnector_factory.DBConnectorInterfaceFactory().create().mobile_sharing_enabled(mobile)
if share_mobile:
return mobile + "\n"
elif not share_mobile:
return ""
def add_move_request(blocker_mobile, blockee_mobile):
move_request = {
"BlockerMobile": blocker_mobile,
"BlockeeMobile": blockee_mobile
}
bb_dbconnector_factory.DBConnectorInterfaceFactory().create().add_move_request(move_request)
# IF check to see whether the MOVE command was sent on its own or with a registration plate. If so, do the below.
sentWithoutRegistration = (len(SMSList) < 2)
if sentWithoutRegistration:
# Get a count of the active blocks for the person requesting the 'MOVE'
count_of_blocks = bb_dbconnector_factory.DBConnectorInterfaceFactory().create().get_count_of_blocks_for_blockee(requester_number)
logger.debug('Count of blocks: ' + str(count_of_blocks))
# Where the number of blocks is less than 1 (i.e. 0 as it shouldn't ever be a negative number) send a message
# informing the blockee that there are no active blocks registered for them.
if count_of_blocks < 1:
bb_sms_handler.send_sms_notification(service_number, requester_number, "Sorry - cannot find any current blocks for you. \n\n"
"Use 'MOVE registration' for a specific car.")
return "<Response></Response>"
# Get a list of active blocks for the person requesting the 'MOVE' as a cursor
list_of_blocks = bb_dbconnector_factory.DBConnectorInterfaceFactory().create().get_list_of_blocks_for_blockee(requester_number)
# Declare this outside the for loop so that it can be accessed once the for loop is complete
list_of_names = ""
# Iterate through the cursor, sending an SMS to each blocker asking them to move.
for block_item in list_of_blocks:
a = service_number
b = requester_number
blocker_mobile = block_item['blocker_mobile']
d = block_item['blocked_reg']
blockee_name = bb_dbconnector_factory.DBConnectorInterfaceFactory().create().get_name_from_mobile(b)
blocker_name = bb_dbconnector_factory.DBConnectorInterfaceFactory().create().get_name_from_mobile(blocker_mobile)
blocker_reg = bb_dbconnector_factory.DBConnectorInterfaceFactory().create().get_reg_from_mobile(blocker_mobile)
# Compile the message to send to the blocker.
message = blockee_name + " (" + d + ") needs you to move your car, please.\n\n" \
"Text 'OK' to confirm that you have received this."
# Send the SMS to the blocker.
bb_sms_handler.send_sms_notification(a, blocker_mobile, message)
# Send a push notification if the user wants it
subject = "Move Request"
send_push_notification_if_appropriate(service_number, blocker_mobile, subject, message)
# Ask the notification handler to send out the appropriate notifications
bb_notification_handler.send_notifications(blocker_mobile, subject, message)
# Open a move request for that blocker
add_move_request(blocker_mobile, b)
# Add the name, reg, and mobile number of the blocker to the list
# so that they can be provided back to the blockee.
list_of_names = list_of_names + \
blocker_name + " (" + \
blocker_reg + ")\n" + \
include_mobile_number(blocker_mobile) + \
get_landline_number_string(blocker_reg) + "\n"
# Now send a single message to the blockee containing a list of all people who were being blocked.
send_move_blockee_message(service_number, requester_number, list_of_names)
return "<Response></Response>"
# A value was provided after the MOVE command therefore treat it as if a registration plate was provided.
else:
blocking_reg = SMSList[1].upper()
return request_single_car_move(blocking_reg)
def acknowledge_move_request(SMSTo, SMSFrom, SMSList):
bb_dbconnector_factory.DBConnectorInterfaceFactory().create().add_analytics_record("Count", "Command-ACKNOWLEDGE", instancename)
open_move_requests = bb_dbconnector_factory.DBConnectorInterfaceFactory().create().get_open_move_requests(SMSFrom)
blocker_name = bb_dbconnector_factory.DBConnectorInterfaceFactory().create().get_name_from_mobile(SMSFrom)
if len(open_move_requests) < 1:
bb_sms_handler.send_sms_notification(SMSTo, SMSFrom, "BlockBuster doesn't know of anyone waiting for you to move at this time.")
return
for move_request in open_move_requests:
message = blocker_name + " has acknowledged your move request."
bb_sms_handler.send_sms_notification(SMSTo, move_request['blockee_mobile'], message)
bb_dbconnector_factory.DBConnectorInterfaceFactory().create().remove_move_request(SMSFrom, move_request['blockee_mobile'])
return
def block(SMSTo, SMSFrom, SMSList):
bb_dbconnector_factory.DBConnectorInterfaceFactory().create().add_analytics_record("Count", "Command-BLOCK", instancename)
# Loop through the registrations provided and add them all to an array
reg_list = []
total_elements = len(SMSList)
# Start at element[1} as we have already established that element[0] contains the command by the face we're here.
e = 1
while e < total_elements:
# Skip elements which have come from multiple spaces between registrations in the message.
if SMSList[e] == "":
pass
else:
reg_list.append(SMSList[e])
e += 1
logger.debug("Number of registrations in list is " + str(len(reg_list)))
# Check that a registration was actually provided. If not, respond to the user.
if len(reg_list) < 1:
return respond_noregistrationspecified(SMSTo, SMSFrom)
# Now work through each of the registrations in the list, working | |
<filename>4-dccphase_2/src/3_statistical_simulation.py
#-- -- -- -- Statistical Simulation in Python:
# Used for Data Scientist Training Path
#FYI it's a compilation of how to work
#with different commands.
### --------------------------------------------------------
# # ------>>>>> np.random.choice()
# In this exercise, you will be introduced to the np.random.choice() function.
# This is a remarkably useful function for simulations and you will be making
# extensive use of it later in the course. As a first step, let's try to
# understand the basics of this function. Using help(), figure out which of the
# following input parameters are not optional for the np.random.choice() function:
# There are four parameters for the NumPy random choice function:
# a
# size
# replace
# p
help(np.random.choice)
# R/ a - input array
### --------------------------------------------------------
# # ------>>>>> Poisson random variable
# Initialize seed and parameters
np.random.seed(123)
lam, size_1, size_2 = 5, 3, 1000
# Draw samples & calculate absolute difference between lambda and sample mean
samples_1 = np.random.poisson(lam, size_1)
samples_2 = np.random.poisson(lam, size_2)
answer_1 = abs(np.mean(samples_1) - lam)
answer_2 = abs(np.mean(samples_2) - lam)
print("|Lambda - sample mean| with {} samples is {} and with {} samples is {}. ".format(size_1, answer_1, size_2, answer_2))
### --------------------------------------------------------
# # ------>>>>> Shuffling a deck of cards
print(deck_of_cards)
# Shuffle the deck
np.random.shuffle(deck_of_cards)
# Print out the top three cards
card_choices_after_shuffle = deck_of_cards[:3]
print(card_choices_after_shuffle)
### --------------------------------------------------------
# # ------>>>>> Throwing a fair die
# The seed for this exercise is set to 123
# Define die outcomes and probabilities
die, probabilities, throws = [1,2,3,4,5,6], [1/6]*6, 1
# Use np.random.choice to throw the die once and record the outcome
outcome = np.random.choice(die, size=1, p=probabilities)
print("Outcome of the throw: {}".format(outcome[0]))
### --------------------------------------------------------
# # ------>>>>> Throwing two fair dice
# The seed for this exercise is set to 223
# Initialize number of dice, simulate & record outcome
die, probabilities, num_dice = [1,2,3,4,5,6], [1/6, 1/6, 1/6, 1/6, 1/6, 1/6], 2
outcomes = np.random.choice(die, size=num_dice, p=probabilities)
# Win if the two dice show the same number
if outcomes[0] == outcomes[1]:
answer = 'win'
else:
answer = 'lose'
print("The dice show {} and {}. You {}!".format(outcomes[0], outcomes[1], answer))
### --------------------------------------------------------
# # ------>>>>> Simulating the dice game
# The seed for this exercise is set to 223
# Initialize model parameters & simulate dice throw
die, probabilities, num_dice = [1,2,3,4,5,6], [1/6, 1/6, 1/6, 1/6, 1/6, 1/6], 2
sims, wins = 100, 0
for i in range(sims):
outcomes = np.random.choice(die, size=num_dice, p=probabilities)
# Increment `wins` by 1 if the dice show same number
if outcomes[0] == outcomes[1]:
wins = wins + 1
print("In {} games, you win {} times".format(sims, wins))
### --------------------------------------------------------
# # ------>>>>> Simulating one lottery drawing
# The seed for this exercise is set to 123
# Pre-defined constant variables
lottery_ticket_cost, num_tickets, grand_prize = 10, 1000, 1000000
# Probability of winning
chance_of_winning = 1/num_tickets
# Simulate a single drawing of the lottery
gains = [-lottery_ticket_cost, grand_prize-lottery_ticket_cost]
probability = [1-chance_of_winning, chance_of_winning]
outcome = np.random.choice(a=gains, size=1, p=probability, replace=True)
print("Outcome of one drawing of the lottery is {}".format(outcome))
### --------------------------------------------------------
# # ------>>>>> Should we buy?
# Initialize size and simulate outcome
lottery_ticket_cost, num_tickets, grand_prize = 10, 1000, 10000
chance_of_winning = 1/num_tickets
size = 2000
payoffs = [-lottery_ticket_cost, grand_prize-lottery_ticket_cost]
probs = [1-chance_of_winning, chance_of_winning]
outcomes = np.random.choice(a=payoffs, size=size, p=probs, replace=True)
# Mean of outcomes.
answer = outcomes.mean()
print("Average payoff from {} simulations = {}".format(size, answer))
### --------------------------------------------------------
# # ------>>>>> Calculating a break-even lottery price
# The seed for this exercise is set to 333
# Initialize simulations and cost of ticket
sims, lottery_ticket_cost = 3000, 0
# Use a while loop to increment `lottery_ticket_cost` till average value of outcomes falls below zero
while 1:
outcomes = np.random.choice([-lottery_ticket_cost, grand_prize-lottery_ticket_cost],
size=sims, p=[1-chance_of_winning, chance_of_winning], replace=True)
if outcomes.mean() < 0:
break
else:
lottery_ticket_cost += 1
answer = lottery_ticket_cost - 1
print("The highest price at which it makes sense to buy the ticket is {}".format(answer))
### --------------------------------------------------------
# # ------>>>>> Queen and spade
# Here event A is the card being a queen and event
# B is the card being a spade. Think carefully about whether
# the two events have anything in common.
# P(Queen) + P(Spade) - P(Queen of Spades)
# 4/52 + 13/52 - 1/52
# = 16/52
### --------------------------------------------------------
# # ------>>>>> Two of a kind
# The seed for this exercise is set to 123
# Shuffle deck & count card occurrences in the hand
n_sims, two_kind = 10000, 0
for i in range(n_sims):
np.random.shuffle(deck_of_cards)
hand, cards_in_hand = deck_of_cards[0:5], {}
for card in hand:
# Use .get() method on cards_in_hand
cards_in_hand[card[1]] = cards_in_hand.get(card[1], 0) + 1
# Condition for getting at least 2 of a kind
highest_card = max(cards_in_hand.values())
if highest_card>=2:
two_kind += 1
print("Probability of seeing at least two of a kind = {} ".format(two_kind/n_sims))
### --------------------------------------------------------
# # ------>>>>> Game of thirteen
# Pre-set constant variables
deck, sims, coincidences = np.arange(1, 14), 10000, 0
for _ in range(sims):
# Draw all the cards without replacement to simulate one game
draw = np.random.choice(deck, size=len(deck), replace=False)
# Check if there are any coincidences
coincidence = (draw == list(np.arange(1, 14))).any()
if coincidence == True:
coincidences += 1
# Calculate probability of winning
prob_of_winning = 1 - coincidences / sims
print("Probability of winning = {}".format(prob_of_winning))
### --------------------------------------------------------
# # ------>>>>> The conditional urn
# Initialize success, sims and urn
success, sims = 0, 5000
urn = ['w'] * 7 + ['b'] * 6
for _ in range(sims):
# Draw 4 balls without replacement
draw = np.random.choice(urn, replace=False, size=4)
# Count the number of successes
if (draw == ['w','b','w','b']).all():
success +=1
print("Probability of success = {}".format(success/sims))
### --------------------------------------------------------
# # ------>>>>> Birthday problem - part #0
# Draw a sample of birthdays & check if each birthday is unique
days = np.arange(1,366)
people = 2
def birthday_sim(people):
sims, unique_birthdays = 2000, 0
for _ in range(sims):
draw = np.random.choice(days, size=people, replace=True)
if len(draw) == len(set(draw)):
unique_birthdays += 1
out = 1 - unique_birthdays / sims
return out
### --------------------------------------------------------
# # ------>>>>> Birthday problem - part #1
# Break out of the loop if probability greater than 0.5
while (people > 0):
prop_bds = birthday_sim(people)
if prop_bds > 0.5:
break
people += 1
print("With {} people, there's a 50% chance that two share a birthday.".format(people))
### --------------------------------------------------------
# # ------>>>>> Full house
#Shuffle deck & count card occurrences in the hand
n_sims, full_house, deck_of_cards = 50000, 0, deck.copy()
for i in range(n_sims):
np.random.shuffle(deck_of_cards)
hand, cards_in_hand = deck_of_cards[0:5], {}
for card in hand:
# Use .get() method to count occurrences of each card
cards_in_hand[card[1]] = cards_in_hand.get(card[1], 0) + 1
# Condition for getting full house
condition = (max(cards_in_hand.values()) ==3) & (min(cards_in_hand.values())==2)
if condition == True:
full_house += 1
print("Probability of seeing a full house = {}".format(full_house/n_sims))
### --------------------------------------------------------
# # ------>>>>> Driving test - part #0
sims, outcomes, p_rain, p_pass = 1000, [], 0.40, {'sun':0.9, 'rain':0.3}
def test_outcome(p_rain):
# Simulate whether it will rain or not
weather = np.random.choice(['sun', 'rain'], p=[1-p_rain, p_rain])
# Simulate and return whether you will pass or fail
return np.random.choice(['pass', 'fail'], p=[p_pass[weather], 1-p_pass[weather]])
### --------------------------------------------------------
# # ------>>>>> Driving test - part #1
for _ in range(sims):
outcomes.append(test_outcome(p_rain))
# Calculate fraction of outcomes where you pass
pass_outcomes_frac = outcomes.count('pass') / len(outcomes)
print("Probability of Passing the driving test = {}".format(pass_outcomes_frac))
### --------------------------------------------------------
# # ------>>>>> National elections
outcomes, sims, probs = [], 1000, p
for _ in range(sims):
# Simulate elections in the 50 states
election = np.random.binomial(p=probs, n=1)
# Get average of Red wins and add to `outcomes`
outcomes.append(np.sum(election)/len(election))
# Calculate probability of Red winning in less than 45% of the states
prob_red_wins = sum(x<0.45 for x in outcomes)/ len(outcomes)
print("Probability of Red winning in less than 45% of the states = {}".format(prob_red_wins))
### --------------------------------------------------------
# # ------>>>>> Fitness goals
# Simulate steps & choose prob
for _ in range(sims):
w = []
for i in range(days):
lam = np.random.choice([5000, 15000], p=[0.6, 0.4], size=1)
steps = np.random.poisson(lam)
if steps > 10000:
prob = [0.2, 0.8]
elif steps < 8000:
prob = [0.8, 0.2]
else:
prob = [0.5, 0.5]
w.append(np.random.choice([1, -1], p=prob))
outcomes.append(sum(w))
# Calculate fraction of outcomes where there was a weight loss
weight_loss_outcomes_frac = sum(x<0 for x in outcomes)/ len(outcomes)
print("Probability of Weight Loss = {}".format(weight_loss_outcomes_frac))
### --------------------------------------------------------
# # ------>>>>> Sign up Flow
# Initialize click-through rate and signup rate dictionaries
ct_rate = {'low':0.01, 'high':np.random.uniform(low=0.01, high=1.2*0.01)}
su_rate = {'low':0.2, 'high':np.random.uniform(low=0.2, high=1.2*0.2)}
def get_signups(cost, ct_rate, | |
from collections import defaultdict
import numpy as np
import rlf.rl.utils as rutils
import torch
from rlf.storage.base_storage import BaseStorage
from torch.utils.data.sampler import BatchSampler, SubsetRandomSampler
def get_shape_for_ac(action_space):
if action_space.__class__.__name__ == "Discrete":
action_shape = 1
elif action_space.__class__.__name__ == "Dict":
# Another example of being hardcoded to logic game.
# 1 for the discrete action space index selection
action_shape = 1 + action_space.spaces["pos"].shape[0]
else:
action_shape = action_space.shape[0]
return action_shape
def _flatten_helper(T, N, _tensor):
return _tensor.view(T * N, *_tensor.size()[2:])
def to_double(inp):
return inp.double() if (inp is not None and inp.dtype == torch.float32) else inp
class RolloutStorage(BaseStorage):
def __init__(
self,
num_steps,
num_processes,
obs_space,
action_space,
args,
value_dim=1,
hidden_states={},
):
"""
- hidden_states: dict(key_name: str -> hidden_state_dim: int)
"""
super().__init__()
self.value_dim = value_dim
self.args = args
self.ob_keys = rutils.get_ob_shapes(obs_space)
self.obs = {}
for k, space in self.ob_keys.items():
ob = torch.zeros(num_steps + 1, num_processes, *space)
if k is None:
self.obs = ob
else:
self.obs[k] = ob
# Data from the info dictionary that will be saved.
self.add_data = {}
self.rewards = torch.zeros(num_steps, num_processes, 1)
self.value_preds = torch.zeros(num_steps + 1, num_processes, self.value_dim)
self.returns = torch.zeros(num_steps + 1, num_processes, self.value_dim)
self.action_log_probs = torch.zeros(num_steps, num_processes, self.value_dim)
self.hidden_states = {}
for k, dim in hidden_states.items():
self.hidden_states[k] = torch.zeros(num_steps + 1, num_processes, dim)
action_shape = get_shape_for_ac(action_space)
self.actions = torch.zeros(num_steps, num_processes, action_shape)
if action_space.__class__.__name__ == "Discrete":
self.actions = self.actions.long()
self.masks = torch.zeros(num_steps + 1, num_processes, 1)
# Masks that indicate whether it's a true terminal state
# or time limit end state
self.bad_masks = torch.ones(num_steps + 1, num_processes, 1)
self.num_steps = num_steps
self.n_procs = num_processes
self.step = 0
def get_def_obs_seq(self):
if isinstance(self.obs, dict):
return rutils.get_def_obs(self.obs)
else:
return self.obs
def add_info_key(self, key_name, data_size):
super().add_info_key(key_name, data_size)
self.add_data[key_name] = torch.zeros(self.num_steps, self.n_procs, *data_size)
def init_storage(self, obs):
super().init_storage(obs)
for k in self.ob_keys:
if k is None:
self.obs[0].copy_(obs)
else:
self.obs[k][0].copy_(obs[k])
def get_add_info(self, key):
return self.add_data[key]
def to(self, device):
for k in self.ob_keys:
if k is None:
self.obs = self.obs.to(device)
else:
self.obs[k] = self.obs[k].to(device)
self.rewards = self.rewards.to(device)
self.value_preds = self.value_preds.to(device)
self.returns = self.returns.to(device)
self.action_log_probs = self.action_log_probs.to(device)
self.actions = self.actions.to(device)
self.masks = self.masks.to(device)
self.bad_masks = self.bad_masks.to(device)
for k, d in self.add_data.items():
self.add_data[k] = d.to(device)
for k, d in self.hidden_states.items():
self.hidden_states[k] = d.to(device)
def insert(self, obs, next_obs, rewards, done, info, ac_info):
super().insert(obs, next_obs, rewards, done, info, ac_info)
masks, bad_masks = self.compute_masks(done, info)
for k in self.ob_keys:
if k is None:
self.obs[self.step + 1].copy_(next_obs)
else:
self.obs[k][self.step + 1].copy_(next_obs[k])
for i, inf in enumerate(info):
for k in self.get_extract_info_keys():
if k in inf:
if not isinstance(inf[k], torch.Tensor):
assign_val = torch.tensor(inf[k]).to(self.args.device)
else:
assign_val = inf[k]
self.add_data[k][self.step, i] = assign_val
self.actions[self.step].copy_(ac_info.action)
self.action_log_probs[self.step].copy_(ac_info.action_log_probs)
self.value_preds[self.step].copy_(ac_info.value)
self.rewards[self.step].copy_(rewards)
self.masks[self.step + 1].copy_(masks)
self.bad_masks[self.step + 1].copy_(bad_masks)
for k in self.hidden_states:
self.hidden_states[k][self.step + 1].copy_(ac_info.hxs[k])
self.step = (self.step + 1) % self.num_steps
def after_update(self):
for k in self.ob_keys:
if k is None:
self.obs[0].copy_(self.obs[-1])
else:
self.obs[k][0].copy_(self.obs[k][-1])
self.masks[0].copy_(self.masks[-1])
self.bad_masks[0].copy_(self.bad_masks[-1])
for k in self.add_data:
self.add_data[k][0].copy_(self.add_data[k][-1])
for k in self.hidden_states:
self.hidden_states[k][0].copy_(self.hidden_states[k][-1])
def compute_returns(self, next_value):
exp_rewards = self.rewards.repeat(1, 1, self.value_dim)
gamma = self.args.gamma
if self.args.use_proper_time_limits:
# Use the "bad_masks" to properly account for early terminations.
# This is the case in mujoco OpenAI gym tasks.
if self.args.use_gae:
self.value_preds[-1] = next_value
gae = 0
for step in reversed(range(self.rewards.size(0))):
delta = (
exp_rewards[step]
+ gamma * self.value_preds[step + 1] * self.masks[step + 1]
- self.value_preds[step]
)
gae = (
delta
+ gamma * self.args.gae_lambda * self.masks[step + 1] * gae
)
gae = gae * self.bad_masks[step + 1]
self.returns[step] = gae + self.value_preds[step]
else:
self.returns[-1] = next_value
for step in reversed(range(self.rewards.size(0))):
# ((R_{t+1} * \gamma * M_{t+1}) + (R_t * B_{t+1}) +
# (1 - B_{t+1}) * V_t
self.returns[step] = (
self.returns[step + 1] * gamma * self.masks[step + 1]
+ exp_rewards[step]
) * self.bad_masks[step + 1] + (
1 - self.bad_masks[step + 1]
) * self.value_preds[
step
]
else:
if self.args.use_gae:
self.value_preds[-1] = next_value
gae = 0
for step in reversed(range(self.rewards.size(0))):
delta = (
exp_rewards[step]
+ gamma * self.value_preds[step + 1] * self.masks[step + 1]
- self.value_preds[step]
)
gae = (
delta
+ gamma * self.args.gae_lambda * self.masks[step + 1] * gae
)
self.returns[step] = gae + self.value_preds[step]
else:
self.returns[-1] = next_value
for step in reversed(range(self.rewards.size(0))):
self.returns[step] = (
self.returns[step + 1] * gamma * self.masks[step + 1]
+ exp_rewards[step]
)
def compute_advantages(self):
advantages = self.returns[:-1] - self.value_preds[:-1]
# Normalize the advantages
advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-5)
return advantages
# return advantages.reshape(-1, self.value_dim)
def get_generator(
self, advantages=None, num_mini_batch=None, mini_batch_size=None, **kwargs
):
if self.args.recurrent_policy:
data_generator = self.recurrent_generator(advantages, num_mini_batch)
else:
data_generator = self.feed_forward_generator(
advantages, num_mini_batch, mini_batch_size
)
return data_generator
def get_rollout_data(self, advantages=None):
gen = self.get_generator(advantages, num_mini_batch=1)
return next(gen)
def feed_forward_generator(
self, advantages, num_mini_batch=None, mini_batch_size=None
):
num_steps, num_processes = self.rewards.size()[0:2]
batch_size = num_processes * num_steps
if mini_batch_size is None:
assert batch_size >= num_mini_batch, (
"PPO requires the number of processes ({}) "
"* number of steps ({}) = {} "
"to be greater than or equal to the number of PPO mini batches ({})."
"".format(
num_processes, num_steps, num_processes * num_steps, num_mini_batch
)
)
mini_batch_size = batch_size // num_mini_batch
sampler = BatchSampler(
SubsetRandomSampler(range(batch_size)), mini_batch_size, drop_last=True
)
for indices in sampler:
obs_batch = None
other_obs_batch = {}
for k, ob_shape in self.ob_keys.items():
if k is None:
obs_batch = self.obs[:-1].view(-1, *ob_shape)[indices]
elif k == self.args.policy_ob_key:
obs_batch = self.obs[k][:-1].view(-1, *ob_shape)[indices]
else:
other_obs_batch[k] = self.obs[k][:-1].view(-1, *ob_shape)[indices]
assert obs_batch is not None, f"Found not find {self.args.policy_ob_key}"
actions_batch = self.actions.view(-1, self.actions.size(-1))[indices]
rewards_batch = self.rewards.view(-1, 1)[indices]
hidden_states_batch = {}
for k in self.hidden_states:
hidden_states_batch[k] = self.hidden_states[k][:-1].view(
-1, self.hidden_states[k].size(-1)
)[indices]
value_preds_batch = self.value_preds[:-1].view(-1, self.value_dim)[indices]
return_batch = self.returns[:-1].view(-1, self.value_dim)[indices]
masks_batch = self.masks[:-1].view(-1, 1)[indices]
old_action_log_probs_batch = self.action_log_probs.view(-1, self.value_dim)[
indices
]
if advantages is None:
adv_targ = None
else:
adv_targ = advantages.view(-1, self.value_dim)[indices]
yield {
"state": obs_batch,
"other_state": other_obs_batch,
"reward": rewards_batch,
"hxs": hidden_states_batch,
"action": actions_batch,
"value": value_preds_batch,
"return": return_batch,
"mask": masks_batch,
"prev_log_prob": old_action_log_probs_batch,
"adv": adv_targ,
}
def get_np_tensors(self):
"""
Helper method to get the "simple" data in the buffer as numpy arrays. The
data ordering is preserved.
"""
ob_shape = self.ob_keys[None]
s = self.obs[:-1].view(-1, *ob_shape).numpy()
n_s = self.obs[1:].view(-1, *ob_shape).numpy()
mask = self.masks[1:].view(-1, 1).numpy()
actions = self.actions.view(-1, self.actions.size(-1)).numpy()
reward = self.rewards.view(-1, 1).numpy()
return s, n_s, actions, reward, mask
def get_scalars(self):
s, n_s, a, r, m = self.get_np_tensors()
return int(s[0]), int(n_s[0]), a[0, 0], r[0, 0], m[0, 0]
def recurrent_generator(self, advantages, num_mini_batch):
# Only called if args.recurrent_policy is True
num_processes = self.rewards.size(1)
assert num_processes >= num_mini_batch, (
"PPO requires the number of processes ({}) "
"to be greater than or equal to the number of "
"PPO mini batches ({}).".format(num_processes, num_mini_batch)
)
num_envs_per_batch = num_processes // num_mini_batch
perm = torch.randperm(num_processes)
for start_ind in range(0, num_processes, num_envs_per_batch):
obs_batch = []
hidden_states_batch = defaultdict(list)
obs_batch = defaultdict(list)
other_obs_batch = defaultdict(list)
actions_batch = []
value_preds_batch = []
return_batch = []
masks_batch = []
old_action_log_probs_batch = []
adv_targ = []
reward_batch = []
for offset in range(num_envs_per_batch):
ind = perm[start_ind + offset]
for k, ob_shape in self.ob_keys.items():
if k is None:
obs_batch[None].append(self.obs[:-1, ind])
elif k == self.args.policy_ob_key or k is None:
obs_batch[k].append(self.obs[k][:-1, ind])
else:
other_obs_batch[k].append(self.obs[k][:-1, ind])
for k in self.hidden_states:
hidden_states_batch[k].append(self.hidden_states[k][0:1, ind])
actions_batch.append(self.actions[:, ind])
value_preds_batch.append(self.value_preds[:-1, ind])
return_batch.append(self.returns[:-1, ind])
reward_batch.append(self.rewards[:, ind])
masks_batch.append(self.masks[:-1, ind])
old_action_log_probs_batch.append(self.action_log_probs[:, ind])
adv_targ.append(advantages[:, ind])
T, N = self.num_steps, num_envs_per_batch
# These are all tensors of size (T, N, -1)
actions_batch = torch.stack(actions_batch, 1)
value_preds_batch = torch.stack(value_preds_batch, 1)
return_batch = torch.stack(return_batch, 1)
reward_batch = torch.stack(reward_batch, 1)
masks_batch = torch.stack(masks_batch, 1)
old_action_log_probs_batch = torch.stack(old_action_log_probs_batch, 1)
adv_targ = torch.stack(adv_targ, 1)
# States is just a (N, -1) tensor
for k in hidden_states_batch:
hidden_states_batch[k] = torch.stack(hidden_states_batch[k], 1).view(
N, -1
)
# Flatten the (T, N, ...) tensors to (T * N, ...)
for k in obs_batch:
obs_batch[k] = torch.stack(obs_batch[k], 1)
obs_batch[k] = _flatten_helper(T, N, obs_batch[k])
for k in other_obs_batch:
other_obs_batch[k] = torch.stack(other_obs_batch[k], 1)
other_obs_batch[k] = _flatten_helper(T, N, other_obs_batch[k])
actions_batch = _flatten_helper(T, N, actions_batch)
value_preds_batch = _flatten_helper(T, N, value_preds_batch)
reward_batch = _flatten_helper(T, N, reward_batch)
return_batch = _flatten_helper(T, N, return_batch)
masks_batch = _flatten_helper(T, N, masks_batch)
old_action_log_probs_batch = _flatten_helper(
T, N, old_action_log_probs_batch
)
adv_targ = _flatten_helper(T, N, adv_targ)
# No need to return obs dict | |
<reponame>mmeyer724/sqlalchemy
"""
a series of tests which assert the behavior of moving objects between
collections and scalar attributes resulting in the expected state w.r.t.
backrefs, add/remove events, etc.
there's a particular focus on collections that have "uselist=False", since in
these cases the re-assignment of an attribute means the previous owner needs an
UPDATE in the database.
"""
from sqlalchemy import testing
from sqlalchemy.orm import attributes
from sqlalchemy.orm import backref
from sqlalchemy.orm import mapper
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session
from sqlalchemy.orm import sessionmaker
from sqlalchemy.testing import eq_
from sqlalchemy.testing import is_
from test.orm import _fixtures
class O2MCollectionTest(_fixtures.FixtureTest):
run_inserts = None
@classmethod
def setup_mappers(cls):
Address, addresses, users, User = (
cls.classes.Address,
cls.tables.addresses,
cls.tables.users,
cls.classes.User,
)
mapper(Address, addresses)
mapper(
User,
users,
properties=dict(addresses=relationship(Address, backref="user")),
)
def test_collection_move_hitslazy(self):
User, Address = self.classes.User, self.classes.Address
sess = sessionmaker()()
a1 = Address(email_address="address1")
a2 = Address(email_address="address2")
a3 = Address(email_address="address3")
u1 = User(name="jack", addresses=[a1, a2, a3])
u2 = User(name="ed")
sess.add_all([u1, a1, a2, a3])
sess.commit()
# u1.addresses
def go():
u2.addresses.append(a1)
u2.addresses.append(a2)
u2.addresses.append(a3)
self.assert_sql_count(testing.db, go, 0)
def test_collection_move_preloaded(self):
User, Address = self.classes.User, self.classes.Address
sess = sessionmaker()()
a1 = Address(email_address="address1")
u1 = User(name="jack", addresses=[a1])
u2 = User(name="ed")
sess.add_all([u1, u2])
sess.commit() # everything is expired
# load u1.addresses collection
u1.addresses
u2.addresses.append(a1)
# backref fires
assert a1.user is u2
# a1 removed from u1.addresses as of [ticket:2789]
assert a1 not in u1.addresses
assert a1 in u2.addresses
def test_collection_move_notloaded(self):
User, Address = self.classes.User, self.classes.Address
sess = sessionmaker()()
a1 = Address(email_address="address1")
u1 = User(name="jack", addresses=[a1])
u2 = User(name="ed")
sess.add_all([u1, u2])
sess.commit() # everything is expired
u2.addresses.append(a1)
# backref fires
assert a1.user is u2
# u1.addresses wasn't loaded,
# so when it loads its correct
assert a1 not in u1.addresses
assert a1 in u2.addresses
def test_collection_move_commitfirst(self):
User, Address = self.classes.User, self.classes.Address
sess = sessionmaker()()
a1 = Address(email_address="address1")
u1 = User(name="jack", addresses=[a1])
u2 = User(name="ed")
sess.add_all([u1, u2])
sess.commit() # everything is expired
# load u1.addresses collection
u1.addresses
u2.addresses.append(a1)
# backref fires
assert a1.user is u2
# everything expires, no changes in
# u1.addresses, so all is fine
sess.commit()
assert a1 not in u1.addresses
assert a1 in u2.addresses
def test_scalar_move_preloaded(self):
User, Address = self.classes.User, self.classes.Address
sess = sessionmaker()()
u1 = User(name="jack")
u2 = User(name="ed")
a1 = Address(email_address="a1")
a1.user = u1
sess.add_all([u1, u2, a1])
sess.commit()
# u1.addresses is loaded
u1.addresses
# direct set - the "old" is "fetched",
# but only from the local session - not the
# database, due to the PASSIVE_NO_FETCH flag.
# this is a more fine grained behavior introduced
# in 0.6
a1.user = u2
assert a1 not in u1.addresses
assert a1 in u2.addresses
def test_plain_load_passive(self):
"""test that many-to-one set doesn't load the old value."""
User, Address = self.classes.User, self.classes.Address
sess = sessionmaker()()
u1 = User(name="jack")
u2 = User(name="ed")
a1 = Address(email_address="a1")
a1.user = u1
sess.add_all([u1, u2, a1])
sess.commit()
# in this case, a lazyload would
# ordinarily occur except for the
# PASSIVE_NO_FETCH flag.
def go():
a1.user = u2
self.assert_sql_count(testing.db, go, 0)
assert a1 not in u1.addresses
assert a1 in u2.addresses
def test_set_none(self):
User, Address = self.classes.User, self.classes.Address
sess = sessionmaker()()
u1 = User(name="jack")
a1 = Address(email_address="a1")
a1.user = u1
sess.add_all([u1, a1])
sess.commit()
# works for None too
def go():
a1.user = None
self.assert_sql_count(testing.db, go, 0)
assert a1 not in u1.addresses
def test_scalar_move_notloaded(self):
User, Address = self.classes.User, self.classes.Address
sess = sessionmaker()()
u1 = User(name="jack")
u2 = User(name="ed")
a1 = Address(email_address="a1")
a1.user = u1
sess.add_all([u1, u2, a1])
sess.commit()
# direct set - the fetching of the
# "old" u1 here allows the backref
# to remove it from the addresses collection
a1.user = u2
assert a1 not in u1.addresses
assert a1 in u2.addresses
def test_scalar_move_commitfirst(self):
User, Address = self.classes.User, self.classes.Address
sess = sessionmaker()()
u1 = User(name="jack")
u2 = User(name="ed")
a1 = Address(email_address="a1")
a1.user = u1
sess.add_all([u1, u2, a1])
sess.commit()
# u1.addresses is loaded
u1.addresses
# direct set - the fetching of the
# "old" u1 here allows the backref
# to remove it from the addresses collection
a1.user = u2
sess.commit()
assert a1 not in u1.addresses
assert a1 in u2.addresses
def test_collection_assignment_mutates_previous_one(self):
User, Address = self.classes.User, self.classes.Address
u1 = User(name="jack")
u2 = User(name="ed")
a1 = Address(email_address="a1")
u1.addresses.append(a1)
is_(a1.user, u1)
u2.addresses = [a1]
eq_(u1.addresses, [])
is_(a1.user, u2)
def test_collection_assignment_mutates_previous_two(self):
User, Address = self.classes.User, self.classes.Address
u1 = User(name="jack")
a1 = Address(email_address="a1")
u1.addresses.append(a1)
is_(a1.user, u1)
u1.addresses = []
is_(a1.user, None)
def test_del_from_collection(self):
User, Address = self.classes.User, self.classes.Address
u1 = User(name="jack")
a1 = Address(email_address="a1")
u1.addresses.append(a1)
is_(a1.user, u1)
del u1.addresses[0]
is_(a1.user, None)
def test_del_from_scalar(self):
User, Address = self.classes.User, self.classes.Address
u1 = User(name="jack")
a1 = Address(email_address="a1")
u1.addresses.append(a1)
is_(a1.user, u1)
del a1.user
assert a1 not in u1.addresses
def test_tuple_assignment_w_reverse(self):
User, Address = self.classes.User, self.classes.Address
u1 = User()
a1 = Address(email_address="1")
a2 = Address(email_address="2")
a3 = Address(email_address="3")
u1.addresses.append(a1)
u1.addresses.append(a2)
u1.addresses.append(a3)
u1.addresses[1], u1.addresses[2] = u1.addresses[2], u1.addresses[1]
assert a3.user is u1
eq_(u1.addresses, [a1, a3, a2])
def test_straight_remove(self):
User, Address = self.classes.User, self.classes.Address
u1 = User()
a1 = Address(email_address="1")
a2 = Address(email_address="2")
a3 = Address(email_address="3")
u1.addresses.append(a1)
u1.addresses.append(a2)
u1.addresses.append(a3)
del u1.addresses[2]
assert a3.user is None
eq_(u1.addresses, [a1, a2])
def test_append_del(self):
User, Address = self.classes.User, self.classes.Address
u1 = User()
a1 = Address(email_address="1")
a2 = Address(email_address="2")
a3 = Address(email_address="3")
u1.addresses.append(a1)
u1.addresses.append(a2)
u1.addresses.append(a3)
u1.addresses.append(a2)
del u1.addresses[1]
assert a2.user is u1
eq_(u1.addresses, [a1, a3, a2])
def test_bulk_replace(self):
User, Address = self.classes.User, self.classes.Address
u1 = User()
a1 = Address(email_address="1")
a2 = Address(email_address="2")
a3 = Address(email_address="3")
u1.addresses.append(a1)
u1.addresses.append(a2)
u1.addresses.append(a3)
u1.addresses.append(a3)
assert a3.user is u1
u1.addresses = [a1, a2, a1]
assert a3.user is None
eq_(u1.addresses, [a1, a2, a1])
class O2OScalarBackrefMoveTest(_fixtures.FixtureTest):
run_inserts = None
@classmethod
def setup_mappers(cls):
Address, addresses, users, User = (
cls.classes.Address,
cls.tables.addresses,
cls.tables.users,
cls.classes.User,
)
mapper(Address, addresses)
mapper(
User,
users,
properties={
"address": relationship(
Address, backref=backref("user"), uselist=False
)
},
)
def test_collection_move_preloaded(self):
User, Address = self.classes.User, self.classes.Address
sess = sessionmaker()()
a1 = Address(email_address="address1")
u1 = User(name="jack", address=a1)
u2 = User(name="ed")
sess.add_all([u1, u2])
sess.commit() # everything is expired
# load u1.address
u1.address
# reassign
u2.address = a1
assert u2.address is a1
# backref fires
assert a1.user is u2
# doesn't extend to the previous attribute tho.
# flushing at this point means its anyone's guess.
assert u1.address is a1
assert u2.address is a1
def test_scalar_move_preloaded(self):
User, Address = self.classes.User, self.classes.Address
sess = sessionmaker()()
a1 = Address(email_address="address1")
a2 = Address(email_address="address1")
u1 = User(name="jack", address=a1)
sess.add_all([u1, a1, a2])
sess.commit() # everything is expired
# load a1.user
a1.user
# reassign
a2.user = u1
# backref fires
assert u1.address is a2
# stays on both sides
assert a1.user is u1
assert a2.user is u1
def test_collection_move_notloaded(self):
User, Address = self.classes.User, self.classes.Address
sess = sessionmaker()()
a1 = Address(email_address="address1")
u1 = User(name="jack", address=a1)
u2 = User(name="ed")
sess.add_all([u1, u2])
sess.commit() # everything is expired
# reassign
u2.address = a1
assert u2.address is a1
# backref fires
assert a1.user is u2
# u1.address loads now after a flush
assert u1.address is None
assert u2.address is a1
def test_scalar_move_notloaded(self):
User, Address = self.classes.User, self.classes.Address
sess = sessionmaker()()
a1 = Address(email_address="address1")
a2 = Address(email_address="address1")
u1 = User(name="jack", address=a1)
sess.add_all([u1, a1, a2])
sess.commit() # everything is expired
# reassign
a2.user = u1
# backref fires
assert u1.address is a2
# stays on both sides
assert a1.user is u1
assert a2.user is u1
def test_collection_move_commitfirst(self):
User, Address = self.classes.User, self.classes.Address
sess = sessionmaker()()
a1 = Address(email_address="address1")
u1 = User(name="jack", address=a1)
u2 = User(name="ed")
sess.add_all([u1, u2])
sess.commit() # everything is expired
# load u1.address
u1.address
# reassign
u2.address = a1
assert u2.address is a1
# backref fires
assert a1.user is u2
# the commit cancels out u1.addresses
# being loaded, on next access its fine.
sess.commit()
assert u1.address is None
assert u2.address is a1
def test_scalar_move_commitfirst(self):
User, Address = self.classes.User, self.classes.Address
sess = sessionmaker()()
a1 = Address(email_address="address1")
a2 = Address(email_address="address2")
u1 = User(name="jack", address=a1)
sess.add_all([u1, a1, a2])
sess.commit() # everything is expired
# load
assert a1.user is u1
# reassign
a2.user = u1
# backref fires
assert u1.address is a2
# didn't work this way tho
assert a1.user is u1
# moves appropriately after commit
sess.commit()
assert u1.address is a2
assert a1.user is None
assert | |
import tempfile
import unittest
import docker
from docker import models
from seaworthy.checks import docker_client, dockertest
from seaworthy.helpers import (
ContainerHelper, DockerHelper, ImageHelper, NetworkHelper, VolumeHelper,
_parse_image_tag, fetch_images)
# We use this image to test with because it is a small (~7MB) image from
# https://github.com/docker-library/official-images that runs indefinitely with
# no configuration.
IMG = 'nginx:alpine'
@dockertest()
def setUpModule(): # noqa: N802 (The camelCase is mandated by unittest.)
with docker_client() as client:
fetch_images(client, [IMG])
def filter_by_name(things, prefix):
return [t for t in things if t.name.startswith(prefix)]
# This is a private function but it's difficult to test indirectly without
# pulling images.
class TestParseImageTagFunc(unittest.TestCase):
def test_with_tag(self):
"""An image name with a tag is parsed into a name and tag."""
self.assertEqual(('test', 'foo'), _parse_image_tag('test:foo'))
def test_without_tag(self):
"""An image name without a tag is parsed into a name and None."""
self.assertEqual(('test', None), _parse_image_tag('test'))
def test_with_tag_and_registry(self):
"""
An image name with a tag and a registry is parsed into a name and tag.
"""
self.assertEqual(('myregistry:5000/test', 'foo'),
_parse_image_tag('myregistry:5000/test:foo'))
def test_without_tag_with_registry(self):
"""
An image name without a tag but with a registry is parsed into a name
and None.
"""
self.assertEqual(('myregistry:5000/test', None),
_parse_image_tag('myregistry:5000/test'))
@dockertest()
class TestImageHelper(unittest.TestCase):
def setUp(self):
self.client = docker.client.from_env()
self.addCleanup(self.client.api.close)
def make_helper(self):
return ImageHelper(self.client)
def test_fetch(self):
"""
We check if the image is already present and pull it if necessary.
"""
ih = self.make_helper()
# First, remove the image if it's already present. (We use the busybox
# image for this test because it's the smallest I can find that is
# likely to be reliably available.)
try:
self.client.images.get('busybox:latest')
except docker.errors.ImageNotFound: # pragma: no cover
pass
else:
self.client.images.remove('busybox:latest') # pragma: no cover
# Pull the image, which we now know we don't have.
with self.assertLogs('seaworthy', level='INFO') as cm:
ih.fetch('busybox:latest')
self.assertEqual(
[l.getMessage() for l in cm.records],
["Pulling tag 'latest' for image 'busybox'..."])
# Pull the image again, now that we know it's present.
with self.assertLogs('seaworthy', level='DEBUG') as cm:
ih.fetch('busybox:latest')
logs = [l.getMessage() for l in cm.records]
self.assertEqual(len(logs), 1)
self.assertRegex(
logs[0],
r"Found image 'sha256:[a-f0-9]{64}' for tag 'busybox:latest'")
@dockertest()
class TestNetworkHelper(unittest.TestCase):
def setUp(self):
self.client = docker.client.from_env()
self.addCleanup(self.client.api.close)
def make_helper(self, namespace='test'):
nh = NetworkHelper(self.client, namespace)
self.addCleanup(nh._teardown)
return nh
def list_networks(self, *args, namespace='test', **kw):
return filter_by_name(
self.client.networks.list(*args, **kw), '{}_'.format(namespace))
def test_default_lifecycle(self):
"""
The default network can only be created once and is removed during
teardown.
"""
nh = self.make_helper()
# The default network isn't created unless required
network = nh.get_default(create=False)
self.assertIsNone(network)
# Create the default network
network = nh.get_default(create=True)
self.assertIsNotNone(network)
# We can try to get the network lots of times and we get the same one
# and new ones aren't created.
nh.get_default(create=False)
nh.get_default(create=True)
networks = self.list_networks()
self.assertEqual(networks, [network])
# The default network is removed on teardown
nh._teardown()
network = nh.get_default(create=False)
self.assertIsNone(network)
def test_default_already_exists(self):
"""
If the default network already exists when we try to create it, we
fail.
"""
# We use a separate NetworkHelper (with the usual cleanup) to create
# the test network so that the DockerHelper under test will see that it
# already exists.
nh1 = self.make_helper()
nh1.get_default()
# Now for the test.
nh2 = self.make_helper()
with self.assertRaises(docker.errors.APIError) as cm:
nh2.get_default()
self.assertIn('network', str(cm.exception))
self.assertIn('already exists', str(cm.exception))
def test_teardown(self):
"""
NetworkHelper._teardown() will remove any networks that were created,
even if they no longer exist.
"""
nh = self.make_helper()
self.assertEqual([], self.list_networks())
net_bridge1 = nh.create('bridge1', driver='bridge')
net_bridge2 = nh.create('bridge2', driver='bridge')
net_removed = nh.create('removed')
# We remove this behind the helper's back so the helper thinks it still
# exists at teardown time.
net_removed.remove()
with self.assertRaises(docker.errors.NotFound):
net_removed.reload()
self.assertEqual(
set([net_bridge1, net_bridge2]),
set(self.list_networks()))
with self.assertLogs('seaworthy', level='WARNING') as cm:
nh._teardown()
self.assertEqual(sorted(l.getMessage() for l in cm.records), [
"Network 'test_bridge1' still existed during teardown",
"Network 'test_bridge2' still existed during teardown",
])
self.assertEqual([], self.list_networks())
def test_create(self):
"""
We can create a network with various parameters.
"""
nh = self.make_helper()
net_simple = nh.create('simple')
self.addCleanup(nh.remove, net_simple)
self.assertEqual(net_simple.name, 'test_simple')
self.assertEqual(net_simple.attrs['Driver'], 'bridge')
self.assertEqual(net_simple.attrs['Internal'], False)
net_internal = nh.create('internal', internal=True)
self.addCleanup(nh.remove, net_internal)
self.assertEqual(net_internal.name, 'test_internal')
self.assertEqual(net_internal.attrs['Internal'], True)
# Copy custom IPAM/subnet example from Docker docs:
# https://docker-py.readthedocs.io/en/2.5.1/networks.html#docker.models.networks.NetworkCollection.create
ipam_pool = docker.types.IPAMPool(
subnet='192.168.52.0/24', gateway='192.168.52.254')
ipam_config = docker.types.IPAMConfig(pool_configs=[ipam_pool])
net_subnet = nh.create('subnet', ipam=ipam_config)
self.addCleanup(nh.remove, net_subnet)
self.assertEqual(net_subnet.name, 'test_subnet')
config = net_subnet.attrs['IPAM']['Config'][0]
self.assertEqual(config['Subnet'], '192.168.52.0/24')
self.assertEqual(config['Gateway'], '192.168.52.254')
def test_remove(self):
"""
We can remove a network.
"""
nh = self.make_helper()
net_test = nh.create('test')
nh.remove(net_test)
with self.assertRaises(docker.errors.NotFound):
net_test.reload()
def test_custom_namespace(self):
"""
When the helper has a custom namespace, the networks created are
prefixed with the namespace.
"""
nh = self.make_helper(namespace='integ')
net = nh.create('net')
self.addCleanup(nh.remove, net)
self.assertEqual(net.name, 'integ_net')
@dockertest()
class TestVolumeHelper(unittest.TestCase):
def setUp(self):
self.client = docker.client.from_env()
self.addCleanup(self.client.api.close)
def make_helper(self, namespace='test'):
vh = VolumeHelper(self.client, namespace)
self.addCleanup(vh._teardown)
return vh
def list_volumes(self, *args, namespace='test', **kw):
return filter_by_name(
self.client.volumes.list(*args, **kw), '{}_'.format(namespace))
def test_teardown(self):
"""
VolumeHelper._teardown() will remove any volumes that were created,
even if they no longer exist.
"""
vh = self.make_helper()
self.assertEqual([], self.list_volumes())
vol_local1 = vh.create('local1', driver='local')
vol_local2 = vh.create('local2', driver='local')
vol_removed = vh.create('removed')
# We remove this behind the helper's back so the helper thinks it still
# exists at teardown time.
vol_removed.remove()
with self.assertRaises(docker.errors.NotFound):
vol_removed.reload()
self.assertEqual(
set([vol_local1, vol_local2]),
set(self.list_volumes()))
with self.assertLogs('seaworthy', level='WARNING') as cm:
vh._teardown()
self.assertEqual(sorted(l.getMessage() for l in cm.records), [
"Volume 'test_local1' still existed during teardown",
"Volume 'test_local2' still existed during teardown",
])
self.assertEqual([], self.list_volumes())
def test_create(self):
"""
We can create a volume with various parameters.
"""
vh = self.make_helper()
vol_simple = vh.create('simple')
self.addCleanup(vh.remove, vol_simple)
self.assertEqual(vol_simple.name, 'test_simple')
self.assertEqual(vol_simple.attrs['Driver'], 'local')
vol_labels = vh.create('labels', labels={'foo': 'bar'})
self.addCleanup(vh.remove, vol_labels)
self.assertEqual(vol_labels.name, 'test_labels')
self.assertEqual(vol_labels.attrs['Labels'], {'foo': 'bar'})
# Copy tmpfs example from Docker docs:
# https://docs.docker.com/engine/reference/commandline/volume_create/#driver-specific-options
# This won't work on Windows
driver_opts = {
'type': 'tmpfs', 'device': 'tmpfs', 'o': 'size=100m,uid=1000'}
vol_opts = vh.create('opts', driver='local', driver_opts=driver_opts)
self.addCleanup(vh.remove, vol_opts)
self.assertEqual(vol_opts.name, 'test_opts')
self.assertEqual(vol_opts.attrs['Options'], driver_opts)
def test_remove(self):
"""
We can remove a volume.
"""
vh = self.make_helper()
vol_test = vh.create('test')
vh.remove(vol_test)
with self.assertRaises(docker.errors.NotFound):
vol_test.reload()
def test_custom_namespace(self):
"""
When the helper has a custom namespace, the volumes created are
prefixed with the namespace.
"""
vh = self.make_helper(namespace='integ')
vol = vh.create('vol')
self.addCleanup(vh.remove, vol)
self.assertEqual(vol.name, 'integ_vol')
@dockertest()
class TestContainerHelper(unittest.TestCase):
def setUp(self):
self.client = docker.client.from_env()
self.addCleanup(self.client.api.close)
self.ih = ImageHelper(self.client)
self.nh = NetworkHelper(self.client, 'test')
self.addCleanup(self.nh._teardown)
self.vh = VolumeHelper(self.client, 'test')
self.addCleanup(self.vh._teardown)
def make_helper(self, namespace='test'):
ch = ContainerHelper(self.client, namespace, self.ih, self.nh, self.vh)
self.addCleanup(ch._teardown)
return ch
def list_containers(self, *args, namespace='test', **kw):
return filter_by_name(
self.client.containers.list(*args, **kw), '{}_'.format(namespace))
def test_teardown(self):
"""
ContainerHelper._teardown() will remove any containers that were
created, no matter what state they are in or even whether they still
exist.
"""
ch = self.make_helper()
self.assertEqual([], self.list_containers(all=True))
con_created = ch.create('created', IMG)
self.assertEqual(con_created.status, 'created')
con_running = ch.create('running', IMG)
con_running.start()
con_running.reload()
self.assertEqual(con_running.status, 'running')
con_stopped = ch.create('stopped', IMG)
con_stopped.start()
con_stopped.reload()
self.assertEqual(con_stopped.status, 'running')
con_stopped.stop()
con_stopped.reload()
self.assertNotEqual(con_stopped.status, 'running')
con_removed = ch.create('removed', IMG)
# We remove this behind the helper's back so the helper thinks it still
# exists at teardown time.
con_removed.remove()
with self.assertRaises(docker.errors.NotFound):
con_removed.reload()
self.assertEqual(
set([con_created, con_running, con_stopped]),
set(self.list_containers(all=True)))
with self.assertLogs('seaworthy', level='WARNING') as cm:
ch._teardown()
self.assertEqual(sorted(l.getMessage() for l in cm.records), [
"Container 'test_created' still existed during teardown",
"Container 'test_running' still existed during teardown",
"Container 'test_stopped' still existed during teardown",
])
self.assertEqual([], self.list_containers(all=True))
def test_create(self):
"""
We can create a container with various parameters without starting it.
"""
ch = self.make_helper()
con_simple = ch.create('simple', IMG)
self.addCleanup(ch.remove, con_simple)
self.assertEqual(con_simple.status, 'created')
self.assertEqual(con_simple.attrs['Path'], 'nginx')
con_cmd = ch.create('cmd', IMG, command='echo hello')
self.addCleanup(ch.remove, con_cmd)
self.assertEqual(con_cmd.status, 'created')
self.assertEqual(con_cmd.attrs['Path'], 'echo')
con_env = ch.create('env', IMG, environment={'FOO': 'bar'})
self.addCleanup(ch.remove, con_env)
self.assertEqual(con_env.status, 'created')
self.assertIn('FOO=bar', con_env.attrs['Config']['Env'])
def test_network(self):
"""
When a container is created, the network settings are respected, and if
no network settings are specified, the container is connected to a
default network.
"""
ch = self.make_helper()
# When 'network' is provided, that network is used
custom_network = self.nh.create('network')
self.addCleanup(self.nh.remove, custom_network)
con_network = ch.create('network', IMG, network=custom_network)
self.addCleanup(ch.remove, con_network)
networks = con_network.attrs['NetworkSettings']['Networks']
self.assertEqual(list(networks.keys()), [custom_network.name])
network = networks[custom_network.name]
self.assertCountEqual(
network['Aliases'], [con_network.id[:12], 'network'])
# When 'network_mode' is provided, the default network is not used
con_mode = ch.create('mode', IMG, network_mode='none')
self.addCleanup(ch.remove, con_mode)
networks = con_mode.attrs['NetworkSettings']['Networks']
self.assertEqual(list(networks.keys()), ['none'])
# When 'network_disabled' is True, the default network is not used
con_disabled = ch.create(
'disabled', IMG, network_disabled=True)
self.addCleanup(ch.remove, con_disabled)
self.assertEqual(con_disabled.attrs['NetworkSettings']['Networks'], {})
con_default = ch.create('default', IMG)
self.addCleanup(ch.remove, con_default)
default_network_name = self.nh.get_default().name
networks = con_default.attrs['NetworkSettings']['Networks']
self.assertEqual(list(networks.keys()), [default_network_name])
network = networks[default_network_name]
self.assertCountEqual(
network['Aliases'], [con_default.id[:12], 'default'])
def test_network_by_id(self):
"""
When | |
<reponame>vanvalenlab/deepcell-spots
# Copyright 2019-2022 The <NAME> at the California Institute of
# Technology (Caltech), with support from the Paul Allen Family Foundation,
# Google, & National Institutes of Health (NIH) under Grant U24CA224309-01.
# All rights reserved.
#
# Licensed under a modified 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.github.com/vanvalenlab/deepcell-spots/LICENSE
#
# The Work provided may be used for non-commercial academic purposes only.
# For any other use of the Work, including commercial use, please contact:
# <EMAIL>
#
# Neither the name of Caltech nor the names of its contributors may be used
# to endorse or promote products derived from this software without specific
# prior written permission.
#
# 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.
# ==============================================================================
"""Functions for image augmentation"""
import numpy as np
from keras_preprocessing.image.affine_transformations import \
transform_matrix_offset_center
from scipy.ndimage.morphology import distance_transform_edt
def subpixel_distance_transform(point_list, image_shape, dy=1, dx=1):
"""For each pixel in image, return the vectorial distance to a point in
``point_list`` that is in the pixel nearest to it.
Args:
point_list: (N,2) numpy array of point coordinates [y, x]
(y before x as in image/matrix indexing)
image_shape: (Ly,Lx) specifies the shape of an image that contains
the coordinates.
The coordinates should be in dy*[-0.5, Ly-0.5] x dx*[-0.5, Lx-0.5]
dy: pixel width in y axis
dx: pixel width in x axis
Returns:
numpy.array: (Ly, Lx), nearest_point[i,j] is the index in point_list of
a point in a point-containing pixel which is closest to pixel [i,j].
Note no uniqueness of the point or the pixel, since there could be
several point-containing pixels with minimal distance to pixel [i,j]
and there could be several points contained in the pixel [i,j] but
only one is chosen delta_x[i,j], delta_y[i,j] are elements of the
vectorial distance between the chosen point which nearest_point[i,j]
refers to, and the center of the pixel [i,j],
which is at x =j * dx, y = i * dy.
numpy.array: (Ly, Lx) numpy array of signed y distance between a point
from ``point_list`` that is near pixel [i,j] and the center of the
pixel.
numpy.array: (Ly, Lx) numpy array of signed x distance between a point
from ``point_list`` that is near pixel [i,j] and the center of the
pixel.
"""
# create an image with 0 = pixel containing point from point_list, 1 = pixel not containing
# point from point_list
contains_point = np.ones(image_shape)
# index in point_list of point nearest to pixel
nearest_point = np.full(image_shape, np.nan)
# dictionary to be filled s.t.: pixel_to_contained_point_ind[(i,j)] = k if point_list[k]
# is a point contained in pixel i,j of the image
pixel_to_contained_point_ind = {}
for ind, [y, x] in enumerate(point_list):
nearest_pixel_y_ind = int(round(y / dy))
nearest_pixel_x_ind = int(round(x / dx))
contains_point[nearest_pixel_y_ind, nearest_pixel_x_ind] = 0
pixel_to_contained_point_ind[(
nearest_pixel_y_ind, nearest_pixel_x_ind)] = ind
edt, inds = distance_transform_edt(
contains_point, return_indices=True, sampling=[dy, dx])
# signed y distance to nearest point
delta_y = np.full(image_shape, np.inf)
# signed x distance to nearest point
delta_x = np.full(image_shape, np.inf)
Ly, Lx = image_shape
for j in range(0, Lx):
for i in range(0, Ly):
# inds[0][i,j] # y index of nearest pixel to [i,j] which contains a point
# inds[1][i,j] # x index of nearest pixel to [i,j] which contains a point
# nearest_point[i,j] # index in point_list of point contained by pixel [i,j]
nearest_point[i, j] = pixel_to_contained_point_ind[(
inds[0][i, j], inds[1][i, j])]
delta_y[i, j] = dy * (point_list[int(nearest_point[i, j])][0] - i)
delta_x[i, j] = dx * (point_list[int(nearest_point[i, j])][1] - j)
return delta_y, delta_x, nearest_point
def generate_transformation_matrix(transform_parameters, image_shape, img_row_axis, img_col_axis):
"""Given a dictionary of affine transformation parameters (such as the one
generated by the ImageDataGenerator function get_random_transform),
generate the transformation matrix and offset which apply_affine_transform
generates and passes to scipy.ndimage.interpolation.affine_transform:
ndimage.interpolation.affine_transform(
x_channel,
final_affine_matrix,
final_offset,
order=order,
mode=fill_mode,
cval=cval)
this function performs the calculations performed by
tf.keras.preprocessing.image.apply_affine_transform
to obtain final_affine_matrix and final_offset, and returns them.
A point p in the output image of affine_transform corresponds to the point
pT+s in the input image
Args:
transform_parameters: dictionary of affine transformation parameters such as
the output of ImageDataGenerator get_random_transform
(as used in input to apply_transform called on image)
From keras-preprocessing/keras_preprocessing/image/image_data_generator.py,
apply_transform documentation:
Dictionary with string - parameter pairs describing the transformation.
Currently, the following parameters
from the dictionary are used:
- `'theta'`: Float. Rotation angle in degrees.
- `'tx'`: Float. Shift in the x direction.
- `'ty'`: Float. Shift in the y direction.
- `'shear'`: Float. Shear angle in degrees.
- `'zx'`: Float. Zoom in the x direction.
- `'zy'`: Float. Zoom in the y direction.
- `'flip_horizontal'`: Boolean. Horizontal flip. - NOT USED HERE
- `'flip_vertical'`: Boolean. Vertical flip. - NOT USED HERE
- `'channel_shift_intensity'`: Float. Channel shift intensity.
- `'brightness'`: Float. Brightness shift intensity.
Returns:
final_affine_matrix (2*2 matrix ,denote below: T)
final_offset (length 2 vector, denote below: s)
"""
# get transform parameters from the input dictionary (if non given, the default value in
# apply_affine_transform is used)
theta = transform_parameters.get('theta', 0)
tx = transform_parameters.get('tx', 0)
ty = transform_parameters.get('ty', 0)
shear = transform_parameters.get('shear', 0)
zx = transform_parameters.get('zx', 1)
zy = transform_parameters.get('zy', 1)
# generate the transform matrix and offset vector
transform_matrix = None
if theta != 0:
theta = np.deg2rad(theta)
rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0],
[0, 0, 1]])
transform_matrix = rotation_matrix
if tx != 0 or ty != 0:
shift_matrix = np.array([[1, 0, tx],
[0, 1, ty],
[0, 0, 1]])
if transform_matrix is None:
transform_matrix = shift_matrix
else:
transform_matrix = np.dot(transform_matrix, shift_matrix)
if shear != 0:
shear = np.deg2rad(shear)
shear_matrix = np.array([[1, -np.sin(shear), 0],
[0, np.cos(shear), 0],
[0, 0, 1]])
if transform_matrix is None:
transform_matrix = shear_matrix
else:
transform_matrix = np.dot(transform_matrix, shear_matrix)
if zx != 1 or zy != 1:
zoom_matrix = np.array([[zx, 0, 0],
[0, zy, 0],
[0, 0, 1]])
if transform_matrix is None:
transform_matrix = zoom_matrix
else:
transform_matrix = np.dot(transform_matrix, zoom_matrix)
if transform_matrix is None:
# if no shift, shear or zoom are done, the transformation is the identity
transform_matrix = np.array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
# if transform_matrix is not None:
h, w = image_shape[img_row_axis], image_shape[img_col_axis]
transform_matrix = transform_matrix_offset_center(transform_matrix, h, w)
final_affine_matrix = transform_matrix[:2, :2]
final_offset = transform_matrix[:2, 2]
return final_affine_matrix, final_offset
def affine_transform_points(points, transform_parameters,
image_shape, img_row_axis=0, img_col_axis=1, fill_mode='nearest'):
"""Perform an affine transform mapping input coordinates referring to the
input image of the apply_transform function of the class ImageDataGenerator
To the output space of that function. Returned points are (original and
padding points) contained in the output image.
Args:
transform_parameters: dictionary of affine transformation parameters
such as the output of ImageDataGenerator get_random_transform
points: (N, 2) numpy array which contains points in the format [y, x]
(NOTE: as in image/matrix notation, not Cartesian notation)
points are labels for the input image
- they should be -0.5 <= x <= Lx-0.5, -0.5 <= y <= Ly-0.5
where Lx = image_shape[img_col_axis], Ly = image_shape[img_row_axis]
image_shape (tuple): the shape of the image which contains the points
(for 2D image, has length 2)
img_row_axis: the index of the axis (0 or 1) to be flipped when
``flip_vertical`` is True
img_col_axis: the index of the axis (0 or 1) to be flipped when
``flip_horizontal`` is True
fill_mode: One of {"constant", "nearest", "reflect" or "wrap"}.
Default is 'nearest'. Points outside the boundaries of the input
are filled according to the given mode:
'constant': kkkkkkkk|abcd|kkkkkkkk (cval=k)
'nearest': aaaaaaaa|abcd|dddddddd
'reflect': abcddcba|abcd|dcbaabcd
'wrap': abcdabcd|abcd|abcdabcd
Returns:
transformed_points: list of points / or numpy array of shape (N',2)
which contains points in the format [y, x].
NOTE N' != N because points in the original image may fall outside
of the transformed output image. Also, if fill_mode is 'reflect' or
'wrap', point images in the padding of the | |
import pytest
pytest.importorskip("numpy")
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_array_equal
import dask.array as da
from dask.array.overlap import (
boundaries,
constant,
ensure_minimum_chunksize,
nearest,
overlap,
overlap_internal,
periodic,
reflect,
trim_internal,
)
from dask.array.utils import assert_eq, same_keys
from ..lib.stride_tricks import sliding_window_view
def test_overlap_internal():
x = np.arange(64).reshape((8, 8))
d = da.from_array(x, chunks=(4, 4))
g = overlap_internal(d, {0: 2, 1: 1})
result = g.compute(scheduler="sync")
assert g.chunks == ((6, 6), (5, 5))
expected = np.array(
[
[0, 1, 2, 3, 4, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 12, 11, 12, 13, 14, 15],
[16, 17, 18, 19, 20, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 27, 28, 29, 30, 31],
[32, 33, 34, 35, 36, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 43, 44, 45, 46, 47],
[16, 17, 18, 19, 20, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 27, 28, 29, 30, 31],
[32, 33, 34, 35, 36, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 43, 44, 45, 46, 47],
[48, 49, 50, 51, 52, 51, 52, 53, 54, 55],
[56, 57, 58, 59, 60, 59, 60, 61, 62, 63],
]
)
assert_eq(result, expected)
assert same_keys(overlap_internal(d, {0: 2, 1: 1}), g)
def test_overlap_internal_asymmetric():
x = np.arange(64).reshape((8, 8))
d = da.from_array(x, chunks=(4, 4))
result = overlap_internal(d, {0: (2, 0), 1: (1, 0)})
assert result.chunks == ((4, 6), (4, 5))
expected = np.array(
[
[0, 1, 2, 3, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 11, 12, 13, 14, 15],
[16, 17, 18, 19, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 27, 28, 29, 30, 31],
[16, 17, 18, 19, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 27, 28, 29, 30, 31],
[32, 33, 34, 35, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 43, 44, 45, 46, 47],
[48, 49, 50, 51, 51, 52, 53, 54, 55],
[56, 57, 58, 59, 59, 60, 61, 62, 63],
]
)
assert_eq(result, expected)
assert same_keys(overlap_internal(d, {0: (2, 0), 1: (1, 0)}), result)
def test_overlap_internal_asymmetric_small():
x = np.arange(32).reshape((2, 16))
d = da.from_array(x, chunks=(2, 4))
result = overlap_internal(d, {0: (0, 0), 1: (1, 1)})
assert result.chunks == ((2,), (5, 6, 6, 5))
expected = np.array(
[
[0, 1, 2, 3, 4, 3, 4, 5, 6, 7, 8, 7, 8, 9, 10, 11, 12, 11, 12, 13, 14, 15],
[
16,
17,
18,
19,
20,
19,
20,
21,
22,
23,
24,
23,
24,
25,
26,
27,
28,
27,
28,
29,
30,
31,
],
]
)
assert_eq(result, expected)
assert same_keys(overlap_internal(d, {0: (0, 0), 1: (1, 1)}), result)
def test_trim_internal():
d = da.ones((40, 60), chunks=(10, 10))
e = trim_internal(d, axes={0: 1, 1: 2})
assert e.chunks == ((8, 8, 8, 8), (6, 6, 6, 6, 6, 6))
def test_periodic():
x = np.arange(64).reshape((8, 8))
d = da.from_array(x, chunks=(4, 4))
e = periodic(d, axis=0, depth=2)
assert e.shape[0] == d.shape[0] + 4
assert e.shape[1] == d.shape[1]
assert_eq(e[1, :], d[-1, :])
assert_eq(e[0, :], d[-2, :])
def test_reflect():
x = np.arange(10)
d = da.from_array(x, chunks=(5, 5))
e = reflect(d, axis=0, depth=2)
expected = np.array([1, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8])
assert_eq(e, expected)
e = reflect(d, axis=0, depth=1)
expected = np.array([0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9])
assert_eq(e, expected)
def test_nearest():
x = np.arange(10)
d = da.from_array(x, chunks=(5, 5))
e = nearest(d, axis=0, depth=2)
expected = np.array([0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9])
assert_eq(e, expected)
e = nearest(d, axis=0, depth=1)
expected = np.array([0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9])
assert_eq(e, expected)
def test_constant():
x = np.arange(64).reshape((8, 8))
d = da.from_array(x, chunks=(4, 4))
e = constant(d, axis=0, depth=2, value=10)
assert e.shape[0] == d.shape[0] + 4
assert e.shape[1] == d.shape[1]
assert_eq(e[1, :], np.ones(8, dtype=x.dtype) * 10)
assert_eq(e[-1, :], np.ones(8, dtype=x.dtype) * 10)
def test_boundaries():
x = np.arange(64).reshape((8, 8))
d = da.from_array(x, chunks=(4, 4))
e = boundaries(d, {0: 2, 1: 1}, {0: 0, 1: "periodic"})
expected = np.array(
[
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[7, 0, 1, 2, 3, 4, 5, 6, 7, 0],
[15, 8, 9, 10, 11, 12, 13, 14, 15, 8],
[23, 16, 17, 18, 19, 20, 21, 22, 23, 16],
[31, 24, 25, 26, 27, 28, 29, 30, 31, 24],
[39, 32, 33, 34, 35, 36, 37, 38, 39, 32],
[47, 40, 41, 42, 43, 44, 45, 46, 47, 40],
[55, 48, 49, 50, 51, 52, 53, 54, 55, 48],
[63, 56, 57, 58, 59, 60, 61, 62, 63, 56],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]
)
assert_eq(e, expected)
def test_overlap():
x = np.arange(64).reshape((8, 8))
d = da.from_array(x, chunks=(4, 4))
g = overlap(d, depth={0: 2, 1: 1}, boundary={0: 100, 1: "reflect"})
assert g.chunks == ((8, 8), (6, 6))
expected = np.array(
[
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100],
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100],
[0, 0, 1, 2, 3, 4, 3, 4, 5, 6, 7, 7],
[8, 8, 9, 10, 11, 12, 11, 12, 13, 14, 15, 15],
[16, 16, 17, 18, 19, 20, 19, 20, 21, 22, 23, 23],
[24, 24, 25, 26, 27, 28, 27, 28, 29, 30, 31, 31],
[32, 32, 33, 34, 35, 36, 35, 36, 37, 38, 39, 39],
[40, 40, 41, 42, 43, 44, 43, 44, 45, 46, 47, 47],
[16, 16, 17, 18, 19, 20, 19, 20, 21, 22, 23, 23],
[24, 24, 25, 26, 27, 28, 27, 28, 29, 30, 31, 31],
[32, 32, 33, 34, 35, 36, 35, 36, 37, 38, 39, 39],
[40, 40, 41, 42, 43, 44, 43, 44, 45, 46, 47, 47],
[48, 48, 49, 50, 51, 52, 51, 52, 53, 54, 55, 55],
[56, 56, 57, 58, 59, 60, 59, 60, 61, 62, 63, 63],
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100],
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100],
]
)
assert_eq(g, expected)
assert same_keys(g, overlap(d, depth={0: 2, 1: 1}, boundary={0: 100, 1: "reflect"}))
u_depth = np.uint16([2, 1])
u_depth = {k: v for k, v in enumerate(u_depth)}
g = overlap(d, depth=u_depth, boundary={0: 100, 1: "reflect"})
assert g.chunks == ((8, 8), (6, 6))
assert_eq(g, expected)
assert same_keys(g, overlap(d, depth={0: 2, 1: 1}, boundary={0: 100, 1: "reflect"}))
g = overlap(d, depth={0: 2, 1: 1}, boundary={0: 100, 1: "none"})
expected = np.array(
[
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100],
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100],
[0, 1, 2, 3, 4, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 12, 11, 12, 13, 14, 15],
[16, 17, 18, 19, 20, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 27, 28, 29, 30, 31],
[32, 33, 34, 35, 36, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 43, 44, 45, 46, 47],
[16, 17, 18, 19, 20, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 27, 28, 29, 30, 31],
[32, 33, 34, 35, 36, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 43, 44, 45, 46, 47],
[48, 49, 50, 51, 52, 51, 52, 53, 54, 55],
[56, 57, 58, 59, 60, 59, 60, 61, 62, 63],
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100],
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100],
]
)
assert_eq(g, expected)
assert g.chunks == ((8, 8), (5, 5))
u_depth = np.uint16([2, 1])
u_depth = {k: v for k, v in enumerate(u_depth)}
g = overlap(d, depth=u_depth, boundary={0: 100, 1: "none"})
assert_eq(g, expected)
assert g.chunks == ((8, 8), (5, 5))
def test_asymmetric_overlap_boundary_exception():
x = da.arange(10, chunks=5)
with pytest.raises(NotImplementedError):
x.map_overlap(
lambda x: x + len(x), depth={0: (0, | |
= Column(INTEGER(255))
noservice = Column(TINYINT(1), server_default=text("'0'"))
plannoservice = Column(TINYINT(1), server_default=text("'0'"))
address = Column(String(255))
status = Column(String(100), server_default=text("'adapting'"))
goal = Column(Text)
comment = Column(Text)
class RaActionsAccountsC(Base):
__tablename__ = 'ra_actions_accounts_c'
__table_args__ = (
Index('ra_actions_accounts_alt', 'ra_actions_accountsra_actions_ida', 'ra_actions_accountsaccounts_idb'),
)
id = Column(String(36), primary_key=True)
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
ra_actions_accountsra_actions_ida = Column(String(36))
ra_actions_accountsaccounts_idb = Column(String(36))
class RaActionsAudit(Base):
__tablename__ = 'ra_actions_audit'
id = Column(CHAR(36), primary_key=True)
parent_id = Column(CHAR(36), nullable=False, index=True)
date_created = Column(DateTime)
created_by = Column(String(36))
field_name = Column(String(100))
data_type = Column(String(100))
before_value_string = Column(String(255))
after_value_string = Column(String(255))
before_value_text = Column(Text)
after_value_text = Column(Text)
class RaActionsCasesC(Base):
__tablename__ = 'ra_actions_cases_c'
__table_args__ = (
Index('ra_actions_cases_alt', 'ra_actions_casesra_actions_ida', 'ra_actions_casescases_idb'),
)
id = Column(String(36), primary_key=True)
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
ra_actions_casesra_actions_ida = Column(String(36))
ra_actions_casescases_idb = Column(String(36))
class RaActionsNotesC(Base):
__tablename__ = 'ra_actions_notes_c'
__table_args__ = (
Index('ra_actions_notes_alt', 'ra_actions_notesra_actions_ida', 'ra_actions_notesnotes_idb'),
)
id = Column(String(36), primary_key=True)
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
ra_actions_notesra_actions_ida = Column(String(36))
ra_actions_notesnotes_idb = Column(String(36))
class RaActionsSecuritygroups1C(Base):
__tablename__ = 'ra_actions_securitygroups_1_c'
__table_args__ = (
Index('ra_actions_securitygroups_1_alt', 'ra_actions_securitygroups_1ra_actions_ida', 'ra_actions_securitygroups_1securitygroups_idb'),
)
id = Column(String(36), primary_key=True)
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
ra_actions_securitygroups_1ra_actions_ida = Column(String(36))
ra_actions_securitygroups_1securitygroups_idb = Column(String(36))
class RaActionsTasksC(Base):
__tablename__ = 'ra_actions_tasks_c'
__table_args__ = (
Index('ra_actions_tasks_alt', 'ra_actions_tasksra_actions_ida', 'ra_actions_taskstasks_idb'),
)
id = Column(String(36), primary_key=True)
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
ra_actions_tasksra_actions_ida = Column(String(36))
ra_actions_taskstasks_idb = Column(String(36))
class RaClaim(Base):
__tablename__ = 'ra_claim'
id = Column(CHAR(36), primary_key=True)
name = Column(String(255))
date_entered = Column(DateTime)
date_modified = Column(DateTime)
modified_user_id = Column(CHAR(36))
created_by = Column(CHAR(36))
description = Column(Text)
deleted = Column(TINYINT(1), server_default=text("'0'"))
assigned_user_id = Column(CHAR(36))
date_event = Column(Date)
group_onus = Column(String(100))
volume = Column(Text)
class RaClaimAudit(Base):
__tablename__ = 'ra_claim_audit'
id = Column(CHAR(36), primary_key=True)
parent_id = Column(CHAR(36), nullable=False, index=True)
date_created = Column(DateTime)
created_by = Column(String(36))
field_name = Column(String(100))
data_type = Column(String(100))
before_value_string = Column(String(255))
after_value_string = Column(String(255))
before_value_text = Column(Text)
after_value_text = Column(Text)
class RaClaimBugs1C(Base):
__tablename__ = 'ra_claim_bugs_1_c'
id = Column(String(36), primary_key=True)
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
ra_claim_bugs_1ra_claim_ida = Column(String(36), index=True)
ra_claim_bugs_1bugs_idb = Column(String(36), index=True)
class RaClaimCasesC(Base):
__tablename__ = 'ra_claim_cases_c'
__table_args__ = (
Index('ra_claim_cases_alt', 'ra_claim_casesra_claim_ida', 'ra_claim_casescases_idb'),
)
id = Column(String(36), primary_key=True)
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
ra_claim_casesra_claim_ida = Column(String(36))
ra_claim_casescases_idb = Column(String(36))
class RaClaimNotesC(Base):
__tablename__ = 'ra_claim_notes_c'
id = Column(String(36), primary_key=True)
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
ra_claim_notesra_claim_ida = Column(String(36), index=True)
ra_claim_notesnotes_idb = Column(String(36), index=True)
class RaClaimPhysiCasesPC(Base):
__tablename__ = 'ra_claim_physi_cases_p_c'
__table_args__ = (
Index('ra_claim_physi_cases_p_alt', 'ra_claim_physi_cases_pra_claim_ida', 'ra_claim_physi_cases_pphysi_cases_p_idb'),
)
id = Column(String(36), primary_key=True)
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
ra_claim_physi_cases_pra_claim_ida = Column(String(36))
ra_claim_physi_cases_pphysi_cases_p_idb = Column(String(36))
class RaClaimRaActionsC(Base):
__tablename__ = 'ra_claim_ra_actions_c'
__table_args__ = (
Index('ra_claim_ra_actions_alt', 'ra_claim_ra_actionsra_claim_ida', 'ra_claim_ra_actionsra_actions_idb'),
)
id = Column(String(36), primary_key=True)
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
ra_claim_ra_actionsra_claim_ida = Column(String(36))
ra_claim_ra_actionsra_actions_idb = Column(String(36))
class RaSurvey(Base):
__tablename__ = 'ra_survey'
id = Column(CHAR(36), primary_key=True)
name = Column(String(255))
date_entered = Column(DateTime)
date_modified = Column(DateTime)
modified_user_id = Column(CHAR(36))
created_by = Column(CHAR(36))
description = Column(Text)
deleted = Column(TINYINT(1), server_default=text("'0'"))
assigned_user_id = Column(CHAR(36))
address = Column(String(255))
contact = Column(String(255))
status = Column(String(100), server_default=text("'request'"))
description_survey = Column(Text)
date_request = Column(Date)
addressmap = Column(String(255), server_default=text("'maps.google.com?q= Russia, Kirov, {address}&output=embed'"))
date_survey = Column(Date)
resolution = Column(String(255))
class RaSurveyAccRequisition1C(Base):
__tablename__ = 'ra_survey_acc_requisition_1_c'
__table_args__ = (
Index('ra_survey_acc_requisition_1_alt', 'ra_survey_acc_requisition_1ra_survey_ida', 'ra_survey_acc_requisition_1acc_requisition_idb'),
)
id = Column(String(36), primary_key=True)
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
ra_survey_acc_requisition_1ra_survey_ida = Column(String(36))
ra_survey_acc_requisition_1acc_requisition_idb = Column(String(36))
class RaSurveyAccountsC(Base):
__tablename__ = 'ra_survey_accounts_c'
id = Column(String(36), primary_key=True)
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
ra_survey_accountsra_survey_ida = Column(String(36), index=True)
ra_survey_accountsaccounts_idb = Column(String(36), index=True)
class RaSurveyAudit(Base):
__tablename__ = 'ra_survey_audit'
id = Column(CHAR(36), primary_key=True)
parent_id = Column(CHAR(36), nullable=False, index=True)
date_created = Column(DateTime)
created_by = Column(String(36))
field_name = Column(String(100))
data_type = Column(String(100))
before_value_string = Column(String(255))
after_value_string = Column(String(255))
before_value_text = Column(Text)
after_value_text = Column(Text)
class RaSurveyCstm(Base):
__tablename__ = 'ra_survey_cstm'
id_c = Column(CHAR(36), primary_key=True)
source_inf_c = Column(Text)
permit_installation_c = Column(String(100), server_default=text("'none'"))
ess_comment_c = Column(Text)
date_installation_c = Column(Date)
position_c = Column(String(50))
maps_pos_c = Column(String(255), server_default=text("'https://www.google.ru/maps/place/58.6008947,49.6473304,14z'"))
status_rs_c = Column(String(100), server_default=text("'none'"))
comment_rs_c = Column(Text)
class RaSurveyNotesC(Base):
__tablename__ = 'ra_survey_notes_c'
id = Column(String(36), primary_key=True)
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
ra_survey_notesra_survey_ida = Column(String(36), index=True)
ra_survey_notesnotes_idb = Column(String(36), index=True)
class RaSurveyPhysiPhisicC(Base):
__tablename__ = 'ra_survey_physi_phisic_c'
id = Column(String(36), primary_key=True)
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
ra_survey_physi_phisicra_survey_ida = Column(String(36), index=True)
ra_survey_physi_phisicphysi_phisic_idb = Column(String(36), index=True)
class Relationship(Base):
__tablename__ = 'relationships'
id = Column(CHAR(36), primary_key=True)
relationship_name = Column(String(150), index=True)
lhs_module = Column(String(100))
lhs_table = Column(String(64))
lhs_key = Column(String(64))
rhs_module = Column(String(100))
rhs_table = Column(String(64))
rhs_key = Column(String(64))
join_table = Column(String(128))
join_key_lhs = Column(String(128))
join_key_rhs = Column(String(128))
relationship_type = Column(String(64))
relationship_role_column = Column(String(64))
relationship_role_column_value = Column(String(50))
reverse = Column(TINYINT(1), server_default=text("'0'"))
deleted = Column(TINYINT(1), server_default=text("'0'"))
class Release(Base):
__tablename__ = 'releases'
__table_args__ = (
Index('idx_releases', 'name', 'deleted'),
)
id = Column(CHAR(36), primary_key=True)
deleted = Column(TINYINT(1))
date_entered = Column(DateTime)
date_modified = Column(DateTime)
modified_user_id = Column(CHAR(36))
created_by = Column(CHAR(36))
name = Column(String(50))
list_order = Column(INTEGER(4))
status = Column(String(100))
class RepRepair(Base):
__tablename__ = 'rep_repairs'
id = Column(CHAR(36), primary_key=True)
name = Column(String(255))
date_entered = Column(DateTime)
date_modified = Column(DateTime)
modified_user_id = Column(CHAR(36))
created_by = Column(CHAR(36))
description = Column(Text)
deleted = Column(TINYINT(1), server_default=text("'0'"))
assigned_user_id = Column(CHAR(36))
class RepRepairsAudit(Base):
__tablename__ = 'rep_repairs_audit'
id = Column(CHAR(36), primary_key=True)
parent_id = Column(CHAR(36), nullable=False, index=True)
date_created = Column(DateTime)
created_by = Column(String(36))
field_name = Column(String(100))
data_type = Column(String(100))
before_value_string = Column(String(255))
after_value_string = Column(String(255))
before_value_text = Column(Text)
after_value_text = Column(Text)
class RepRepairsBugs1C(Base):
__tablename__ = 'rep_repairs_bugs_1_c'
__table_args__ = (
Index('rep_repairs_bugs_1_alt', 'rep_repairs_bugs_1rep_repairs_ida', 'rep_repairs_bugs_1bugs_idb'),
)
id = Column(String(36), primary_key=True)
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
rep_repairs_bugs_1rep_repairs_ida = Column(String(36))
rep_repairs_bugs_1bugs_idb = Column(String(36))
class RepRepairsCstm(Base):
__tablename__ = 'rep_repairs_cstm'
id_c = Column(CHAR(36), primary_key=True)
user_id_c = Column(CHAR(36))
user_id1_c = Column(CHAR(36))
date_of_completion_c = Column(Date)
cat_work_c = Column(String(100), server_default=text("'1'"))
account_id_c = Column(CHAR(36))
address_c = Column(String(255))
check_ovm_c = Column(TINYINT(1), server_default=text("'0'"))
photo_one_c = Column(String(255))
photo_two_c = Column(String(255))
photo_three_c = Column(String(255))
photo_four_c = Column(String(255))
photo_five_c = Column(String(255))
photo_six_c = Column(String(255))
contacts_c = Column(String(255))
time_c = Column(String(255))
user_id2_c = Column(CHAR(36))
status_c = Column(String(100), server_default=text("'one'"))
comment_c = Column(Text)
new_cat_work_c = Column(Text)
class RepRepairsNotes1C(Base):
__tablename__ = 'rep_repairs_notes_1_c'
id = Column(String(36), primary_key=True)
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
rep_repairs_notes_1rep_repairs_ida = Column(String(36), index=True)
rep_repairs_notes_1notes_idb = Column(String(36), index=True)
class RepTechnicalConnection(Base):
__tablename__ = 'rep_technical_connections'
id = Column(CHAR(36), primary_key=True)
name = Column(String(255))
date_entered = Column(DateTime)
date_modified = Column(DateTime)
modified_user_id = Column(CHAR(36))
created_by = Column(CHAR(36))
description = Column(Text)
deleted = Column(TINYINT(1), server_default=text("'0'"))
assigned_user_id = Column(CHAR(36))
date_work = Column(Date)
type = Column(String(100))
class RepTechnicalConnectionsAudit(Base):
__tablename__ = 'rep_technical_connections_audit'
id = Column(CHAR(36), primary_key=True)
parent_id = Column(CHAR(36), nullable=False, index=True)
date_created = Column(DateTime)
created_by = Column(String(36))
field_name = Column(String(100))
data_type = Column(String(100))
before_value_string = Column(String(255))
after_value_string = Column(String(255))
before_value_text = Column(Text)
after_value_text = Column(Text)
class Role(Base):
__tablename__ = 'roles'
__table_args__ = (
Index('idx_role_id_del', 'id', 'deleted'),
)
id = Column(CHAR(36), primary_key=True)
date_entered = Column(DateTime)
date_modified = Column(DateTime)
modified_user_id = Column(CHAR(36))
created_by = Column(CHAR(36))
name = Column(String(150))
description = Column(Text)
modules = Column(Text)
deleted = Column(TINYINT(1))
class RolesModule(Base):
__tablename__ = 'roles_modules'
id = Column(String(36), primary_key=True)
role_id = Column(String(36), index=True)
module_id = Column(String(36), index=True)
allow = Column(TINYINT(1), server_default=text("'0'"))
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
class RolesUser(Base):
__tablename__ = 'roles_users'
id = Column(String(36), primary_key=True)
role_id = Column(String(36), index=True)
user_id = Column(String(36), index=True)
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
class SavedSearch(Base):
__tablename__ = 'saved_search'
__table_args__ = (
Index('idx_desc', 'name', 'deleted'),
)
id = Column(CHAR(36), primary_key=True)
name = Column(String(150))
search_module = Column(String(150))
deleted = Column(TINYINT(1))
date_entered = Column(DateTime)
date_modified = Column(DateTime)
assigned_user_id = Column(CHAR(36))
contents = Column(Text)
description = Column(Text)
class Scheduler(Base):
__tablename__ = 'schedulers'
__table_args__ = (
Index('idx_schedule', 'date_time_start', 'deleted'),
)
id = Column(String(36), primary_key=True)
deleted = Column(TINYINT(1), server_default=text("'0'"))
date_entered = Column(DateTime)
date_modified = Column(DateTime)
created_by = Column(CHAR(36))
modified_user_id = Column(CHAR(36))
name = Column(String(255))
job = Column(String(255))
date_time_start = Column(DateTime)
date_time_end = Column(DateTime)
job_interval = Column(String(100))
time_from = Column(Time)
time_to = Column(Time)
last_run = Column(DateTime)
status = Column(String(100))
catch_up = Column(TINYINT(1), server_default=text("'1'"))
class Securitygroup(Base):
__tablename__ = 'securitygroups'
id = Column(CHAR(36), primary_key=True)
name = Column(String(255))
date_entered = Column(DateTime)
date_modified = Column(DateTime)
modified_user_id = Column(CHAR(36))
created_by = Column(CHAR(36))
description = Column(Text)
deleted = Column(TINYINT(1), server_default=text("'0'"))
assigned_user_id = Column(CHAR(36))
noninheritable = Column(TINYINT(1))
class SecuritygroupsAclRole(Base):
__tablename__ = 'securitygroups_acl_roles'
id = Column(CHAR(36), primary_key=True)
securitygroup_id = Column(CHAR(36))
role_id = Column(CHAR(36))
date_modified = Column(DateTime)
deleted = Column(TINYINT(1), server_default=text("'0'"))
class SecuritygroupsAudit(Base):
__tablename__ = 'securitygroups_audit'
id = Column(CHAR(36), primary_key=True)
parent_id = Column(CHAR(36), nullable=False, index=True)
date_created = Column(DateTime)
created_by = Column(String(36))
field_name = Column(String(100))
data_type = Column(String(100))
before_value_string = Column(String(255))
after_value_string = Column(String(255))
before_value_text = | |
format_version,
task_manager: aiotools.BackgroundTaskManager,
pool: concurrent.futures.ThreadPoolExecutor,
):
super().__init__(batch_id, user, gsa_key, job_spec, format_version, task_manager, pool)
assert job_spec['process']['type'] == 'jvm'
input_files = job_spec.get('input_files')
output_files = job_spec.get('output_files')
if input_files or output_files:
raise Exception("i/o not supported")
for envvar in self.env:
assert envvar['name'] not in {
'HAIL_DEPLOY_CONFIG_FILE',
'HAIL_TOKENS_FILE',
'HAIL_SSL_CONFIG_DIR',
'HAIL_GSA_KEY_FILE',
'HAIL_WORKER_SCRATCH_DIR',
}, envvar
self.env.append(
{'name': 'HAIL_DEPLOY_CONFIG_FILE', 'value': f'{self.scratch}/secrets/deploy-config/deploy-config.json'}
)
self.env.append({'name': 'HAIL_TOKENS_FILE', 'value': f'{self.scratch}/secrets/user-tokens/tokens.json'})
self.env.append({'name': 'HAIL_SSL_CONFIG_DIR', 'value': f'{self.scratch}/secrets/ssl-config'})
self.env.append({'name': 'HAIL_GSA_KEY_FILE', 'value': f'{self.scratch}/secrets/gsa-key/key.json'})
self.env.append({'name': 'HAIL_WORKER_SCRATCH_DIR', 'value': self.scratch})
# main container
self.main_spec = {
'command': job_spec['process']['command'], # ['is.hail.backend.service.Worker', $root, $i]
'name': 'main',
'env': self.env,
'cpu': self.cpu_in_mcpu,
'memory': self.memory_in_bytes,
}
self.heap_size = self.memory_in_bytes - self.stack_size
user_command_string = job_spec['process']['command']
assert len(user_command_string) >= 3, user_command_string
self.revision = user_command_string[1]
self.jar_url = user_command_string[2]
classpath = f'{find_spark_home()}/jars/*:/hail-jars/{self.revision}.jar:/log4j.properties'
self.command_string = [
'java',
'-classpath',
classpath,
f'-Xmx{self.heap_size}',
f'-Xss{self.stack_size}',
*user_command_string,
]
self.process = None
self.deleted = False
self.timings = Timings(lambda: self.deleted)
self.state = 'pending'
self.logbuffer = bytearray()
def step(self, name):
return self.timings.step(name)
async def pipe_to_log(self, strm: asyncio.StreamReader):
while not strm.at_eof():
self.logbuffer.extend(await strm.readline())
async def run(self, worker):
async with worker.cpu_sem(self.cpu_in_mcpu):
self.start_time = time_msecs()
try:
self.task_manager.ensure_future(worker.post_job_started(self))
log.info(f'{self}: initializing')
self.state = 'initializing'
os.makedirs(f'{self.scratch}/')
await check_shell_output(f'xfs_quota -x -c "project -s -p {self.scratch} {self.project_id}" /host/')
await check_shell_output(
f'xfs_quota -x -c "limit -p bsoft={self.data_disk_storage_in_gib} bhard={self.data_disk_storage_in_gib} {self.project_id}" /host/'
)
if self.secrets:
for secret in self.secrets:
populate_secret_host_path(self.secret_host_path(secret), secret['data'])
populate_secret_host_path(self.gsa_key_file_path(), self.gsa_key)
self.state = 'running'
log.info(f'{self}: downloading JAR')
with self.step('downloading_jar'):
async with worker.jar_download_locks[self.revision]:
local_jar_location = f'/hail-jars/{self.revision}.jar'
if not os.path.isfile(local_jar_location):
user_fs = RouterAsyncFS(
'file',
[
LocalAsyncFS(worker.pool),
aiogoogle.GoogleStorageAsyncFS(
credentials=aiogoogle.GoogleCredentials.from_file('/worker-key.json')
),
],
)
async with await user_fs.open(self.jar_url) as jar_data:
await user_fs.makedirs('/hail-jars/', exist_ok=True)
async with await user_fs.create(local_jar_location) as local_file:
while True:
b = await jar_data.read(256 * 1024)
if not b:
break
written = await local_file.write(b)
assert written == len(b)
log.info(f'{self}: running jvm process')
with self.step('running'):
self.process = await asyncio.create_subprocess_exec(
*self.command_string,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env={envvar['name']: envvar['value'] for envvar in self.env},
)
await asyncio.gather(self.pipe_to_log(self.process.stdout), self.pipe_to_log(self.process.stderr))
await self.process.wait()
log.info(f'finished {self} with return code {self.process.returncode}')
await worker.file_store.write_log_file(
self.format_version, self.batch_id, self.job_id, self.attempt_id, 'main', self.logbuffer.decode()
)
if self.process.returncode == 0:
self.state = 'succeeded'
else:
self.state = 'failed'
log.info(f'{self} main: {self.state}')
except asyncio.CancelledError:
raise
except Exception:
log.exception(f'while running {self}')
self.state = 'error'
self.error = traceback.format_exc()
await self.cleanup()
await self.cleanup()
async def cleanup(self):
self.end_time = time_msecs()
if not self.deleted:
log.info(f'{self}: marking complete')
self.task_manager.ensure_future(worker.post_job_complete(self))
log.info(f'{self}: cleaning up')
try:
await check_shell(f'xfs_quota -x -c "limit -p bsoft=0 bhard=0 {self.project_id}" /host')
await blocking_to_async(self.pool, shutil.rmtree, self.scratch, ignore_errors=True)
except asyncio.CancelledError:
raise
except Exception:
log.exception('while deleting volumes')
async def get_log(self):
return {'main': self.logbuffer.decode()}
async def delete(self):
log.info(f'deleting {self}')
self.deleted = True
if self.process is not None and self.process.returncode is None:
self.process.kill()
# {
# version: int,
# worker: str,
# batch_id: int,
# job_id: int,
# attempt_id: int,
# user: str,
# state: str, (pending, initializing, running, succeeded, error, failed)
# format_version: int
# error: str, (optional)
# container_statuses: [Container.status],
# start_time: int,
# end_time: int,
# resources: list of dict, {name: str, quantity: int}
# }
async def status(self):
status = await super().status()
status['container_statuses'] = dict()
status['container_statuses']['main'] = {'name': 'main', 'state': self.state, 'timing': self.timings.to_dict()}
if self.process is not None and self.process.returncode is not None:
status['container_statuses']['main']['exit_code'] = self.process.returncode
return status
def __str__(self):
return f'job {self.id}'
class ImageData:
def __init__(self):
self.ref_count = 0
self.time_created = time_msecs()
self.last_accessed = time_msecs()
self.lock = asyncio.Lock()
def __add__(self, other):
self.ref_count += other
self.last_accessed = time_msecs()
return self
def __sub__(self, other):
self.ref_count -= other
assert self.ref_count >= 0
self.last_accessed = time_msecs()
return self
def __str__(self):
return (
f'ImageData('
f'ref_count={self.ref_count}, '
f'time_created={time_msecs_str(self.time_created)}, '
f'last_accessed={time_msecs_str(self.last_accessed)}'
f')'
)
class Worker:
def __init__(self, client_session: httpx.ClientSession):
self.active = False
self.cores_mcpu = CORES * 1000
self.last_updated = time_msecs()
self.cpu_sem = FIFOWeightedSemaphore(self.cores_mcpu)
self.data_disk_space_remaining = Box(UNRESERVED_WORKER_DATA_DISK_SIZE_GB)
self.pool = concurrent.futures.ThreadPoolExecutor()
self.jobs: Dict[Tuple[int, int], Job] = {}
self.stop_event = asyncio.Event()
self.task_manager = aiotools.BackgroundTaskManager()
self.jar_download_locks: Dict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
self.client_session = client_session
self.image_data: Dict[str, ImageData] = defaultdict(ImageData)
self.image_data[BATCH_WORKER_IMAGE_ID] += 1
# filled in during activation
self.file_store = None
self.headers = None
self.compute_client = None
async def shutdown(self):
log.info('Worker.shutdown')
try:
self.task_manager.shutdown()
log.info('shutdown task manager')
finally:
try:
if self.compute_client:
await self.compute_client.close()
log.info('closed compute client')
finally:
try:
if self.file_store:
await self.file_store.close()
log.info('closed file store')
finally:
await self.client_session.close()
log.info('closed client session')
async def run_job(self, job):
try:
await job.run(self)
except asyncio.CancelledError:
raise
except Exception as e:
if not user_error(e):
log.exception(f'while running {job}, ignoring')
async def create_job_1(self, request):
body = await request.json()
batch_id = body['batch_id']
job_id = body['job_id']
format_version = BatchFormatVersion(body['format_version'])
if format_version.has_full_spec_in_gcs():
token = body['token']
start_job_id = body['start_job_id']
addtl_spec = body['job_spec']
job_spec = await self.file_store.read_spec_file(batch_id, token, start_job_id, job_id)
job_spec = json.loads(job_spec)
job_spec['attempt_id'] = addtl_spec['attempt_id']
job_spec['secrets'] = addtl_spec['secrets']
addtl_env = addtl_spec.get('env')
if addtl_env:
env = job_spec.get('env')
if not env:
env = []
job_spec['env'] = env
env.extend(addtl_env)
else:
job_spec = body['job_spec']
assert job_spec['job_id'] == job_id
id = (batch_id, job_id)
# already running
if id in self.jobs:
return web.HTTPForbidden()
# check worker hasn't started shutting down
if not self.active:
return web.HTTPServiceUnavailable()
job = Job.create(
batch_id,
body['user'],
body['gsa_key'],
job_spec,
format_version,
self.task_manager,
self.pool,
self.client_session,
)
log.info(f'created {job}, adding to jobs')
self.jobs[job.id] = job
self.task_manager.ensure_future(self.run_job(job))
return web.Response()
async def create_job(self, request):
return await asyncio.shield(self.create_job_1(request))
async def get_job_log(self, request):
batch_id = int(request.match_info['batch_id'])
job_id = int(request.match_info['job_id'])
id = (batch_id, job_id)
job = self.jobs.get(id)
if not job:
raise web.HTTPNotFound()
return web.json_response(await job.get_log())
async def get_job_status(self, request):
batch_id = int(request.match_info['batch_id'])
job_id = int(request.match_info['job_id'])
id = (batch_id, job_id)
job = self.jobs.get(id)
if not job:
raise web.HTTPNotFound()
return web.json_response(await job.status())
async def delete_job_1(self, request):
batch_id = int(request.match_info['batch_id'])
job_id = int(request.match_info['job_id'])
id = (batch_id, job_id)
log.info(f'deleting job {id}, removing from jobs')
job = self.jobs.pop(id, None)
if job is None:
raise web.HTTPNotFound()
self.last_updated = time_msecs()
self.task_manager.ensure_future(job.delete())
return web.Response()
async def delete_job(self, request):
return await asyncio.shield(self.delete_job_1(request))
async def healthcheck(self, request): # pylint: disable=unused-argument
body = {'name': NAME}
return web.json_response(body)
async def run(self):
app = web.Application(client_max_size=HTTP_CLIENT_MAX_SIZE)
app.add_routes(
[
web.post('/api/v1alpha/kill', self.kill),
web.post('/api/v1alpha/batches/jobs/create', self.create_job),
web.delete('/api/v1alpha/batches/{batch_id}/jobs/{job_id}/delete', self.delete_job),
web.get('/api/v1alpha/batches/{batch_id}/jobs/{job_id}/log', self.get_job_log),
web.get('/api/v1alpha/batches/{batch_id}/jobs/{job_id}/status', self.get_job_status),
web.get('/healthcheck', self.healthcheck),
]
)
try:
await asyncio.wait_for(self.activate(), MAX_IDLE_TIME_MSECS / 1000)
except asyncio.TimeoutError:
log.exception(f'could not activate after trying for {MAX_IDLE_TIME_MSECS} ms, exiting')
return
app_runner = web.AppRunner(app)
await app_runner.setup()
site = web.TCPSite(app_runner, '0.0.0.0', 5000)
await site.start()
self.task_manager.ensure_future(periodically_call(60, self.cleanup_old_images))
try:
while True:
try:
await asyncio.wait_for(self.stop_event.wait(), 15)
log.info('received stop event')
break
except asyncio.TimeoutError:
idle_duration = time_msecs() - self.last_updated
if not self.jobs and idle_duration >= MAX_IDLE_TIME_MSECS:
log.info(f'idle {idle_duration} ms, exiting')
break
log.info(
f'n_jobs {len(self.jobs)} free_cores {self.cpu_sem.value / 1000} idle {idle_duration} '
f'free worker data disk storage {self.data_disk_space_remaining.value}Gi'
)
finally:
self.active = False
log.info('shutting down')
await site.stop()
log.info('stopped site')
await app_runner.cleanup()
log.info('cleaned up app runner')
await self.deactivate()
log.info('deactivated')
async def deactivate(self):
# Don't retry. If it doesn't go through, the driver
# monitoring loops will recover. If the driver is
# gone (e.g. testing a PR), this would go into an
# infinite loop and the instance won't be deleted.
await self.client_session.post(
deploy_config.url('batch-driver', '/api/v1alpha/instances/deactivate'), headers=self.headers
)
async def kill_1(self, request): # pylint: disable=unused-argument
log.info('killed')
self.stop_event.set()
async def kill(self, request):
return await asyncio.shield(self.kill_1(request))
async def post_job_complete_1(self, job):
run_duration = job.end_time - job.start_time
full_status = await retry_all_errors(f'error while getting status for {job}')(job.status)
if job.format_version.has_full_status_in_gcs():
await retry_all_errors(f'error while writing status file to gcs for {job}')(
self.file_store.write_status_file, job.batch_id, job.job_id, job.attempt_id, json.dumps(full_status)
)
db_status = job.format_version.db_status(full_status)
status = {
'version': full_status['version'],
'batch_id': full_status['batch_id'],
'job_id': full_status['job_id'],
'attempt_id': full_status['attempt_id'],
'state': full_status['state'],
'start_time': full_status['start_time'],
'end_time': full_status['end_time'],
'resources': full_status['resources'],
'status': db_status,
}
body = {'status': status}
start_time = time_msecs()
delay_secs = 0.1
while True:
try:
await self.client_session.post(
deploy_config.url('batch-driver', '/api/v1alpha/instances/job_complete'),
json=body,
headers=self.headers,
)
return
except asyncio.CancelledError: # pylint: disable=try-except-raise
raise
except Exception as e:
if isinstance(e, aiohttp.ClientResponseError) and e.status == 404: # pylint: disable=no-member
raise
log.warning(f'failed to mark {job} complete, retrying', exc_info=True)
# unlist job after 3m or half the run duration
now = time_msecs()
elapsed = now - start_time
if job.id in self.jobs and elapsed > 180 * 1000 and elapsed > run_duration / 2:
log.info(f'too much time elapsed marking {job} complete, removing from jobs, will keep retrying')
del self.jobs[job.id]
self.last_updated = time_msecs()
await asyncio.sleep(delay_secs * random.uniform(0.7, 1.3))
# exponentially back off, up to (expected) max of 2m
delay_secs = min(delay_secs * 2, 2 * 60.0)
async def post_job_complete(self, job):
try:
await self.post_job_complete_1(job)
except asyncio.CancelledError:
raise
| |
for _ in ranges]
# varlist={}
for i, rpart in enumerate(ranges):
varlist = rangedvars[i]
# varlist.clear()
for (varname, partlist) in arr_parts.items():
for (vpart, data) in partlist:
if not shardview.overlaps(rpart, vpart): # skip
continue
# times.append(timer())
# slindex = shardview.to_base_slice(shardview.mapsv(vpart,rpart))
tmp = shardview.mapsv(vpart, rpart)
# times.append(timer())
# slindex = shardview.to_base_slice(tmp)
# times.append(timer())
# varlist[varname] = data[slindex]
varlist[varname] = shardview.get_base_slice(tmp, data)
# times.append(timer())
# if not shardview.is_empty(rpart):
# func( **varlist, **othervars )
# times.append(timer())
#######
# ranges = [ (subspace, {}) ]
# for (varname, partlist) in arr_parts.items():
# i=0;
# while i<len(partlist):
# vpart, data = partlist[i]
# i+=1
# j=0
# while j<len(ranges):
# rpart,varlist = ranges[j]
# if not shardview.overlaps(rpart,vpart): # skip
# j+=1
# continue
# if shardview.is_compat(rpart,vpart): # matches range
# varlist[varname] = data
# break
# # does not match; split the ranges into parts, add to lists
# rparts, vparts = shardview.get_range_splits(rpart,vpart)
# if len(rparts)>1:
# #ranges[j] = ( rparts[0], { v: d[shardview.to_base_slice(shardview.mapslice(rpart,shardview.to_slice(rparts[0])))] for (v,d) in varlist.items() } )
# #ranges[j] = ( rparts[0], { v: d[shardview.to_base_slice(shardview.mapsv(rpart,rparts[0]))] for (v,d) in varlist.items() } )
# slindex = shardview.to_base_slice(shardview.mapsv(rpart,rparts[0]))
# ranges[j] = ( rparts[0], { v: d[slindex] for (v,d) in varlist.items() } )
# for r in rparts[1:]:
# #ranges.append( (r, {v: d[shardview.to_base_slice(shardview.mapslice(rpart,shardview.to_slice(r)))] for (v,d) in varlist.items() } ) )
# #ranges.append( (r, {v: d[shardview.to_base_slice(shardview.mapsv(rpart,r))] for (v,d) in varlist.items() } ) )
# slindex = shardview.to_base_slice(shardview.mapsv(rpart,r))
# ranges.append( (r, {v: d[slindex] for (v,d) in varlist.items() } ) )
# if len(vparts)>1:
# for r in vparts:
# #partlist.append( (r, data[shardview.to_base_slice(shardview.mapslice(vpart,shardview.to_slice(r)))]) )
# partlist.append( (r, data[shardview.to_base_slice(shardview.mapsv(vpart,r))]) )
# break
# # if we get here, should continue with same j value (repeat with updated ranges)
times.append(timer())
if len(ranges) > 1:
dprint(2, "Ranges:", len(ranges))
# execute function in each range
# for (r,arrvars) in ranges:
for i, r in enumerate(ranges):
arrvars = rangedvars[i]
if not shardview.is_empty(r):
for k, v in arrvars.items():
dprint(4, "inputs:", k, v, type(v))
for k, v in othervars.items():
dprint(4, "others:", k, v, type(v))
func(**arrvars, **othervars)
for k, v in arrvars.items():
dprint(4, "results:", k, v, type(v))
times.append(timer())
# delete arrays no longer needed
[self.destroy_array(g) for g in delete_gids]
times.append(timer())
if not USE_ZMQ and USE_MPI:
ramba_queue.wait_sends()
tnow = timer()
times.append(tnow)
self.deferred_ops_time += tnow - times[0]
self.deferred_ops_count += 1
if ntiming >= 1 and self.worker_num == timing_debug_worker:
times = [
int((times[i] - times[i - 1]) * 1000000) / 1000
for i in range(1, len(times))
]
tprint(
1,
"Deferred execution",
(tnow - self.tlast) * 1000,
times,
int(overlap_time * 1000000) / 1000,
int(getview_time * 1000000) / 1000,
int(arrview_time * 1000000) / 1000,
int(copy_time * 1000000) / 1000,
)
tprint(2, code)
self.tlast = tnow
def nop(self):
return
def seed(self, x):
np.random.seed(x + self.worker_num)
def get_comm_stats(self):
return [x.get_stats() for x in self.comm_queues]
def reset_def_ops_stats(self):
self.deferred_ops_time = 0
self.deferred_ops_count = 0
def get_def_ops_stats(self):
return (self.deferred_ops_count, self.deferred_ops_time)
def reset_compile_stats(self):
if numba.version_info.short >= (0, 53):
self.compile_recorder.buffer = []
def get_compile_stats(self):
if numba.version_info.short >= (0, 53):
return rec_buf_summary(self.compile_recorder.buffer)
else:
return 0
def rpc_serve(self, rvq):
# z = numa.set_affinity(self.worker_num, numa_zones)
print_stuff = timing > 2 and self.worker_num == 0
self.up_rvq = rvq
if self.is_aggregator:
if self.my_rvq is None:
self.my_rvq = ramba_queue.Queue(hint_ip=hint_ip, tag=2)
msg = ramba_queue.pickle(("RPC", "set_up_rvq", None, [self.my_rvq], {}))
[self.control_queues[i].put(msg, raw=True) for i in self.children]
t0 = timer()
while True:
if self.is_aggregator:
msg = self.my_control_queue.get(raw=True, print_times=print_stuff)
rpctype, method, rvid, args, kwargs = ramba_queue.unpickle(msg)
if rpctype == "RPC":
[self.control_queues[i].put(msg, raw=True) for i in self.children]
else:
rpctype, method, rvid, args, kwargs = self.my_control_queue.get(
gfilter=lambda x: x[0] == "RPC" or x[0] == "RPC1",
print_times=print_stuff,
)
if method == "END":
break
t1 = timer()
try:
op = getattr(self, method)
retval = op(*args, **kwargs)
except:
traceback.print_exc()
rvq.put(("ERROR", self.worker_num, traceback.format_exc()))
break
t2 = timer()
if rvid is not None:
if rpctype == "RPC":
self.up_rvq.put((rvid + str(self.worker_num), retval))
else:
rvq.put((rvid + str(self.worker_num), retval))
t3 = timer()
if self.is_aggregator and rvid is not None and rpctype == "RPC":
for _ in self.children:
msg = self.my_rvq.get(raw=True)
self.up_rvq.put(msg, raw=True)
t4 = timer()
if print_stuff:
print(
"Command ",
method,
"get",
(t1 - t0) * 1000,
"exec",
(t2 - t1) * 1000,
"ret",
(t3 - t2) * 1000,
"fwd",
(t4 - t3) * 1000,
)
t0 = t4
def mgrid(self, out_gid, out_size, out_distribution):
divs = shardview.distribution_to_divisions(out_distribution)[self.worker_num]
dprint(2, "mgrid remote:", self.worker_num, divs)
if np.all(divs[0] <= divs[1]):
out_lnd = self.numpy_map[out_gid]
bcontainer = out_lnd.bcontainer[out_lnd.core_slice]
mslice = [
slice(divs[0][i + 1], divs[1][i + 1] + 1)
for i in range(divs.shape[1] - 1)
]
dprint(2, "mslice", mslice, bcontainer.shape)
bcontainer[:] = np.mgrid[mslice]
def load(self, gid, fname, ftype=None, **kwargs):
lnd = self.numpy_map[gid]
fldr = fileio.get_load_handler(fname, ftype)
fldr.read(fname, lnd.bcontainer, shardview.to_slice(lnd.subspace), **kwargs)
if not USE_MPI:
RemoteState = ray.remote(num_cpus=num_threads)(RemoteState)
# Wrappers to abstract away Ray method calls
ALL_NODES = -1
def _real_remote(nodeid, method, has_retval, args, kwargs):
if nodeid == ALL_NODES:
if USE_RAY_CALLS:
rargs = [ray.put(v) for v in args]
rkwargs = {k: ray.put(v) for k, v in kwargs.items()}
return [
getattr(remote_states[i], method).remote(*rargs, **rkwargs)
for i in range(num_workers)
]
rvid = str(uuid.uuid4()) if has_retval else None
if USE_ZMQ or not USE_BCAST:
msg = ramba_queue.pickle(("RPC", method, rvid, args, kwargs))
if ntiming >= 1:
print(
"control message size: ",
sum(
[
len(i.raw())
if isinstance(i, pickle.PickleBuffer)
else len(i)
for i in msg
]
)
if isinstance(msg, list)
else len(msg),
)
else:
msg = ("RPC", method, rvid, args, kwargs)
if USE_MPI and USE_BCAST and not USE_ZMQ:
ramba_queue.bcast(msg)
elif USE_ZMQ and USE_BCAST:
[control_queues[i].put(msg, raw=True) for i in aggregators]
else:
[control_queues[i].put(msg, raw=True) for i in range(num_workers)]
return [rvid + str(i) for i in range(num_workers)] if has_retval else None
if USE_RAY_CALLS:
rop = getattr(remote_states[nodeid], method)
return rop.remote(*args, **kwargs)
rvid = str(uuid.uuid4()) if has_retval else None
control_queues[nodeid].put(("RPC1", method, rvid, args, kwargs))
return rvid + str(nodeid) if has_retval else None
def get_results(refs):
if USE_RAY_CALLS:
return ray.get(refs)
if isinstance(refs, list):
rv = [get_results(v) for v in refs]
else:
rv = retval_queue.get(gfilter=lambda x: x[0] == refs or x[0] == "ERROR")
if rv[0] == "ERROR":
raise Exception("Exception in Remote Worker " + str(rv[1]) + "\n" + rv[2])
rv = rv[1]
return rv
def remote_exec(nodeid, method, *args, **kwargs):
_real_remote(nodeid, method, False, args, kwargs)
def remote_async_call(nodeid, method, *args, **kwargs):
return _real_remote(nodeid, method, True, args, kwargs)
def remote_call(nodeid, method, *args, **kwargs):
return get_results(_real_remote(nodeid, method, True, args, kwargs))
def remote_exec_all(method, *args, **kwargs):
# [ _real_remote(i, method, False, args, kwargs) for i in range(num_workers) ]
_real_remote(ALL_NODES, method, False, args, kwargs)
# get_results(_real_remote(ALL_NODES, method, True, args, kwargs))
def remote_async_call_all(method, *args, **kwargs):
# return [ _real_remote(i, method, True, args, kwargs) for i in range(num_workers) ]
return _real_remote(ALL_NODES, method, True, args, kwargs)
def remote_call_all(method, *args, **kwargs):
# return get_results([ _real_remote(i, method, True, args, kwargs) for i in range(num_workers) ])
return get_results(_real_remote(ALL_NODES, method, True, args, kwargs))
if USE_RAY_CALLS:
def func_dumps(f):
return f
def func_loads(f):
return f
else:
func_dumps = cloudpickle.dumps
func_loads = cloudpickle.loads
# *******************************
# ** Initialize Remote Workers **
# *******************************
import atexit
if USE_MPI:
# MPI setup
# Queue tags: 0 = general comm, 1 = control, 2 = reply
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
if rank == num_workers: # driver
# do this stuff only once
def do_init(done=[]):
if len(done) > 0:
print("HERE -- already done")
return None
done += [1]
rv_q = ramba_queue.Queue(tag=2)
comm_q = comm.allgather(0)[:-1] # ignore our own invalid one
con_q = comm.allgather(rv_q)
aggr = get_aggregators(comm_q)
return rv_q, comm_q, con_q, aggr
x = do_init()
if x is not None:
retval_queue, comm_queues, control_queues, aggregators = x
atexit.register(remote_exec_all, "END")
else: # workers -- should never leave this section!
RS = RemoteState(rank, get_common_state())
con_q = RS.get_control_queue()
comm_q = RS.get_comm_queue()
comm_queues = comm.allgather(comm_q)[:-1] # ignore invalid one for controller
control_queues = comm.allgather(con_q)
rv_q = control_queues[num_workers]
RS.set_comm_queues(comm_queues, control_queues)
RS.rpc_serve(rv_q)
sys.exit()
else: # Ray setup
# Start remote Actors, but only if this was the process that initialized Ray;
# This avoids starting the remote workers every time ramba.py is imported
if ray_first_init:
dprint(1, "Constructing RemoteState actors")
from ray.util.placement_group import placement_group
res = [{"CPU": num_threads}] * num_workers
pg = placement_group(res, strategy="SPREAD")
remote_states = [
RemoteState.options(placement_group=pg).remote(x, get_common_state())
for x in range(num_workers)
]
control_queues = ray.get([x.get_control_queue.remote() for | |
self.statements[statement.feature].val = statement.val
if updateOperators:
self.statements[statement.feature].op = statement.op
else:
prevStatType = 'binary' if self.statements[statement.feature].binary else 'non-binary'
newStatType = 'binary' if statement.binary else 'non-binary'
raise ValueError(f'Cannot update {prevStatType} statement with new {newStatType} statement.')
class TransparentRuleClassifier(_BaseClassifier):
""" Used on the higher level data generation class :class:`teex.featureImportance.data.SenecaFI`
(**use that and get it from there preferably**).
Transparent, rule-based classifier with decision rules as explanations. For each prediction, the associated
ground truth explanation is available with the :func:`explain` method. Follows the sklearn API. Presented in
[Evaluating local explanation methods on ground truth, <NAME>, 2021]. """
def __init__(self, **kwargs):
super().__init__()
self.model = DecisionTreeClassifier(**kwargs)
# dict. for each tree node, contains its learned condition as a "Statement" (None if node is a leaf)
self._nodeStatements = None
def fit(self, data, target, featureNames=None):
""" Fits the classifier and automatically parses the learned tree structure into statements.
:param data: (array-like) of shape (n_samples, n_features) The training input samples. Internally, it will be
converted to dtype=np.float32.
:param target: (array-like of shape (n_samples,) or (n_samples, n_outputs)) The target values (class labels) as
integers or strings.
:param featureNames: (array-like) names of the features in the data. If not specified, they will be created.
Stored in ``self.featureNames``.
"""
self.model.fit(data, target)
if featureNames is None:
self.featureNames = [str(num) for num in range(data.shape[1])]
else:
self.featureNames = featureNames
self._parse_tree_structure()
def predict(self, obs):
""" Predicts the class for each observation.
:param obs: (array-like) of n observations with m features and shape (n, m)
:return np.ndarray: array of n predicted labels
"""
return self.model.predict(obs)
def predict_proba(self, obs):
""" Predicts probability that each observation belongs to each of the c classes.
:param obs: array of n observations with m features and shape (n, m)
:return np.ndarray: array of n probability tuples of length c
"""
return self.model.predict_proba(obs)
def explain(self, obs):
""" Explain observations' predictions with decision rules.
:param obs: array of n observations with m features and shape (n, m)
:return: list with n :class:`DecisionRule` objects """
nodeIndicators = self.model.decision_path(obs) # id's of the nodes for which each observation passes through
rules = []
# for each sample, retrieve its path and navigate it, looking at the precomputed decision splits
for sampleId in range(len(obs)):
nodePath = nodeIndicators.indices[nodeIndicators.indptr[sampleId]:nodeIndicators.indptr[sampleId + 1]]
rule = DecisionRule()
for nodeId in nodePath:
# node is not a leaf if None
if self._nodeStatements[nodeId] is not None:
feature = self._nodeStatements[nodeId].feature
threshold = self._nodeStatements[nodeId].val
statement = Statement(self.featureNames[feature], lowOp='<', upperOp='<=')
# define bounds. Remember that the tree splits are of the form: feature '<=' val
if obs[sampleId][feature] <= threshold:
statement.upperB = round(threshold, 3)
else:
statement.lowB = round(threshold, 3)
# we create binary statements and will update the bounds as we traverse the tree's decision
rule.upsert_statement(statement, updateOperators=False)
rule.set_result(Statement('Class', val=self.predict(obs[sampleId].reshape(1, -1))[0], op='='))
rules.append(rule)
return rules
def _parse_tree_structure(self):
""" Precomputes the learned tree splits and stores them as unary :code:`Statement` objects. """
nodeFeatures = self.model.tree_.feature
nodeThresholds = self.model.tree_.threshold
childrenRight = self.model.tree_.children_right
childrenLeft = self.model.tree_.children_left
self._nodeStatements = {nodeId: None for nodeId in range(self.model.tree_.node_count)}
# root node
nodeStack = [0]
while len(nodeStack) > 0:
nodeId = nodeStack.pop()
if childrenRight[nodeId] != childrenLeft[nodeId]:
# nodeId is a split node; add child nodes to the stack and parse its decision split into a statement
nodeStack.append(childrenRight[nodeId])
nodeStack.append(childrenLeft[nodeId])
# all split nodes check with the '<=' op
nodeStatement = Statement(nodeFeatures[nodeId], val=nodeThresholds[nodeId], op='<=')
self._nodeStatements[nodeId] = nodeStatement
class SenecaDR(_SyntheticDataset):
""" Generate synthetic binary classification data with ground truth decision rule explanations. The returned
decision rule g.t. explanations are instances of the :class:`DecisionRule` class.
Ground truth explanations are generated with the :class:`TransparentRuleClassifier` class. The method was presented
in [Evaluating local explanation methods on ground truth, <NAME>, 2021]. From this class one can also
obtain a trained transparent model (instance of :class:`TransparentRuleClassifier`).
When sliced, this object will return
- X (ndarray) of shape (nSamples, nFeatures) or (nFeatures). Generated data.
- y (ndarray) of shape (nSamples,) or int. Binary data labels.
- explanations (list) of :class:`DecisionRule` objects of length (nSamples) or :class:`DecisionRule` object.
Generated ground truth explanations.
:param int nSamples: number of samples to be generated.
:param int nFeatures: total number of features in the generated data.
:param featureNames: (array-like) names of the generated features. If not provided, a list with the generated
feature names will be returned by the function (necessary because the g.t. decision rules use them).
:param int randomState: random state seed. """
def __init__(self, nSamples: int = 1000, nFeatures: int = 3, featureNames=None, randomState: int = 888) -> None:
self.nSamples = nSamples
self.nFeatures = nFeatures
self.featureNames = _generate_feature_names(nFeatures) if featureNames is None else featureNames
self.randomState = randomState
self.X, self.y, self.exp, self.transparentModel = self._gen_dataset_seneca_dr()
def __getitem__(self, item):
if isinstance(item, (slice, int)):
return self.X[item], self.y[item], self.exp[item]
else:
raise TypeError('Invalid argument type.')
def __len__(self) -> int:
return len(self.y)
def _gen_dataset_seneca_dr(self):
""" g.t. explanations generated with the :class:`TransparentRuleClassifier` class. The
method was presented in [Evaluating local explanation methods on ground truth, <NAME>, 2021]. """
# generate explanations with rules and binarize
data, targets = make_classification(n_samples=self.nSamples, n_classes=2, n_features=self.nFeatures,
n_informative=self.nFeatures, n_redundant=0, n_repeated=0,
random_state=self.randomState)
classifier = TransparentRuleClassifier(random_state=self.randomState)
classifier.fit(data, targets, featureNames=self.featureNames)
explanations = classifier.explain(data)
return data, targets, explanations, classifier
# Utils for data manipulation:
def rule_to_feature_importance(rules, allFeatures) -> np.ndarray:
""" Converts one or more :class:`DecisionRule` objects to feature importance vector/s. For each
feature in *allFeatures*, the feature importance representation contains a 1 if there is a
:class:'Statement' with that particular feature in the decision rule and 0 otherwise.
:param rules: (:class:`DecisionRule` or (1, r) array-like of :class:`DecisionRule`) Rule/s
to convert to feature importance vectors.
:param allFeatures: (array-like of str) List with m features (same as the rule features) whose order the returned
array will follow. The features must match the ones used in the decision rules.
:return: (binary ndarray of shape (n_features,) or shape (n_rules, n_features)). """
if isinstance(rules, (list, np.ndarray, tuple)):
res = []
for rule in rules:
res.append([1 if feature in rule else 0 for feature in allFeatures])
elif isinstance(rules, DecisionRule):
res = [1 if feature in rules else 0 for feature in allFeatures]
else:
raise ValueError('The rule is not a DecisionRule object nor array-like.')
return np.array(res).astype(np.float32)
def _induce_binary_statement(feature, operator, value):
if operator == '<' or operator == '<=':
s = Statement(feature, lowOp='<', upperOp=operator, upperB=float(value))
elif operator == '>' or operator == '>=':
op = '<' if operator == '>' else '<='
s = Statement(feature, upperOp='<', lowOp=op, lowB=float(value))
else:
raise ValueError('Operator for binary statement not valid.')
return s
def _generate_binary_statement(feature, op1, val1, op2, val2):
""" Generates binary statement from operators, a feature and values. """
if op1 == '>' or op1 == '>=':
lowOp = '<' if op1 == '>' else '<='
s = Statement(feature, lowOp=lowOp, lowB=float(val1), upperOp=op2, upperB=float(val2))
elif op2 == '>' or op2 == '>=':
lowOp = '<' if op2 == '>' else '<='
s = Statement(feature, lowOp=lowOp, lowB=float(val2), upperOp=op1, upperB=float(val1))
else:
raise ValueError('Operator for binary statement not valid.')
return s
def clean_binary_statement(bounds: list):
""" Parses binary statement edge cases from a list of operators and values. Checks if the edge cases
occur for any pair of operator and value. Does not fix errors with bounds != or =.
f > 3 & f > 4 TRANSFORMS INTO f > 4
f > 3 & f >= 4 TRANSFORMS INTO f >= 4
f < 3 & f < 4 TRANSFORMS INTO f < 3
f <= 3 & f < 4 TRANSFORMS INTO f <= 3
:param list bounds: list with bounds i.e. [(op, val), ..., (op, val)]
:return: op1, val1, op2, val2
"""
op1, val1 = '>', -np.inf
op2, val2 = '<', np.inf
for op, val in bounds:
if op == '>=' or op == '>':
if val > val1:
op1, val1 = op, val
elif op == '<=' or op == '<':
if val < val2:
op2, val2 = op, val
else:
raise ValueError('Invalid bound operator for binary statement.')
return op1, val1, op2, val2
def _get_statements_dict(strRule, statementType='binary') -> dict:
""" Returns a dictionary with Statements from a string. """
rules | |
ClientMethod: string
:param ClientMethod: The client method to presign for
:type Params: dict
:param Params: The parameters normally passed to\nClientMethod.
:type ExpiresIn: int
:param ExpiresIn: The number of seconds the presigned url is valid\nfor. By default it expires in an hour (3600 seconds)
:type HttpMethod: string
:param HttpMethod: The http method to use on the generated url. By\ndefault, the http method is whatever is used in the method\'s model.
"""
pass
def get_customer_gateway_associations(GlobalNetworkId=None, CustomerGatewayArns=None, MaxResults=None, NextToken=None):
"""
Gets the association information for customer gateways that are associated with devices and links in your global network.
See also: AWS API Documentation
Exceptions
:example: response = client.get_customer_gateway_associations(
GlobalNetworkId='string',
CustomerGatewayArns=[
'string',
],
MaxResults=123,
NextToken='string'
)
:type GlobalNetworkId: string
:param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n
:type CustomerGatewayArns: list
:param CustomerGatewayArns: One or more customer gateway Amazon Resource Names (ARNs). For more information, see Resources Defined by Amazon EC2 . The maximum is 10.\n\n(string) --\n\n
:type MaxResults: integer
:param MaxResults: The maximum number of results to return.
:type NextToken: string
:param NextToken: The token for the next page of results.
:rtype: dict
ReturnsResponse Syntax
{
'CustomerGatewayAssociations': [
{
'CustomerGatewayArn': 'string',
'GlobalNetworkId': 'string',
'DeviceId': 'string',
'LinkId': 'string',
'State': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED'
},
],
'NextToken': 'string'
}
Response Structure
(dict) --
CustomerGatewayAssociations (list) --
The customer gateway associations.
(dict) --
Describes the association between a customer gateway, a device, and a link.
CustomerGatewayArn (string) --
The Amazon Resource Name (ARN) of the customer gateway.
GlobalNetworkId (string) --
The ID of the global network.
DeviceId (string) --
The ID of the device.
LinkId (string) --
The ID of the link.
State (string) --
The association state.
NextToken (string) --
The token for the next page of results.
Exceptions
NetworkManager.Client.exceptions.ValidationException
NetworkManager.Client.exceptions.AccessDeniedException
NetworkManager.Client.exceptions.ResourceNotFoundException
NetworkManager.Client.exceptions.ConflictException
NetworkManager.Client.exceptions.ThrottlingException
NetworkManager.Client.exceptions.InternalServerException
:return: {
'CustomerGatewayAssociations': [
{
'CustomerGatewayArn': 'string',
'GlobalNetworkId': 'string',
'DeviceId': 'string',
'LinkId': 'string',
'State': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED'
},
],
'NextToken': 'string'
}
:returns:
NetworkManager.Client.exceptions.ValidationException
NetworkManager.Client.exceptions.AccessDeniedException
NetworkManager.Client.exceptions.ResourceNotFoundException
NetworkManager.Client.exceptions.ConflictException
NetworkManager.Client.exceptions.ThrottlingException
NetworkManager.Client.exceptions.InternalServerException
"""
pass
def get_devices(GlobalNetworkId=None, DeviceIds=None, SiteId=None, MaxResults=None, NextToken=None):
"""
Gets information about one or more of your devices in a global network.
See also: AWS API Documentation
Exceptions
:example: response = client.get_devices(
GlobalNetworkId='string',
DeviceIds=[
'string',
],
SiteId='string',
MaxResults=123,
NextToken='string'
)
:type GlobalNetworkId: string
:param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n
:type DeviceIds: list
:param DeviceIds: One or more device IDs. The maximum is 10.\n\n(string) --\n\n
:type SiteId: string
:param SiteId: The ID of the site.
:type MaxResults: integer
:param MaxResults: The maximum number of results to return.
:type NextToken: string
:param NextToken: The token for the next page of results.
:rtype: dict
ReturnsResponse Syntax
{
'Devices': [
{
'DeviceId': 'string',
'DeviceArn': 'string',
'GlobalNetworkId': 'string',
'Description': 'string',
'Type': 'string',
'Vendor': 'string',
'Model': 'string',
'SerialNumber': 'string',
'Location': {
'Address': 'string',
'Latitude': 'string',
'Longitude': 'string'
},
'SiteId': 'string',
'CreatedAt': datetime(2015, 1, 1),
'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING',
'Tags': [
{
'Key': 'string',
'Value': 'string'
},
]
},
],
'NextToken': 'string'
}
Response Structure
(dict) --
Devices (list) --
The devices.
(dict) --
Describes a device.
DeviceId (string) --
The ID of the device.
DeviceArn (string) --
The Amazon Resource Name (ARN) of the device.
GlobalNetworkId (string) --
The ID of the global network.
Description (string) --
The description of the device.
Type (string) --
The device type.
Vendor (string) --
The device vendor.
Model (string) --
The device model.
SerialNumber (string) --
The device serial number.
Location (dict) --
The site location.
Address (string) --
The physical address.
Latitude (string) --
The latitude.
Longitude (string) --
The longitude.
SiteId (string) --
The site ID.
CreatedAt (datetime) --
The date and time that the site was created.
State (string) --
The device state.
Tags (list) --
The tags for the device.
(dict) --
Describes a tag.
Key (string) --
The tag key.
Length Constraints: Maximum length of 128 characters.
Value (string) --
The tag value.
Length Constraints: Maximum length of 256 characters.
NextToken (string) --
The token for the next page of results.
Exceptions
NetworkManager.Client.exceptions.ValidationException
NetworkManager.Client.exceptions.AccessDeniedException
NetworkManager.Client.exceptions.ResourceNotFoundException
NetworkManager.Client.exceptions.ThrottlingException
NetworkManager.Client.exceptions.InternalServerException
:return: {
'Devices': [
{
'DeviceId': 'string',
'DeviceArn': 'string',
'GlobalNetworkId': 'string',
'Description': 'string',
'Type': 'string',
'Vendor': 'string',
'Model': 'string',
'SerialNumber': 'string',
'Location': {
'Address': 'string',
'Latitude': 'string',
'Longitude': 'string'
},
'SiteId': 'string',
'CreatedAt': datetime(2015, 1, 1),
'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING',
'Tags': [
{
'Key': 'string',
'Value': 'string'
},
]
},
],
'NextToken': 'string'
}
:returns:
NetworkManager.Client.exceptions.ValidationException
NetworkManager.Client.exceptions.AccessDeniedException
NetworkManager.Client.exceptions.ResourceNotFoundException
NetworkManager.Client.exceptions.ThrottlingException
NetworkManager.Client.exceptions.InternalServerException
"""
pass
def get_link_associations(GlobalNetworkId=None, DeviceId=None, LinkId=None, MaxResults=None, NextToken=None):
"""
Gets the link associations for a device or a link. Either the device ID or the link ID must be specified.
See also: AWS API Documentation
Exceptions
:example: response = client.get_link_associations(
GlobalNetworkId='string',
DeviceId='string',
LinkId='string',
MaxResults=123,
NextToken='string'
)
:type GlobalNetworkId: string
:param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n
:type DeviceId: string
:param DeviceId: The ID of the device.
:type LinkId: string
:param LinkId: The ID of the link.
:type MaxResults: integer
:param MaxResults: The maximum number of results to return.
:type NextToken: string
:param NextToken: The token for the next page of results.
:rtype: dict
ReturnsResponse Syntax
{
'LinkAssociations': [
{
'GlobalNetworkId': 'string',
'DeviceId': 'string',
'LinkId': 'string',
'LinkAssociationState': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED'
},
],
'NextToken': 'string'
}
Response Structure
(dict) --
LinkAssociations (list) --
The link associations.
(dict) --
Describes the association between a device and a link.
GlobalNetworkId (string) --
The ID of the global network.
DeviceId (string) --
The device ID for the link association.
LinkId (string) --
The ID of the link.
LinkAssociationState (string) --
The state of the association.
NextToken (string) --
The token for the next page of results.
Exceptions
NetworkManager.Client.exceptions.ValidationException
NetworkManager.Client.exceptions.AccessDeniedException
NetworkManager.Client.exceptions.ResourceNotFoundException
NetworkManager.Client.exceptions.ThrottlingException
NetworkManager.Client.exceptions.InternalServerException
:return: {
'LinkAssociations': [
{
'GlobalNetworkId': 'string',
'DeviceId': 'string',
'LinkId': 'string',
'LinkAssociationState': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED'
},
],
'NextToken': 'string'
}
:returns:
NetworkManager.Client.exceptions.ValidationException
NetworkManager.Client.exceptions.AccessDeniedException
NetworkManager.Client.exceptions.ResourceNotFoundException
NetworkManager.Client.exceptions.ThrottlingException
NetworkManager.Client.exceptions.InternalServerException
"""
pass
def get_links(GlobalNetworkId=None, LinkIds=None, SiteId=None, Type=None, Provider=None, MaxResults=None, NextToken=None):
"""
Gets information about one or more links in a specified global network.
If you specify the site ID, you cannot specify the type or provider in the same request. You can specify the type and provider in the same request.
See also: AWS API Documentation
Exceptions
:example: response = client.get_links(
GlobalNetworkId='string',
LinkIds=[
'string',
],
SiteId='string',
Type='string',
Provider='string',
MaxResults=123,
NextToken='string'
)
:type GlobalNetworkId: string
:param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n
:type LinkIds: list
:param LinkIds: One or more link IDs. The maximum is 10.\n\n(string) --\n\n
:type SiteId: string
:param SiteId: The ID of the site.
:type Type: string
:param Type: The link type.
:type Provider: string
:param Provider: The link provider.
:type MaxResults: integer
:param MaxResults: The maximum number of results to return.
:type NextToken: string
:param NextToken: The token for the next page of results.
:rtype: dict
ReturnsResponse Syntax
{
'Links': [
{
'LinkId': 'string',
'LinkArn': 'string',
'GlobalNetworkId': 'string',
'SiteId': 'string',
'Description': 'string',
'Type': 'string',
'Bandwidth': {
'UploadSpeed': 123,
'DownloadSpeed': 123
},
'Provider': 'string',
'CreatedAt': datetime(2015, 1, 1),
'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING',
'Tags': [
{
'Key': 'string',
'Value': 'string'
},
]
},
],
'NextToken': 'string'
}
Response Structure
(dict) --
Links (list) --
The links.
(dict) --
Describes a link.
LinkId (string) --
The ID of the link.
LinkArn (string) --
The Amazon Resource Name (ARN) of the link.
GlobalNetworkId (string) --
The ID of the global network.
SiteId (string) --
The ID of the site.
Description (string) --
The description of the link.
Type (string) --
The type of the link.
Bandwidth (dict) --
The bandwidth for the link.
UploadSpeed (integer) --
Upload speed in Mbps.
DownloadSpeed (integer) --
Download speed in Mbps.
Provider (string) --
The provider of the link.
CreatedAt (datetime) --
The date and time that the link was created.
State (string) --
The state of the link.
Tags (list) --
The tags for the link.
(dict) --
Describes a tag.
Key (string) --
The tag key.
Length Constraints: Maximum length of 128 characters.
Value (string) --
The tag value.
Length Constraints: Maximum length of 256 characters.
NextToken (string) --
The token for the next page of results.
Exceptions
NetworkManager.Client.exceptions.ValidationException
NetworkManager.Client.exceptions.AccessDeniedException
NetworkManager.Client.exceptions.ResourceNotFoundException
NetworkManager.Client.exceptions.ThrottlingException
NetworkManager.Client.exceptions.InternalServerException
:return: {
'Links': [
{
'LinkId': 'string',
'LinkArn': 'string',
'GlobalNetworkId': 'string',
'SiteId': 'string',
'Description': 'string',
'Type': 'string',
'Bandwidth': {
'UploadSpeed': 123,
'DownloadSpeed': 123
},
'Provider': 'string',
'CreatedAt': datetime(2015, 1, 1),
'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING',
'Tags': [
{
'Key': 'string',
'Value': 'string'
},
]
},
],
'NextToken': 'string'
}
:returns:
NetworkManager.Client.exceptions.ValidationException
NetworkManager.Client.exceptions.AccessDeniedException
NetworkManager.Client.exceptions.ResourceNotFoundException
NetworkManager.Client.exceptions.ThrottlingException
NetworkManager.Client.exceptions.InternalServerException
"""
pass
def get_paginator(operation_name=None):
"""
Create a paginator for an operation.
:type operation_name: string
:param operation_name: The operation name. This is the same name\nas the method name on the client. For example, if the\nmethod name is create_foo, and you\'d normally invoke the\noperation as client.create_foo(**kwargs), if the\ncreate_foo operation can be paginated, you can use the\ncall client.get_paginator('create_foo').
:rtype: L{botocore.paginate.Paginator}
ReturnsA paginator object.
"""
pass
def get_sites(GlobalNetworkId=None, SiteIds=None, MaxResults=None, NextToken=None):
"""
Gets information | |
#!/usr/bin/env python3
"""
Polyglot v2 node server Russound status and control via RNET protocol
Copyright (C) 2020 <NAME>
"""
try:
import polyinterface
except ImportError:
import pgc_interface as polyinterface
import sys
import time
import datetime
import requests
import threading
import socket
import math
import re
import russound_main
import node_funcs
from nodes import zone
from rnet_message import RNET_MSG_TYPE
LOGGER = polyinterface.LOGGER
@node_funcs.add_functions_as_methods(node_funcs.functions)
class Controller(polyinterface.Controller):
id = 'russound'
hint = [0,0,0,0]
def __init__(self, polyglot):
super(Controller, self).__init__(polyglot)
self.name = 'Russound'
self.address = 'rnet'
self.primary = self.address
self.configured = False
self.rnet = None
self.sock = None
self.mesg_thread = None
self.source_status = 0x00 # assume all sources are inactive
self.params = node_funcs.NSParameters([{
'name': 'IP Address',
'default': 'set me',
'isRequired': True,
'notice': 'IP Address of serial network interface must be set',
},
{
'name': 'Port',
'default': '0',
'isRequired': True,
'notice': 'Serial network interface port must be set',
},
{
'name': 'Network Protocol',
'default': 'UDP',
'isRequired': False,
'notice': '',
},
{
'name': 'Zone 1',
'default': 'Zone 1',
'isRequired': False,
'notice': '',
},
{
'name': 'Zone 2',
'default': 'Zone 2',
'isRequired': False,
'notice': '',
},
{
'name': 'Zone 3',
'default': 'Zone 3',
'isRequired': False,
'notice': '',
},
{
'name': 'Zone 4',
'default': 'Zone 4',
'isRequired': False,
'notice': '',
},
{
'name': 'Zone 5',
'default': 'Zone 5',
'isRequired': False,
'notice': '',
},
{
'name': 'Zone 6',
'default': 'Zone 6',
'isRequired': False,
'notice': '',
},
])
self.poly.onConfig(self.process_config)
# Process changes to customParameters
def process_config(self, config):
(valid, changed) = self.params.update_from_polyglot(config)
if changed and not valid:
LOGGER.debug('-- configuration not yet valid')
self.removeNoticesAll()
self.params.send_notices(self)
elif changed and valid:
LOGGER.debug('-- configuration is valid')
self.removeNoticesAll()
self.configured = True
# TODO: Run discovery/startup here?
elif valid:
LOGGER.debug('-- configuration not changed, but is valid')
# is this necessary
#self.configured = True
def start(self):
LOGGER.info('Starting node server')
self.set_logging_level()
self.check_params()
# Open a connection to the Russound
if self.configured:
if self.params.get('Network Protocol') == 'UDP':
self.rnet = russound_main.RNETConnection(self.params.get('IP Address'), self.params.get('Port'), True)
else:
self.rnet = russound_main.RNETConnection(self.params.get('IP Address'), self.params.get('Port'), False)
self.rnet.Connect()
self.discover()
if self.rnet.connected:
# Start a thread that listens for messages from the russound.
self.mesg_thread = threading.Thread(target=self.rnet.MessageLoop, args=(self.processCommand,))
self.mesg_thread.daemon = True
self.mesg_thread.start()
# Query each zone
self.rnet.get_info(0, 0x0407)
time.sleep(2)
self.rnet.get_info(1, 0x0407)
time.sleep(2)
self.rnet.get_info(2, 0x0407)
time.sleep(2)
self.rnet.get_info(3, 0x0407)
time.sleep(2)
self.rnet.get_info(4, 0x0407)
time.sleep(2)
self.rnet.get_info(5, 0x0407)
LOGGER.info('Node server started')
else:
LOGGER.info('Waiting for configuration to be complete')
def longPoll(self):
pass
def shortPoll(self):
pass
def query(self):
for node in self.nodes:
self.nodes[node].reportDrivers()
def discover(self, *args, **kwargs):
LOGGER.debug('in discover() - Setting up zones')
for z in range(1,7):
param = 'Zone ' + str(z)
node = zone.Zone(self, self.address, 'zone_' + str(z), self.params.get(param))
node.setRNET(self.rnet)
try:
old = self.poly.getNode('zone_' + str(z))
if old['name'] != self.params.get(param):
self.delNode('zone_' + str(z))
time.sleep(1) # give it time to remove from database
except:
LOGGER.warning('Failed to delete node ' + param)
self.addNode(node)
# configuation should hold name for each zone and name for each
# source. Here we should map the zone names to what is reported
# by the russound and create zone nodes. When we create the
# zone node, pass in the source name list.
# Delete the node server from Polyglot
def delete(self):
LOGGER.info('Removing node server')
def stop(self):
LOGGER.info('Stopping node server')
def update_profile(self, command):
st = self.poly.installprofile()
return st
def check_params(self):
# NEW code, try this:
self.removeNoticesAll()
if self.params.get_from_polyglot(self):
LOGGER.debug('All required parameters are set!')
self.configured = True
else:
LOGGER.debug('Configuration required.')
LOGGER.debug('IP Address = ' + self.params.get('IP Address'))
LOGGER.debug('Port = ' + self.params.get('Port'))
self.params.send_notices(self)
def remove_notices_all(self, command):
self.removeNoticesAll()
def set_source_selection(self, state, source):
source_map = ['GV1', 'GV2', 'GV3', 'GV4', 'GV5', 'GV6']
# if state is on, set source bit else clear source bit
if state == 0x01:
LOGGER.info('Source ' + str(source+1) + ' is ACTIVE')
self.source_status = self.source_status | (1 >> source)
self.reportCmd(source_map[source], 1, 25)
self.setDriver(source_map[source], 1)
else:
LOGGER.info('Source ' + str(source+1) + ' is INACTIVE')
self.source_status = self.source_status & ~(1 >> source)
self.reportCmd(source_map[source], 0, 25)
self.setDriver(source_map[source], 0)
def processCommand(self, msg):
zone = msg.TargetZone() + 1
zone_addr = 'zone_' + str(zone)
if zone >= 0x70:
LOGGER.debug('Message target not a zone: ' + str(zone))
return
if msg.MessageType() == RNET_MSG_TYPE.ZONE_STATE:
# It looks like the zone state is in the TS field.
LOGGER.debug(' -> Zone %d state = 0x%x' % (msg.TargetZone(), msg.EventTS()))
zone_addr = 'zone_' + str(msg.TargetZone() + 1)
self.nodes[zone_addr].set_power(int(msg.EventTS()))
elif msg.MessageType() == RNET_MSG_TYPE.ZONE_SOURCE:
LOGGER.debug(' -> Zone %d source = 0x%x' % (zone, msg.MessageData()[19]+1))
self.nodes[zone_addr].set_source(int(msg.MessageData()[19]))
elif msg.MessageType() == RNET_MSG_TYPE.ZONE_VOLUME:
# See what we get here. Then try to update the actual node
# for the zone
LOGGER.debug(' -> Zone %d volume = 0x%x' % (zone, msg.EventData()))
self.nodes[zone_addr].set_volume(int(msg.EventData()))
elif msg.MessageType() == RNET_MSG_TYPE.ZONE_BASS:
LOGGER.debug(' -> Zone %d bass = 0x%x' % (zone, msg.MessageData()[20]))
self.nodes[zone_addr].set_bass(int(msg.MessageData()[20]))
elif msg.MessageType() == RNET_MSG_TYPE.ZONE_TREBLE:
LOGGER.debug(' -> Zone %d treble = 0x%x' % (zone, msg.MessageData()[20]))
self.nodes[zone_addr].set_treble(int(msg.MessageData()[20]))
elif msg.MessageType() == RNET_MSG_TYPE.ZONE_BALANCE:
LOGGER.debug(' -> Zone %d balance = 0x%x' % (zone, msg.MessageData()[20]))
self.nodes[zone_addr].set_balance(int(msg.MessageData()[20]))
elif msg.MessageType() == RNET_MSG_TYPE.ZONE_LOUDNESS:
LOGGER.debug(' -> Zone %d loudness = 0x%x' % (zone, msg.MessageData()[20]))
self.nodes[zone_addr].set_loudness(int(msg.MessageData()[20]))
elif msg.MessageType() == RNET_MSG_TYPE.ZONE_PARTY_MODE:
LOGGER.debug(' -> Zone %d party mode = 0x%x' % (zone, msg.MessageData()[20]))
self.nodes[zone_addr].set_party_mode(int(msg.MessageData()[20]))
elif msg.MessageType() == RNET_MSG_TYPE.ZONE_DO_NOT_DISTURB:
LOGGER.debug(' -> Zone %d do not disturb = 0x%x' % (zone, msg.MessageData()[20]))
self.nodes[zone_addr].set_dnd(int(msg.MessageData()[20]))
elif msg.MessageType() == RNET_MSG_TYPE.UPDATE_SOURCE_SELECTION:
# We can use this to check for sources going on/off (or really
# being activated/deactivated). The value returned is a bitmap
# that indicates which sources are active. By looking at what
# has changed since the last time we saw this message, we can
# track the source state transitions.
LOGGER.debug(' -> Update Zone source 0x%x 0x%x' % (msg.MessageData()[0], msg.MessageData()[1]))
# First, look only at what has changed since the last time this
# was called.
ns = msg.MessageData()[0]
ss = ns ^ self.source_status
# Based on what changed send a command to the ISY that
# can be used as a source activated trigger.
if (ss & 0x01) == 0x01: # source 1 changed
LOGGER.info('Source 1 changed')
if (ns & 0x01) == 0x01: # source 1 activated
self.setDriver('GV1', 1)
else:
self.setDriver('GV1', 0)
if (ss & 0x02) == 0x02: # source 2 changed
LOGGER.info('Source 2 changed')
if (ns & 0x02) == 0x02: # source 2 activated
self.setDriver('GV2', 1)
else:
self.setDriver('GV2', 0)
if (ss & 0x04) == 0x04: # source 3 changed
LOGGER.info('Source 3 changed')
if (ns & 0x04) == 0x04: # source 3 activated
self.setDriver('GV3', 1)
else:
self.setDriver('GV3', 0)
if (ss & 0x08) == 0x08: # source 4 changed
LOGGER.info('Source 4 changed')
if (ns & 0x08) == 0x08: # source 4 activated
self.setDriver('GV4', 1)
else:
self.setDriver('GV4', 0)
if (ss & 0x10) == 0x10: # source 5 changed
LOGGER.info('Source 5 changed')
if (ns & 0x10) == 0x10: # source 5 activated
self.setDriver('GV5', 1)
else:
self.setDriver('GV5', 0)
if (ss & 0x20) == 0x20: # source 6 changed
LOGGER.info('Source 6 changed')
if (ns & 0x20) == 0x20: # source 6 activated
self.setDriver('GV6', 1)
else:
self.setDriver('GV6', 0)
self.source_status = ns
elif msg.MessageType() == RNET_MSG_TYPE.UNDOCUMENTED:
# this seems to be the only thing we get when we select
# a source from the keypad.
# example:
# 49 03 00 00 05
# MessageData[0] varies
# MessageData[1] is the source
# MessageData[4] is 5, does this mean source select?
# param 0x90 is volume?
# event data:
# 0x01 (01) == 2
# 0x0c (12) == 24
# 0x0d (13) == 26
# 0x0e (14) == 28
# 0x16 (22) == 44
if msg.EventId() == 0x90:
LOGGER.debug(' -> Volume adjusted to: ' + str(msg.EventData()))
elif msg.MessageData()[4] == 0x05: # source selection
LOGGER.debug(' -> Zone {} set to source {}'.format(zone_addr, msg.MessageData()[1]+1))
self.nodes[zone_addr].set_source(int(msg.MessageData()[1]))
else:
LOGGER.debug(' -> param 0x%x = 0x%x for zone %d' % (msg.EventId(), msg.EventData(), msg.EventZone()))
#LOGGER.debug(' D ' + ' '.join('{:02x}'.format(x) for x in msg.MessageData()))
# Do we care about keypad events? Maybe in the sense that we'd
# like to create a program that is something like:
#
# if zone keypress == Next then do something
#
# which means we need a node driver that holds the last keypress
# value.
elif msg.MessageType() == RNET_MSG_TYPE.ALL_ZONE_INFO:
LOGGER.info('All zone info for ' + zone_addr)
LOGGER.debug(' | |
#!/usr/bin/env python
# Copyright 2015 VMware, Inc. All rights reserved. -- VMware Confidential
"""
Utility functions to support certificate-manager
"""
__author__ = '<NAME> (<EMAIL>)'
__copyright__ = 'Copyright 2015, VMware Inc.'
__version__ = 1.0
import logging
import os
import sys
import errno
sys.path.append(os.environ['VMWARE_PYTHON_PATH'])
from utils import *
from cis.defaults import get_cis_log_dir, get_cis_data_dir, get_cis_tmp_dir, get_env_var
cfgKeys = list()
cfgValues = list()
resultCfg = list()
global logFile
isLinux = os.name == 'posix'
if not isLinux:
import pywintypes
import win32service as w32s
import win32serviceutil as w32su
def show_progress(progress, appendMsg, msg='Status'):
"""
Function to show progress messages in console
:param progress: Progress %
:param appendMsg: Message which needs to presented to user
:param msg: Status message
"""
value = ' '
if '100' in str(progress) or 'failed' in appendMsg:
value = '\n'
appendMsg = 'Completed [{0}]{1} '.format(appendMsg, value)
sys.stdout.write("{0} : {1}% {2} \r".format(msg, int(progress), appendMsg))
sys.stdout.flush()
def get_log_file():
"""
Function to get certificate-manager log file location
:return: Returns certificate-manager log location
"""
return logfile
def initialize_ops():
"""
Function to setup logging and create required directories
"""
global logfile
# Setup up logging to file/syslog based on operation
log_folder = 'vmca'
if isLinux:
log_folder = 'vmcad'
logDir = os.path.join(get_cis_log_dir(), log_folder)
setupLogging('certificate-manager', logMechanism='file', logDir=logDir)
logfile = os.path.join(logDir, 'certificate-manager.log')
# setup certificate manager directory
directory = os.path.dirname(get_cert_dir())
if not os.path.exists(directory):
create_directory(directory)
logging.info("Created the certificate-manager directory: {0}".format(directory))
rollback_dir = os.path.dirname(get_rollback_cert_dir())
if not os.path.exists(rollback_dir):
create_directory(rollback_dir)
logging.info('temp directory of certs : {0}'.format(rollback_dir))
def create_directory(directory):
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
log_error_msg("ERROR: Failed to create directory ({0}): {1}".format(e.errno, e.strerror))
raise e
def get_root_cert_dir():
if isLinux:
return '/var/lib/vmware/vmca/'
else:
dir = os.path.join(get_cis_data_dir(), 'vmca')
return dir + os.path.sep
def get_cert_dir():
directory = os.path.join(get_cis_data_dir(), 'certmanager')
return directory + os.path.sep
def get_rollback_cert_dir():
directory = os.path.join(get_cert_dir(), 'rollback')
return directory + os.path.sep
def get_src_config_file_loc():
if isLinux:
return "/usr/lib/vmware-vmca/share/config/certool.cfg"
else:
return get_env_var('VMWARE_CIS_HOME') + os.path.sep + 'vmcad' + os.path.sep + 'certool.cfg'
def get_dest_config_file_loc():
directory = os.path.join(get_cis_tmp_dir(), 'certool.cfg')
return directory
def log_info_msg(msg):
"""
Method to write messages to console as well as log
"""
#Append new line to make sure progress messages are not over written
print('')
print(str(msg))
logging.info(str(msg))
def log_error_msg(msg):
"""
Method to write messages to console as well as log
"""
#Append new line to make sure progress messages are not over written
print('')
print(str(msg))
logging.error(str(msg))
def read_cfg_file(filename):
with open(filename) as fp:
for line in fp:
if '=' in line:
cfgKeys.append((line.split('=')[0]).replace('\t', '').strip())
cfgValues.append((line.split('=')[1]).replace('\t', '').strip())
def write_cfg_file():
file = open(get_dest_config_file_loc(), "wb")
logging.info('Certool.cfg file contents.')
for item in resultCfg:
logging.info(item)
file.write(item + "\n")
file.close()
def prepare_cfg_file():
"""
Method to prepare Certool.cfg file
"""
str = 'Default'
#If config file exists then reconfigure else create new using default certool.cfg file
if check_file_exists(get_dest_config_file_loc()):
if get_user_confirmation(Constants.RECONFIGURE_CFG_MSG):
filename = get_dest_config_file_loc()
str = 'Previous'
else:
return
else:
log_info_msg(Constants.CONFIGURE_CFG_MSG)
filename = get_src_config_file_loc()
read_cfg_file(filename)
log_info_msg('Press Enter key to skip optional parameters or use {0} value.'.format(str))
index = 0
for item in cfgKeys:
#Optional param will be commented, uncomment while reconfiguring
if '#' in item:
item = item.replace('#','')
if item == 'Hostname':
value = 'Enter valid Fully Qualified Domain Name(FQDN), For Example : example.domain.com'
elif item == 'IPAddress':
value = 'optional'
else:
#Show default or previous value
value = '{0} value : {1}'.format(str, cfgValues[index])
var = raw_input("\nEnter proper value for '{0}' [{1}] : ".format(item, value))
#Validate Hostname, hostname should not be empty
if item == 'Hostname':
while var.strip() == '':
log_info_msg('Hostname should not be empty, please enter valid FQDN.')
var = raw_input("\nEnter proper value for '{0}' [{1}] : ".format(item, value))
if not len(var.strip()) > 0:
if value == 'optional':
item = '#' + item
else:
var = cfgValues[index]
# Validate IPAddress
if item == 'IPAddress':
while not isIPAddress(var):
if not len(var.strip()) > 0:
item = '#' + item
break
log_info_msg('Please enter IP address in valid IPV4 or IPV6 format')
var = raw_input("\nEnter proper value for '{0}' [{1}] : ".format(item, value))
# Restrict Country code to 2 letters
if item == 'Country':
while not len(var.strip()) == 2:
log_info_msg('Enter valid 2 letter country code')
var = raw_input("\nEnter proper value for '{0}' [{1}] : ".format(item, value))
index += 1
resultCfg.append(item + " = " + var)
write_cfg_file()
def check_file_exists(filename):
if '\"' in filename:
filename = filename.replace('\"', '')
elif '\'' in filename:
filename = filename.replace('\'', '')
return os.path.isfile(filename)
def get_user_confirmation(msg):
logging.info(msg + '\n')
msg = msg + ' : Option[Y/N] ? : '
var = raw_input(msg)
if var.strip() in ['y', 'Y']:
logging.info('Answer : Y')
return True
elif var.strip() in ['n', 'N']:
logging.info('Answer : N')
return False
else:
get_user_confirmation('Please enter any value with in [Y/N].')
def ask_for_file_and_validate(msg, optional=False):
log_info_msg(msg)
if optional:
log_info_msg('Optional parameter, press Enter key to skip')
var = raw_input('File : ')
if len(var.strip()) == 0 and optional:
return ''
while not check_file_exists(var.strip()):
log_info_msg("Please provide valid file location, couldn't find file : " + var.strip())
var = raw_input("File : ")
#Remove quotes in filename
if '\"' in var:
var = var.replace('\"', '')
elif '\'' in var:
var = var.replace('\'', '')
return var.strip()
def ask_for_output_file_path(msg, isDir=False):
log_info_msg(msg)
var = raw_input('Output directory path: ')
realPath = os.path.realpath(var.strip())
if isDir:
if os.path.exists(realPath) == False:
raise IOError ('Cannot find directory: ' + realPath)
if os.access(realPath, os.W_OK) == False:
raise PermissionError ('You do not have permission to write to this location')
else:
if os.path.exists(os.path.split(realPath)[0]) == False:
raise IOError ('Cannot find parent directory location: ' + realPath)
if os.access(os.path.split(realPath)[0], os.W_OK) == False:
raise PermissionError ('You do not have permission to write to this location')
return var.strip()
class Constants():
"""
Class maintaining all constants and messages used by cert-manager
"""
# Progress constants
STARTING_SERVICES = 'starting services...'
STOPPING_SERVICES = 'stopping services...'
REPLACE_MACHINE_SSL = 'Replacing Machine SSL Cert...'
REPLACE_SOLUTION_CERT = 'Replace {0} Cert...'
REPLACE_ROOT_CERT = 'Replacing Root Cert...'
REPLACED_ROOT_CERT = 'Replaced Root Cert...'
ROLLBACK_MACHINE_SSL = 'Rollback Machine SSL Cert...'
ROLLBACK_SOLUTION_CERT = 'Rollback {0} Cert...'
ROLLBACK_ROOT_CERT = 'Rollback Root Cert...'
REVERT_MACHINE_SSL = 'Revert Machine SSL Cert...'
REVERT_SOLUTION_CERT = 'Revert {0} Cert...'
REVERT_ROOT_CERT = 'Revert Root Cert...'
RESET_MACHINE_SSL = 'Reset Machine SSL Cert...'
RESET_SOLUTION_CERT = 'Reset {0} Cert...'
RESET_ROOT_CERT = 'Reset Root Cert...'
PUBLISHING_ROOT_CERT = 'Publishing Root cert...'
TASK_COMPLETED = 'All tasks completed successfully'
REVERT_TASK_COMPLETED = 'Revert completed successfully'
RESET_TASK_COMPLETED = 'Reset completed successfully'
ROLLBACK_TASK_COMPLETED = 'Rollback completed successfully'
ROLLBACK_MSG = 'Operation failed, performing automatic rollback'
MGMT_ROLLBACK_MSG = 'Operation failed, Automatic rollback is not supported in distributed setup.\nPlease perform revert operation in Platform Services Controller machine \'{0}\' and then perform revert operation in this machine'
REVERT_ERROR_MSG = 'Revert operation failed'
RESET_ERROR_MSG = 'Reset operation failed'
ROLLBACK_ERROR_MSG = 'Rollback operation failed'
REVERT_STATUS = 'Revert status'
RESET_STATUS = 'Reset status'
ROLLBACK_STATUS = 'Rollback Status'
#Load certificate messages
READ_ROOT_CRT = 'Please provide valid custom certificate for Root.'
READ_ROOT_SIGNING_CRT = 'Please provide the signing certificate of the '
READ_ROOT_KEY = 'Please provide valid custom key for Root.'
READ_MACHINE_SSL_CRT = 'Please provide valid custom certificate for Machine SSL.'
READ_MACHINE_SSL_KEY = 'Please provide valid custom key for Machine SSL.'
READ_SOLUTION_USER_CRT = 'Please provide valid custom certificate for solution user store : '
READ_SOLUTION_USER_KEY = 'Please provide valid custom key for solution user store : '
READ_PRIVATEKEY_OP_PATH = 'Please provide a location for private key: '
READ_CSR_OP_PATH = 'Please provide a location for CSR: '
READ_CSR_OP_DIR_PATH = 'Please provide a directory location to write the CSR(s) and PrivateKey(s) to: '
#General constants
IP_LOCALHOST = 'localhost'
CONTINUE_OPERATION = 'Continue operation'
MACHINE_SSL_STORE = 'MACHINE_SSL_CERT'
MACHINE_SSL_ALIAS = '__MACHINE_CERT'
TRUSTED_ROOTS_STORE = 'TRUSTED_ROOTS'
SERVICES_ALL = 'all'
SERVICES_NON_CORE = 'non-core'
ROOT_CERT = 'root.cer'
ROOT_KEY = 'privatekey.pem'
BKP_ROOT_CERT = 'root.cer.0'
BKP_ROOT_KEY = 'privatekey.pem.0'
TERMINATE_OP = '\nTerminating operation.'
PASSWORD_ATTEMPTS_ERROR = 'Reached max number of attempts, terminating operation.'
BKP_CERT_EXT = '_bkp.crt'
BKP_KEY_EXT = '_bkp.priv'
SSL_ROLLBACK_MSG = 'Performing rollback of Machine SSL Cert...'
SOL_ROLLBACK_MSG = 'Performing rollback of Solution User Certs...'
ROOT_ROLLBACK_MSG = 'Performing rollback of Root Cert...'
ROLLBACK_FAILED_MSG = 'Error while performing rollback operation, please try Reset operation...'
CERT_EXT = '.crt'
KEY_EXT = '.priv'
PUB_EXT = '.pub'
RECONFIGURE_CFG_MSG = 'Certool.cfg file exists, Do you wish to reconfigure'
CONFIGURE_CFG_MSG = 'Please configure certool.cfg file with proper values before proceeding to next step.'
ROOT_PRIVATE_KEY_OUTPUT_FILENAME = 'root_signing_cert.key'
ROOT_CSR_FILE_OUTPUT_FILENAME = 'root_signing_cert.csr'
MACHINE_SSL_PRIVATE_KEY_OUTPUT_FILENAME = 'machine_ssl.key'
MACHINE_SSL_CSR_OUTPUT_FILENAME = 'machine_ssl.csr'
#service constants
VMCA_SERVICE_LIN = 'vmcad'
VMAFD_SERVICE_LIN = 'vmafdd'
VMDIRD_SERVICE_LIN = 'vmdird'
| |
if not 'timestamp' in quote:
quote['timestamp'] = self.time
if not 'order_id' in quote:
quote['order_id'] = self.next_order_id
self._last_order_timestamp = quote['timestamp']
if quote['quantity'] <= 0:
sys.exit('process_order() given order of quantity <= 0')
if order_type == 'market':
# Tape LOB state before processing order :
if self.b_tape_LOB:
self.LOBtape.append(self.getCurrentLOB('market', 'MO', quote))
trades = self.process_market_order(quote)
elif order_type == 'limit':
quote['price'] = Decimal(quote['price'])
# Tape LOB state before processing order :
if self.b_tape_LOB:
self.LOBtape.append(self.getCurrentLOB('limit', 'LO', quote))
trades, order_in_book = self.process_limit_order(quote)
else:
sys.exit("order_type for process_order() is neither 'market' or 'limit'")
self.notify_agents(trades, order_in_book)
return trades, order_in_book
def process_order_list(self, side, order_list, quantity_still_to_trade, quote):
'''
Takes an OrderList (stack of orders at one price) and an incoming order and matches
appropriate trades given the order's quantity.
'''
trades = []
quantity_to_trade = quantity_still_to_trade
while len(order_list) > 0 and quantity_to_trade > 0:
head_order = order_list.get_head_order()
traded_price = head_order.price
counter_party = head_order.trader_id
new_book_quantity = None
if quantity_to_trade < head_order.quantity:
traded_quantity = quantity_to_trade
# Do the transaction
new_book_quantity = head_order.quantity - quantity_to_trade
head_order.update_quantity(new_book_quantity, head_order.timestamp)
quantity_to_trade = 0
elif quantity_to_trade == head_order.quantity:
traded_quantity = quantity_to_trade
if side == 'bid':
self.bids.remove_order_by_id(head_order.order_id)
else:
self.asks.remove_order_by_id(head_order.order_id)
quantity_to_trade = 0
else: # quantity to trade is larger than the head order
traded_quantity = head_order.quantity
if side == 'bid':
self.bids.remove_order_by_id(head_order.order_id)
else:
self.asks.remove_order_by_id(head_order.order_id)
quantity_to_trade -= traded_quantity
transaction_record = {
# 'timestamp': self.time,
'traded_price': traded_price,
'traded_quantity': traded_quantity,
'time': quote['timestamp'] if 'timestamp' in quote else self.time
}
party2_orderid=quote['order_id'] if 'order_id' in quote else None
if side == 'bid':
transaction_record['party1_id'] = counter_party
transaction_record['party1_side'] = 'bid'
transaction_record['party1_order_id'] = head_order.order_id
# transaction_record['party1_newbookquantity'] = [counter_party, 'bid', head_order.order_id, new_book_quantity]
transaction_record['party2_id'] = quote['trader_id']
transaction_record['party2_side'] = 'ask'
transaction_record['party2_order_id'] = party2_orderid # None means that the sender of order is party 2
self.lastTradeSign = 'ask'
else:
transaction_record['party1_id'] = counter_party
transaction_record['party1_side'] = 'ask'
transaction_record['party1_order_id'] = head_order.order_id
transaction_record['party2_id'] = quote['trader_id']
transaction_record['party2_side'] = 'ask'
transaction_record['party2_order_id'] = party2_orderid # None means that the sender of order is party 2
self.lastTradeSign = 'bid'
if self.verbose:
print(f'\n**** New Trade : **** \n: {str(transaction_record)}')
self.lastTradePrice = traded_price
if self.b_tape:
self.tape.append(transaction_record)
#FDR
self.tstape += [quote['timestamp'] if 'timestamp' in quote else self.time]
self.pricetape += [traded_price]
self.qttytape += [traded_quantity]
trades.append(transaction_record)
return quantity_to_trade, trades
def process_market_order(self, quote):
if self.verbose:
print(f'\n**** I received this market order **** \n: {str(quote)}')
trades = []
quantity_to_trade = quote['quantity']
side = quote['side']
if side == 'bid':
while quantity_to_trade > 0 and self.asks:
best_price_asks = self.asks.min_price_list()
quantity_to_trade, new_trades = self.process_order_list('ask', best_price_asks, quantity_to_trade, quote)
trades += new_trades
elif side == 'ask':
while quantity_to_trade > 0 and self.bids:
best_price_bids = self.bids.max_price_list()
quantity_to_trade, new_trades = self.process_order_list('bid', best_price_bids, quantity_to_trade, quote)
trades += new_trades
else:
sys.exit('process_market_order() recieved neither "bid" nor "ask"')
return trades
def process_limit_order(self, quote):
if self.verbose:
print(f'\n**** I received this limit order **** \n: {str(quote)}')
order_in_book = None
trades = []
quantity_to_trade = quote['quantity']
side = quote['side']
price = quote['price']
if side == 'bid':
while (self.asks and price >= self.asks.min_price() and quantity_to_trade > 0):
best_price_asks = self.asks.min_price_list()
quantity_to_trade, new_trades = self.process_order_list('ask', best_price_asks, quantity_to_trade, quote)
trades += new_trades
# If volume remains, need to update the book with new quantity
if quantity_to_trade > 0:
quote['quantity'] = quantity_to_trade
self.bids.insert_order(quote)
order_in_book = quote
elif side == 'ask':
while (self.bids and price <= self.bids.max_price() and quantity_to_trade > 0):
best_price_bids = self.bids.max_price_list()
quantity_to_trade, new_trades = self.process_order_list('bid', best_price_bids, quantity_to_trade, quote)
trades += new_trades
# If volume remains, need to update the book with new quantity
if quantity_to_trade > 0:
quote['quantity'] = quantity_to_trade
self.asks.insert_order(quote)
order_in_book = quote
else:
sys.exit('process_limit_order() given neither "bid" nor "ask"')
return trades, order_in_book
def cancel_order(self, side, order_id):
if self.verbose:
print(f'\n**** I received this cancel order **** \n: {str(order_id)}')
# Tape LOB state before processing order :
self.cancel_order_tape(side, order_id)
# Cancel Order
trader_id = None
if side == 'bid':
if self.bids.order_exists(order_id):
trader_id = self.bids.remove_order_by_id(order_id)
else:
if self.verbose:
print(f'\n**** Cancel Error : Order does not exist **** \n: {str(order_id)}')
elif side == 'ask':
if self.asks.order_exists(order_id):
trader_id = self.asks.remove_order_by_id(order_id)
else:
if self.verbose:
print(f'\n**** Cancel Error : Order does not exist **** \n: {str(order_id)}')
else:
sys.exit('cancel_order() given neither "bid" nor "ask"')
if trader_id:
self.notify_cancelation(side, trader_id, order_id)
# add the cancel order to the tape
def cancel_order_tape(self, side, order_id):
if self.b_tape_LOB:
if side == 'bid':
if self.bids.order_exists(order_id):
order = self.bids.order_map[order_id]
self.LOBtape.append(self.getCurrentLOB('limit', 'cancel', order))
else:
self.LOBtape.append(self.getCurrentLOB('limit', 'cancel', {'order_id':order_id}))
elif side == 'ask':
if self.asks.order_exists(order_id):
order = self.asks.order_map[order_id]
self.LOBtape.append(self.getCurrentLOB('limit', 'cancel', order))
else:
self.LOBtape.append(self.getCurrentLOB('limit', 'cancel', {'order_id':order_id}))
else:
sys.exit('cancel_order() given neither "bid" nor "ask"')
######################################################################
# Order cancelation rules :
# 4202/4 Modification and cancellation.
# Any order entered into the Central Order Book may be modified or
# cancelled prior to its execution. Any increase in the order
# quantity or change in the limit price shall cause the forfeiture
# of time priority.
######################################################################
def modify_order(self, order_id, order_update):
if self.verbose:
print(f'\n**** I received this modify order **** \n: {str(order_id)} : {str(order_update)}')
side = order_update['side']
order_update['order_id'] = order_id
if 'timestamp' not in order_update:
order_update['timestamp'] = self.time
# Tape LOB state before processing order :
if self.b_tape_LOB:
self.LOBtape.append(self.getCurrentLOB('limit', 'modify', order_update))
if side == 'bid':
if self.bids.order_exists(order_update['order_id']):
# Check if the order looses priority :
if self.bids.update_order_looses_priority(order_update):
# if true, delete order and re process it (if it becomes agressive)
trader_id = self.bids.remove_order_by_id(order_id)
# don't record the new order, it isn't new.
old_b_tape_lob = self.b_tape_LOB
self._b_tape_LOB = False
self.process_order(order_update)
self._b_tape_LOB = old_b_tape_lob
else:
self.bids.update_order_quantity(order_update)
self.notify_modification(order_update)
else:
if self.verbose:
print(f'\n**** Order modification Error : order does not exist **** \n: {str(order_id)}')
elif side == 'ask':
if self.asks.order_exists(order_update['order_id']):
# Check if the order looses priority :
if self.asks.update_order_looses_priority(order_update):
# if true, delete order and re process it (if it becomes agressive)
trader_id = self.asks.remove_order_by_id(order_id)
# don't record the new order, it isn't new.
old_b_tape_lob = self.b_tape_LOB
self._b_tape_LOB = False
self.process_order(order_update)
self._b_tape_LOB = old_b_tape_lob
else:
self.asks.update_order_quantity(order_update)
self.notify_modification(order_update)
else:
if self.verbose:
print(f'\n**** Order modification Error : order does not exist **** \n: {str(order_id)}')
else:
sys.exit('modify_order() given neither "bid" nor "ask"')
# def modify_order_old(self, order_id, order_update):
# if self.verbose:
# print(f'\n**** I received this modify order **** \n: {str(order_id)}')
# side = order_update['side']
# order_update['order_id'] = order_id
# order_update['timestamp'] = self.time
# # Tape LOB state before processing order :
# if self.b_tape_LOB:
# self.LOBtape.append(self.getCurrentLOB('limit', 'modify', order_update))
# if side == 'bid':
# if self.bids.order_exists(order_update['order_id']):
# self.bids.update_order(order_update)
# # self.notify_modification(order_id, order_update)
# else:
# if self.verbose:
# print(f'\n**** Order modification Error : order does not exist **** \n: {str(order_id)}')
# elif side == 'ask':
# if self.asks.order_exists(order_update['order_id']):
# self.asks.update_order(order_update)
# else:
# if self.verbose:
# print(f'\n**** Order modification Error : order does not exist **** \n: {str(order_id)}')
# else:
# sys.exit('modify_order() given neither "bid" nor "ask"')
#########################################
# Order Book state information
#########################################
# for market makers
def get_head_order_at_price(self, side, price):
price = Decimal(price)
if side == 'bid':
order = None
if self.bids.price_exists(price):
order = self.bids.get_price_list(price).tail_order
return order
elif side == 'ask':
order = None
if self.asks.price_exists(price):
order = self.asks.get_price_list(price).tail_order
return order
else:
sys.exit('get_head_order_at_price() given neither "bid" nor "ask"')
def get_volume_at_price(self, side, price):
price = Decimal(price)
if side == 'bid':
volume = 0
if self.bids.price_exists(price):
volume = self.bids.get_price_list(price).volume
return volume
elif side == 'ask':
volume = 0
if self.asks.price_exists(price):
volume = self.asks.get_price_list(price).volume
return volume
else:
sys.exit('get_volume_at_price() given neither "bid" nor "ask"')
def get_best_bid(self):
return self.bids.max_price()
def get_worst_bid(self):
return self.bids.min_price()
def get_best_ask(self):
return self.asks.min_price()
def get_worst_ask(self):
return self.asks.max_price()
#########################################
# Order Book Purging
#########################################
def tape_dump(self, filename, filemode, tapemode):
if filename is not None:
dumpfile = open(filename, filemode)
for tapeitem in self.tape:
dumpfile.write('Time: %s, Price: %s, Quantity: %s\n' % (tapeitem['time'],
tapeitem['price'],
tapeitem['quantity']))
dumpfile.close()
if tapemode == 'wipe':
self.tape = []
#########################################
# Order Book Statistical info : volatility ? imbalance ?
#########################################
#########################################
# Fancy Outputs
#########################################
def getCurrentLOB(self, ordertype_, actiontype_, order, side=None):
# gives the -i best bids & i asks and corersponding quantities as a dictionary
# bids:
if type(order) == dict:
order_id = order['order_id'] if 'order_id' in order else None
timestamp = order['timestamp'] | |
subscriber_activity_table,
'total_number_of_events': total_number_of_events,
'number_of_filtered_events': len(events),
'keyword': keyword,
'start_date': context_start_date,
'end_date': context_end_date,
'all_services': all_services,
'checked_services': checked_services,
}
template = get_template('dashboard/subscriber_detail/activity.html')
html = template.render(context, request)
return HttpResponse(html)
class SubscriberSendSMS(ProtectedView):
"""Send an SMS to a single subscriber."""
def get(self, request, imsi=None):
"""Handles GET requests."""
user_profile = UserProfile.objects.get(user=request.user)
network = user_profile.network
try:
subscriber = Subscriber.objects.get(imsi=imsi,
network=network)
except Subscriber.DoesNotExist:
return HttpResponseBadRequest()
initial_form_data = {
'imsi': subscriber.imsi
}
# Set the response context.
context = {
'networks': get_objects_for_user(request.user, 'view_network', klass=Network),
'user_profile': user_profile,
'subscriber': subscriber,
'send_sms_form': dform.SubscriberSendSMSForm(
initial=initial_form_data)
}
# Render template.
template = get_template('dashboard/subscriber_detail/send_sms.html')
html = template.render(context, request)
return HttpResponse(html)
def post(self, request, imsi=None):
user_profile = UserProfile.objects.get(user=request.user)
network = user_profile.network
if 'message' not in request.POST:
return HttpResponseBadRequest()
try:
sub = Subscriber.objects.get(imsi=imsi,
network=network)
except Subscriber.DoesNotExist:
return HttpResponseBadRequest()
# Fire off an async task request to send the SMS. We send to the
# subscriber's first number and from some admin number.
num = sub.number_set.all()[0]
params = {
'to': num.number,
'sender': '0000',
'text': request.POST['message'],
'msgid': str(uuid.uuid4())
}
url = sub.bts.inbound_url + "/endaga_sms"
tasks.async_post.delay(url, params)
params = {
'imsi': sub.imsi
}
url_params = {
'sent': 'true'
}
base_url = urlresolvers.reverse('subscriber-send-sms', kwargs=params)
url = '%s?%s' % (base_url, urllib.urlencode(url_params))
return redirect(url)
class SubscriberAdjustCredit(ProtectedView):
"""Adjust credit for a single subscriber."""
def get(self, request, imsi=None):
"""Handles GET requests."""
user_profile = UserProfile.objects.get(user=request.user)
network = user_profile.network
try:
subscriber = Subscriber.objects.get(imsi=imsi,
network=network)
except Subscriber.DoesNotExist:
return HttpResponseBadRequest()
# Set the response context.
pending_updates = subscriber.pendingcreditupdate_set.all().order_by(
'date')
initial_form_data = {
'imsi': subscriber.imsi,
}
context = {
'networks': get_objects_for_user(request.user, 'view_network', klass=Network),
'currency': CURRENCIES[network.subscriber_currency],
'user_profile': user_profile,
'subscriber': subscriber,
'pending_updates': pending_updates,
'credit_update_form': dform.SubscriberCreditUpdateForm(
initial=initial_form_data),
}
# Render template.
template = get_template(
'dashboard/subscriber_detail/adjust_credit.html')
html = template.render(context, request)
return HttpResponse(html)
def post(self, request, imsi=None):
"""Operators can use this API to add credit to a subscriber.
These additions become PendingCreditUpdates and celery will try to
"apply" then by sending the info to the corresponding BTS. The
operator may also delete PendingCreditUpdates, effectively canceling
them.
"""
user_profile = UserProfile.objects.get(user=request.user)
network = user_profile.network
# In all cases we'll redirect back to the adjust-credit page.
sub = Subscriber.objects.get(imsi=imsi, network=network)
params = {
'imsi': sub.imsi
}
adjust_credit_redirect = redirect(
urlresolvers.reverse('subscriber-adjust-credit', kwargs=params))
# Validate the input.
if 'amount' not in request.POST:
return HttpResponseBadRequest()
error_text = 'Error: credit value must be between -10M and 10M.'
try:
currency = network.subscriber_currency
amount = parse_credits(request.POST['amount'],
CURRENCIES[currency]).amount_raw
if abs(amount) > 2147483647:
raise ValueError(error_text)
except ValueError:
messages.error(request, error_text)
return adjust_credit_redirect
# Validation suceeded, create a PCU and start the update credit task.
msgid = str(uuid.uuid4())
credit_update = PendingCreditUpdate(subscriber=sub, uuid=msgid,
amount=amount)
credit_update.save()
tasks.update_credit.delay(sub.imsi, msgid)
return adjust_credit_redirect
def delete(self, request, imsi=None):
"""Handle the deletion of Pending Credit Updates."""
user_profile = UserProfile.objects.get(user=request.user)
network = user_profile.network
request_data = QueryDict(request.body)
if "pending_id" not in request_data:
return HttpResponseBadRequest()
pending_id = request_data['pending_id']
try:
update = PendingCreditUpdate.objects.get(uuid=pending_id)
except PendingCreditUpdate.DoesNotExist:
return HttpResponseBadRequest()
if update.subscriber.network != network:
return HttpResponseBadRequest()
update.delete()
return HttpResponse()
class SubscriberEdit(ProtectedView):
"""Edit a single subscriber's info."""
def get(self, request, imsi=None):
"""Handles GET requests."""
user_profile = UserProfile.objects.get(user=request.user)
network = user_profile.network
try:
subscriber = Subscriber.objects.get(imsi=imsi,
network=network)
except Subscriber.DoesNotExist:
return HttpResponseBadRequest()
# Set the response context.
initial_form_data = {
'imsi': subscriber.imsi,
'name': subscriber.name,
'prevent_automatic_deactivation': (
subscriber.prevent_automatic_deactivation),
}
context = {
'networks': get_objects_for_user(request.user, 'view_network', klass=Network),
'user_profile': user_profile,
'subscriber': subscriber,
'subscriber_info_form': dform.SubscriberInfoForm(
initial=initial_form_data),
'network_version': (
subscriber.network.get_lowest_tower_version()),
}
# Render template.
template = get_template(
'dashboard/subscriber_detail/edit.html')
html = template.render(context, request)
return HttpResponse(html)
def post(self, request, imsi=None):
"""Handles POST requests to change subscriber info."""
user_profile = UserProfile.objects.get(user=request.user)
network = user_profile.network
try:
subscriber = Subscriber.objects.get(imsi=imsi,
network=network)
except Subscriber.DoesNotExist:
return HttpResponseBadRequest()
if (request.POST.get('name') and
subscriber.name != request.POST.get('name')):
subscriber.name = request.POST.get('name')
subscriber.save()
if request.POST.get('prevent_automatic_deactivation'):
protected = (
request.POST.get('prevent_automatic_deactivation') == 'True')
subscriber.prevent_automatic_deactivation = protected
subscriber.save()
messages.success(request, "Subscriber information updated.",
extra_tags="alert alert-success")
kwargs = {
'imsi': imsi
}
return redirect(urlresolvers.reverse('subscriber-edit', kwargs=kwargs))
class ActivityView(ProtectedView):
"""View activity on the network."""
datepicker_time_format = '%Y-%m-%d at %I:%M%p'
def get(self, request, *args, **kwargs):
return self._handle_request(request)
def post(self, request, *args, **kwargs):
return self._handle_request(request)
def _handle_request(self, request):
"""Process request.
We want filters to persist even when someone changes pages without
re-submitting the form. Page changes will always come over a GET
request, not a POST.
- If it's a GET, we should try to pull settings from the session.
- If it's a POST, we should replace whatever is in the session.
- If it's a GET with no page, we should blank out the session.
"""
profile = UserProfile.objects.get(user=request.user)
network = profile.network
# Process parameters.
# We want filters to persist even when someone changes pages without
# re-submitting the form. Page changes will always come over a GET
# request, not a POST.
# - If it's a GET, we should try to pull settings from the session.
# - If it's a POST, we should replace whatever is in the session.
# - If it's a GET with no page variable, we should blank out the
# session.
if request.method == "POST":
page = 1
request.session['keyword'] = request.POST.get('keyword', None)
request.session['start_date'] = request.POST.get('start_date',
None)
request.session['end_date'] = request.POST.get('end_date', None)
request.session['services'] = request.POST.getlist('services[]',
None)
# Added to check password to download the csv
if (request.user.check_password(request.POST.get('password'))):
response = {'status': 'ok'}
return HttpResponse(json.dumps(response),
content_type="application/json")
# We always just do a redirect to GET. We include page reference
# to retain the search parameters in the session.
return redirect(urlresolvers.reverse('network-activity') +
"?page=1")
elif request.method == "GET":
page = request.GET.get('page', 1)
if 'page' not in request.GET:
# Reset filtering params.
request.session['keyword'] = None
request.session['start_date'] = None
request.session['end_date'] = None
request.session['services'] = None
else:
return HttpResponseBadRequest()
# Determine if there has been any activity on the network (if not, we
# won't show the filter boxes).
network_has_activity = UsageEvent.objects.filter(
network=network).exists()
# Read filtering params out of the session.
keyword = request.session['keyword']
start_date = request.session['start_date']
end_date = request.session['end_date']
services = request.session['services']
events = self._get_events(profile, keyword, start_date, end_date,
services)
event_count = events.count()
currency = CURRENCIES[network.subscriber_currency]
# If a CSV has been requested, return that here.
# TODO(shaddi): Kind of a hack, probably should be exposed as REST API
if request.method == "GET" and request.GET.get('csv', False):
headers = [
'Transaction ID',
'Day',
'Time',
'Time Zone',
'Subscriber IMSI',
'BTS Identifier',
'BTS Name',
'Type of Event',
'Description',
'From Number',
'To Number',
'Billable Call Duration (sec)',
'Total Call Duration (sec)',
'Tariff (%s)' % (currency,),
'Cost (%s)' % (currency,),
'Prior Balance (%s)' % (currency,),
'Final Balance (%s)' % (currency,),
'Bytes Uploaded',
'Bytes Downloaded',
]
response = HttpResponse(content_type='text/csv')
# TODO(shaddi): use a filename that captures the search terms?
response['Content-Disposition'] = ('attachment;filename='
'"etage-%s.csv"') \
% (datetime.datetime.now().date(),)
writer = csv.writer(response)
writer.writerow(headers)
# Forcibly limit to 7000 items.
timezone = pytz.timezone(profile.timezone)
for e in events[:7000]:
#first strip the IMSI off if present
subscriber = e.subscriber_imsi
if e.subscriber_imsi.startswith('IMSI'):
subscriber = e.subscriber_imsi[4:]
tz_date = django_utils_timezone.localtime(e.date, timezone)
writer.writerow([
e.transaction_id,
tz_date.date().strftime("%m-%d-%Y"),
tz_date.time().strftime("%I:%M:%S %p"),
timezone,
subscriber,
e.bts_uuid,
e.bts.nickname if e.bts else "<deleted BTS>",
e.kind,
e.reason,
e.from_number,
e.to_number,
e.billsec,
e.call_duration,
humanize_credits(e.tariff, currency=currency).amount_str()
if e.tariff else None,
humanize_credits(e.change, currency=currency).amount_str()
if e.change else None,
humanize_credits(e.oldamt, currency=currency).amount_str()
if e.oldamt else None,
humanize_credits(e.newamt, currency=currency).amount_str()
if e.newamt else None,
e.uploaded_bytes,
e.downloaded_bytes,
])
return response
# Otherwise, we paginate.
event_paginator = Paginator(events, 25)
try:
events = event_paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
events = event_paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 999), deliver last page of results.
events = event_paginator.page(event_paginator.num_pages)
# Setup the context for the template.
context = {
'networks': get_objects_for_user(request.user, 'view_network', klass=Network),
'currency': CURRENCIES[network.subscriber_currency],
'user_profile': profile,
'network_has_activity': network_has_activity,
'events': events,
'event_count': event_count,
}
# Setup various stuff for filter form generation.
service_names = ["SMS", "Call", "GPRS", "Transfer", "Other"]
if not services:
context['service_types'] = [
("SMS", True),
("Call", True),
("GPRS", True),
("Transfer", True),
("Other", True)
]
else:
context['service_types'] = []
for name in service_names:
if name.lower() in services:
context['service_types'].append((name, True))
else:
context['service_types'].append((name, False))
context['eventfilter'] = {
'keyword': keyword,
'start_date': start_date,
'end_date': end_date
}
template = get_template('dashboard/activity.html')
html = template.render(context, request)
return HttpResponse(html)
def _get_events(self, user_profile, query=None, start_date=None,
end_date=None, services=None):
network = user_profile.network
events = UsageEvent.objects.filter(
network=network).order_by('-date')
# If only one of these is | |
#!/usr/bin/env python3
# vim: set expandtab tabstop=4 shiftwidth=4:
# Copyright (c) 2021, <NAME>
# 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 the development team 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 CJ KUCERA 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.
import os
import re
import sys
import json
import yaml
import html
import enum
import lzma
import argparse
from PIL import Image
class Category:
"""
A category with multiple collections in it
"""
def __init__(self, label, collections=None):
self.label = label
if collections:
self.collections = collections
else:
self.collections = []
def __len__(self):
"""
Allows us to use `len(category_obj)`
"""
return len(self.collections)
def __iter__(self):
"""
Allows us to iterate over the object
"""
return iter(self.collections)
def append(self, new_collection):
self.collections.append(new_collection)
class Collection:
"""
A collection of screenshots which we'll display
"""
def __init__(self, slug, name_plural, name_single, base_dir, last_updated, contents=None, extra_text=None, grid=False):
self.slug = slug
self.name_plural = name_plural
self.name_single = name_single
self.base_dir = base_dir
self.last_updated = last_updated
self.extra_text = extra_text
self.grid = grid
if contents:
self.contents = contents
else:
self.contents = []
def __len__(self):
"""
Allows us to use `len(collection_obj)`
"""
return len(self.contents)
def __iter__(self):
"""
Allows us to iterate over the object
"""
return iter(self.contents)
def get_filename(self):
return os.path.join('_pages', f'{self.slug}.html')
class HostType(enum.Enum):
"""
For shots with URLs attached to 'em, what's the source of the URL? (We
may be able to do fancy things like specify host-side resizes, for instance.)
"""
NONE = enum.auto()
GOOGLE = enum.auto()
DROPBOX = enum.auto()
OTHER = enum.auto()
class Shot:
"""
A single screenshot, though possibly with some attached variants.
"""
def __init__(self, name, filename, label=None, url=None, order=None, variants=None):
self.name = name
self.filename = filename
self.base_dir = ''
self.label = label
self.order = order
self.parent = None
if variants:
self.variants = variants
for variant in variants:
variant.parent = self
else:
self.variants = []
# Process our URL (if we have one) -- some types are likely to have
# bits we can strip out to find the "base" URL, just for ease of
# copy+pasting
if url:
if 'googleusercontent.com' in url:
if '=' in url:
self.url_base = url.split('=')[0]
else:
self.url_base = url
self.url_type = HostType.GOOGLE
elif 'dropbox.com' in url:
if '?' in url:
url = url.split('?')[0]
self.url_base = f'{url}?raw=1'
self.url_type = HostType.DROPBOX
else:
self.url_base = url
self.url_type = HostType.OTHER
else:
self.url_type = HostType.NONE
self.url_base = None
def __lt__(self, other):
"""
Sorting -- Primary is the explicit `order` field. Objects with this
defined will go first. `name` is our secondary, and if only one of us has
it, the named object goes first. Tertiary is `label`, and if only one of
us has it, the one *without* the label goes first. Finally we fall back
to `filename`
"""
if self.order is not None and other.order is not None:
return self.order < other.order
elif self.order is not None:
return True
elif other.order is not None:
return False
else:
if self.name and other.name:
return self.name.lower() < other.name.lower()
elif self.name:
return True
elif other.name:
return False
else:
if self.label and other.label:
return self.label.lower() < other.label.lower()
elif self.label:
return False
elif other.label:
return True
else:
return self.filename.lower() < other.filename.lower()
@property
def anchor(self):
return re.sub(r'[^a-zA-Z0-9]', '-', self.name.lower())
def get_url(self, size):
"""
Returns a URL with extra sizing parameters, if the URL type supports it.
"""
if self.url_type == HostType.GOOGLE:
return '{}=w{}-h{}-no?authuser=0'.format(
self.url_base,
size[0],
size[1],
)
else:
return self.url_base
def output(self, odf, collection, base_img_href, thumb_size, urls=False, verbose=False):
# Gather sizing info for the main image, and do resizes (or set up
# serverside resizing URLs)
if verbose:
if self.name:
print(' - Processing {}'.format(self.name))
else:
print(' Processing Variant')
image_filename = os.path.join('img', collection.base_dir, self.filename)
img_width = thumb_size[0]
im = Image.open(image_filename)
if urls and self.url_type != HostType.NONE:
if im.width > thumb_size[0]:
href_thumb = self.get_url(thumb_size)
else:
href_thumb = self.get_url((im.width, im.height))
img_width = im.width
href_link = self.get_url((im.width, im.height))
else:
if im.width > thumb_size[0]:
img_base, img_ext = self.filename.rsplit('.', 1)
base_thumb = '{}-{}-{}.{}'.format(
img_base,
thumb_size[0],
thumb_size[1],
img_ext,
)
dir_thumb = os.path.join('thumbs', collection.base_dir)
full_thumb = os.path.join(dir_thumb, base_thumb)
if not os.path.exists(full_thumb):
if verbose:
print(' Generating thumbnail: {}'.format(full_thumb))
if not os.path.exists(dir_thumb):
os.makedirs(dir_thumb, exist_ok=True)
im.thumbnail(thumb_size)
im.save(full_thumb)
href_thumb = f'{base_img_href}/{full_thumb}'
else:
href_thumb = f'{base_img_href}/{image_filename}'
img_width = im.width
href_link = f'{base_img_href}/{image_filename}'
# Now output - first the header
if collection.grid:
print('<div class="grid-customization">', file=odf)
else:
print('<div class="customization">', file=odf)
# Now the data
if self.name:
print('<div class="title" id="{}">{}</div>'.format(
self.anchor,
html.escape(self.name),
), file=odf)
if self.name:
alt_text = self.name
elif self.parent:
alt_text = self.parent.name
if self.label:
alt_text = '{} - {}'.format(alt_text, self.label)
print('<a href="{}" class="image"><img src="{}" width="{}" alt="{}"></a>'.format(
href_link,
href_thumb,
img_width,
html.escape(alt_text, quote=True),
), file=odf)
if self.label:
print('<div class="extra">{}</div>'.format(
html.escape(self.label),
), file=odf)
# ... and footer.
print('</div>', file=odf)
print('', file=odf)
# Display variants
for variant in self.variants:
variant.output(odf, collection, base_img_href, thumb_size, urls, verbose)
class Variant(Shot):
"""
Just a stupid wrapper for variant shots which don't have a "name" of their own.
"""
def __init__(self, filename, label=None, url=None, order=None, variants=None):
super().__init__(None, filename, label=label, url=url, order=order, variants=variants)
# Our data!
char_heads = Category('Character Heads')
char_skins = Category('Character Skins')
other = Category('Other')
vehicles = Category('Vehicles')
categories = [char_heads, char_skins, other, vehicles]
###
### Our collections! First up:
### Heads
###
char_heads.append(Collection('char-heads-beastmaster',
'Beastmaster Heads',
'Beastmaster Head',
'char_heads/beastmaster',
'Nov 18, 2021',
[
Shot("4ction Figure", '4ction_figure.jpg'),
Shot("4NU Bust", '4nu_bust.jpg'),
Shot("Abyss4l", 'abyss4l.jpg'),
Shot("Anim4tronic", 'anim4tronic.jpg'),
Shot("Antisoci4l", 'antisoci4l.jpg'),
Shot("Barb4ric", 'barb4ric.jpg'),
Shot("Bird Collar", 'bird_collar.jpg'),
Shot("Bully for You", 'bully_for_you.jpg'),
Shot("C4tch A Ride", 'c4tch_a_ride.jpg'),
Shot("Camoufl4ge", 'camoufl4ge.jpg'),
Shot("Cr4cked", 'cr4cked.jpg'),
Shot("Daemon", 'daemon.jpg'),
Shot("De4thless", 'de4thless.jpg'),
Shot("Der4nged Ranger", 'der4nged_ranger.jpg'),
Shot("Desperado", 'desperado.jpg'),
Shot("Dre4dful Visage", 'dre4dful_visage.jpg'),
Shot("FL4K", 'fl4k.jpg', '(default head)', order=1),
Shot("FL4Kenstein's Monster", 'fl4kensteins_monster.jpg'),
Shot("Fr4kkin' Toaster", 'fr4kkin_toaster.jpg'),
Shot("Grand Archivist", 'grand_archivist.jpg'),
Shot("Gray Matter", 'gray_matter.jpg'),
Shot("Guardian", 'guardian.jpg'),
Shot("He4d in the Cloud", 'he4d_in_the_cloud.jpg'),
Shot("Hotline Pandora", 'hotline_pandora.jpg'),
Shot("Immort4l", 'immort4l.jpg'),
Shot("Inh4ler", 'inh4ler.jpg'),
Shot("Lance Helmet", 'lance_helmet.jpg'),
Shot("Lumin4ry", 'lumin4ry.jpg'),
Shot("<NAME>", 'm4nta_ray.jpg'),
Shot("<NAME>", 'marcus_bobble.jpg'),
Shot("Mendic4nt", 'mendic4nt.jpg'),
Shot("Neon Predator", 'neon_predator.jpg'),
Shot("NOG Mask", 'nog_mask.jpg'),
Shot("Null Value", 'null_value.jpg'),
Shot("Pony Up", 'pony_up.jpg'),
Shot("Ratch Rider", 'ratch_rider.jpg'),
Shot("Roll Player", 'roll_player.jpg'),
Shot("Roy4lty", 'roy4lty.jpg'),
Shot("Saurian Synth", 'saurian_synth.jpg'),
Shot("Sh4man", 'sh4man.jpg'),
Shot("Simul4crum", 'simul4crum.jpg'),
Shot("Skagwave", 'skagwave.jpg'),
Shot("Skull and Domes", 'skull_and_domes.jpg'),
Shot("Skull Pl4te", 'skull_pl4te.jpg'),
Shot("Spiderpunk", 'spiderpunk.jpg'),
Shot("Str4nger", 'str4nger.jpg'),
Shot("THE H4RBINGER", 'the_h4rbinger.jpg'),
Shot("Tough Scruff", 'tough_scruff.jpg'),
Shot("Tuned and Doomed", 'tuned_and_doomed.jpg'),
Shot("Ultra Mecha", 'ultra_mecha.jpg'),
Shot("Yok4i", 'yok4i.jpg'),
]))
char_heads.append(Collection('char-heads-gunner',
'Gunner Heads',
'Gunner Head',
'char_heads/gunner',
'Nov 18, 2021',
[
Shot("Antisocial", 'antisocial.jpg'),
Shot("Bird Collar", 'bird_collar.jpg'),
Shot("Black Eye", 'black_eye.jpg'),
Shot("Bull Mozer", 'bull_mozer.jpg'),
Shot("Bully for You", 'bully_for_you.jpg'),
Shot("Commissar Andreyevna", 'commissar_andreyevna.jpg'),
Shot("Conqueror", 'conqueror.jpg'),
Shot("Cy-Ops", 'cy-ops.jpg'),
Shot("Daemon", 'daemon.jpg'),
Shot("Desperado", 'desperado.jpg'),
Shot("Diesel Punk", 'diesel_punk.jpg'),
Shot("Disengaged", 'disengaged.jpg'),
Shot("Dragon's Crest", 'dragons_crest.jpg'),
Shot("Eyes on Target", 'eyes_on_target.jpg'),
Shot("Fresh to Death", 'fresh_to_death.jpg'),
Shot("Fuel Metal", 'fuel_metal.jpg'),
Shot("Gray Matter", 'gray_matter.jpg'),
Shot("Guardian", 'guardian.jpg'),
Shot("Hotline Pandora", 'hotline_pandora.jpg'),
Shot("Insulation", 'insulation.jpg'),
Shot("Iron Baron", 'iron_baron.jpg'),
Shot("Knight Watch", 'knight_watch.jpg'),
Shot("Lance Helmet", 'lance_helmet.jpg'),
Shot("Mad Moze", 'mad_moze.jpg'),
Shot("<NAME>", 'marcus_bobble.jpg'),
Shot("Meowze", 'meowze.jpg'),
Shot("Moze", 'moze.jpg', '(default head)', order=1),
Shot("Mozo", 'mozo.jpg'),
Shot("Neon Charger", 'neon_charger.jpg'),
Shot("NOG Mask", 'nog_mask.jpg'),
Shot("Null Value", 'null_value.jpg'),
Shot("Outlaw", 'outlaw.jpg'),
Shot("Pilot Punk", 'pilot_punk.jpg'),
Shot("Pony Up", 'pony_up.jpg'),
Shot("Ratch Rider", 'ratch_rider.jpg'),
Shot("Roll Player", 'roll_player.jpg'),
Shot("Saint of Iron", 'saint_of_iron.jpg'),
Shot("Saurian Synth", 'saurian_synth.jpg'),
Shot("Shark Tank", 'shark_tank.jpg'),
Shot("Skagwave", 'skagwave.jpg'),
Shot("Skull and Domes", 'skull_and_domes.jpg'),
Shot("Spark of Genius", 'spark_of_genius.jpg'),
Shot("Spiderpunk", 'spiderpunk.jpg'),
Shot("Strange Angles", 'strange_angles.jpg'),
Shot("Swooper Trooper", 'swooper_trooper.jpg'),
Shot("The Garish Gunner", 'the_garish_gunner.jpg'),
Shot("Tough Scruff", 'tough_scruff.jpg'),
| |
<reponame>Di-Weng/emotion_classification_blstm
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/7/1 0:32
# @Author : MengnanChen
# @Site :
# @File : audioFeatureExtraction.py
# @Software: PyCharm Community Edition
import numpy
from scipy.fftpack.basic import _fftpack
from scipy.fftpack.basic import _asfarray
from scipy.fftpack.basic import _DTYPE_TO_FFT
from scipy.fftpack.basic import istype
from scipy.fftpack.basic import _datacopied
from scipy.fftpack.basic import _fix_shape
from scipy.fftpack.basic import swapaxes
eps = 0.00000001
def __fix_shape(x, n, axis, dct_or_dst):
tmp = _asfarray(x)
copy_made = _datacopied(tmp, x)
if n is None:
n = tmp.shape[axis]
elif n != tmp.shape[axis]:
tmp, copy_made2 = _fix_shape(tmp, n, axis)
copy_made = copy_made or copy_made2
if n < 1:
raise ValueError("Invalid number of %s data points "
"(%d) specified." % (dct_or_dst, n))
return tmp, n, copy_made
def stChromaFeaturesInit(nfft, fs):
nfft=int(nfft)
"""
This function initializes the chroma matrices used in the calculation of the chroma features
"""
freqs = numpy.array([((f + 1) * fs) / (2 * nfft) for f in range(nfft)])
Cp = 27.50
nChroma = numpy.round(12.0 * numpy.log2(freqs / Cp)).astype(int)
nFreqsPerChroma = numpy.zeros((nChroma.shape[0],))
uChroma = numpy.unique(nChroma)
for u in uChroma:
idx = numpy.nonzero(nChroma == u)
nFreqsPerChroma[idx] = idx[0].shape
return nChroma, nFreqsPerChroma
def mfccInitFilterBanks(fs, nfft):
"""
Computes the triangular filterbank for MFCC computation (used in the stFeatureExtraction function before the stMFCC function call)
This function is taken from the scikits.talkbox library (MIT Licence):
https://pypi.python.org/pypi/scikits.talkbox
"""
# filter bank params:
lowfreq = 133.33
linsc = 200/3.
logsc = 1.0711703
numLinFiltTotal = 13
numLogFilt = 27
if fs < 8000:
nlogfil = 5
# Total number of filters
nFiltTotal = numLinFiltTotal + numLogFilt
# Compute frequency points of the triangle:
freqs = numpy.zeros(nFiltTotal+2)
freqs[:numLinFiltTotal] = lowfreq + numpy.arange(numLinFiltTotal) * linsc
freqs[numLinFiltTotal:] = freqs[numLinFiltTotal-1] * logsc ** numpy.arange(1, numLogFilt + 3)
heights = 2./(freqs[2:] - freqs[0:-2])
# Compute filterbank coeff (in fft domain, in bins)
fbank = numpy.zeros((int(nFiltTotal), int(nfft)))
nfreqs = numpy.arange(nfft) / (1. * nfft) * fs
for i in range(nFiltTotal):
lowTrFreq = freqs[i]
cenTrFreq = freqs[i+1]
highTrFreq = freqs[i+2]
lid = numpy.arange(numpy.floor(lowTrFreq * nfft / fs) + 1, numpy.floor(cenTrFreq * nfft / fs) + 1, dtype=numpy.int)
lslope = heights[i] / (cenTrFreq - lowTrFreq)
rid = numpy.arange(numpy.floor(cenTrFreq * nfft / fs) + 1, numpy.floor(highTrFreq * nfft / fs) + 1, dtype=numpy.int)
rslope = heights[i] / (highTrFreq - cenTrFreq)
fbank[i][lid] = lslope * (nfreqs[lid] - lowTrFreq)
fbank[i][rid] = rslope * (highTrFreq - nfreqs[rid])
return fbank, freqs
def stZCR(frame):
"""Computes zero crossing rate of frame"""
count = len(frame)
countZ = numpy.sum(numpy.abs(numpy.diff(numpy.sign(frame)))) / 2
return (numpy.float64(countZ) / numpy.float64(count-1.0))
def stEnergy(frame):
"""Computes signal energy of frame"""
return numpy.sum(frame ** 2) / numpy.float64(len(frame))
def stEnergyEntropy(frame, numOfShortBlocks=10):
"""Computes entropy of energy"""
Eol = numpy.sum(frame ** 2) # total frame energy
L = len(frame)
subWinLength = int(numpy.floor(L / numOfShortBlocks))
if L != subWinLength * numOfShortBlocks:
frame = frame[0:subWinLength * numOfShortBlocks]
# subWindows is of size [numOfShortBlocks x L]
subWindows = frame.reshape(subWinLength, numOfShortBlocks, order='F').copy()
# Compute normalized sub-frame energies:
s = numpy.sum(subWindows ** 2, axis=0) / (Eol + eps)
# Compute entropy of the normalized sub-frame energies:
Entropy = -numpy.sum(s * numpy.log2(s + eps))
return Entropy
def stSpectralCentroidAndSpread(X, fs):
"""Computes spectral centroid of frame (given abs(FFT))"""
ind = (numpy.arange(1, len(X) + 1)) * (fs/(2.0 * len(X)))
Xt = X.copy()
Xt = Xt / Xt.max()
NUM = numpy.sum(ind * Xt)
DEN = numpy.sum(Xt) + eps
# Centroid:
C = (NUM / DEN)
# Spread:
S = numpy.sqrt(numpy.sum(((ind - C) ** 2) * Xt) / DEN)
# Normalize:
C = C / (fs / 2.0)
S = S / (fs / 2.0)
return (C, S)
def stSpectralEntropy(X, numOfShortBlocks=10):
"""Computes the spectral entropy"""
L = len(X) # number of frame samples
Eol = numpy.sum(X ** 2) # total spectral energy
subWinLength = int(numpy.floor(L / numOfShortBlocks)) # length of sub-frame
if L != subWinLength * numOfShortBlocks:
X = X[0:subWinLength * numOfShortBlocks]
subWindows = X.reshape(subWinLength, numOfShortBlocks, order='F').copy() # define sub-frames (using matrix reshape)
s = numpy.sum(subWindows ** 2, axis=0) / (Eol + eps) # compute spectral sub-energies
En = -numpy.sum(s*numpy.log2(s + eps)) # compute spectral entropy
return En
def stSpectralFlux(X, Xprev):
"""
Computes the spectral flux feature of the current frame
ARGUMENTS:
X: the abs(fft) of the current frame
Xpre: the abs(fft) of the previous frame
"""
# compute the spectral flux as the sum of square distances:
sumX = numpy.sum(X + eps)
sumPrevX = numpy.sum(Xprev + eps)
F = numpy.sum((X / sumX - Xprev/sumPrevX) ** 2)
return F
def stSpectralRollOff(X, c, fs):
"""Computes spectral roll-off"""
totalEnergy = numpy.sum(X ** 2)
fftLength = len(X)
Thres = c*totalEnergy
# Ffind the spectral rolloff as the frequency position where the respective spectral energy is equal to c*totalEnergy
CumSum = numpy.cumsum(X ** 2) + eps
[a, ] = numpy.nonzero(CumSum > Thres)
if len(a) > 0:
mC = numpy.float64(a[0]) / (float(fftLength))
else:
mC = 0.0
return (mC)
def fft(x, n=None, axis=-1, overwrite_x=False):
"""
Return discrete Fourier transform of real or complex sequence.
The returned complex array contains ``y(0), y(1),..., y(n-1)`` where
``y(j) = (x * exp(-2*pi*sqrt(-1)*j*np.arange(n)/n)).sum()``.
Parameters
----------
x : array_like
Array to Fourier transform.
n : int, optional
Length of the Fourier transform. If ``n < x.shape[axis]``, `x` is
truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
default results in ``n = x.shape[axis]``.
axis : int, optional
Axis along which the fft's are computed; the default is over the
last axis (i.e., ``axis=-1``).
overwrite_x : bool, optional
If True, the contents of `x` can be destroyed; the default is False.
Returns
-------
z : complex ndarray
with the elements::
[y(0),y(1),..,y(n/2),y(1-n/2),...,y(-1)] if n is even
[y(0),y(1),..,y((n-1)/2),y(-(n-1)/2),...,y(-1)] if n is odd
where::
y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k* 2*pi/n), j = 0..n-1
See Also
--------
ifft : Inverse FFT
rfft : FFT of a real sequence
Notes
-----
The packing of the result is "standard": If ``A = fft(a, n)``, then
``A[0]`` contains the zero-frequency term, ``A[1:n/2]`` contains the
positive-frequency terms, and ``A[n/2:]`` contains the negative-frequency
terms, in order of decreasingly negative frequency. So for an 8-point
transform, the frequencies of the result are [0, 1, 2, 3, -4, -3, -2, -1].
To rearrange the fft output so that the zero-frequency component is
centered, like [-4, -3, -2, -1, 0, 1, 2, 3], use `fftshift`.
Both single and double precision routines are implemented. Half precision
inputs will be converted to single precision. Non floating-point inputs
will be converted to double precision. Long-double precision inputs are
not supported.
This function is most efficient when `n` is a power of two, and least
efficient when `n` is prime.
Note that if ``x`` is real-valued then ``A[j] == A[n-j].conjugate()``.
If ``x`` is real-valued and ``n`` is even then ``A[n/2]`` is real.
If the data type of `x` is real, a "real FFT" algorithm is automatically
used, which roughly halves the computation time. To increase efficiency
a little further, use `rfft`, which does the same calculation, but only
outputs half of the symmetrical spectrum. If the data is both real and
symmetrical, the `dct` can again double the efficiency, by generating
half of the spectrum from half of the signal.
Examples
--------
# >>> from scipy.fftpack import fft, ifft
# >>> x = np.arange(5)
# >>> np.allclose(fft(ifft(x)), x, atol=1e-15) # within numerical accuracy.
True
"""
tmp = _asfarray(x)
try:
work_function = _DTYPE_TO_FFT[tmp.dtype]
except KeyError:
raise ValueError("type %s is not supported" % tmp.dtype)
if not (istype(tmp, numpy.complex64) or istype(tmp, numpy.complex128)):
overwrite_x = 1
overwrite_x = overwrite_x or _datacopied(tmp, x)
if n is None:
n = tmp.shape[axis]
elif n != tmp.shape[axis]:
tmp, copy_made = _fix_shape(tmp,n,axis)
overwrite_x = overwrite_x or copy_made
if n < 1:
raise ValueError("Invalid number of FFT data points "
"(%d) specified." % n)
if axis == -1 or axis == len(tmp.shape) - 1:
return work_function(tmp,n,1,0,overwrite_x)
tmp = swapaxes(tmp, axis, -1)
tmp = work_function(tmp,n,1,0,overwrite_x)
return swapaxes(tmp, axis, -1)
def _get_norm_mode(normalize):
try:
nm = {None:0, 'ortho':1}[normalize]
except KeyError:
raise ValueError("Unknown normalize mode %s" % normalize)
return nm
def _get_dct_fun(type, dtype):
try:
name = {'float64':'ddct%d', 'float32':'dct%d'}[dtype.name]
except KeyError:
raise ValueError("dtype %s not supported" % dtype)
try:
f = getattr(_fftpack, name % type)
| |
<filename>reanatempl/util/template/base.py
# Copyright (C) 2019 New York University.
#
# This file is part of REANA Templates. REANA Templates is free software; you
# can redistribute it and/or modify it under the terms of the MIT License; see
# LICENSE file for more details.
"""The workflow template handle provides access to a parameterized REANA
workflow. Parameterized workflows are usually under the control of a template
store. The handle provides access to the workflow template, and the fixed
workflow files. It also provides space to upload files for individual runs
(instantiations) of the workflow template.
"""
import git
import json
import os
import shutil
from reanatempl.base import TemplateSpec
from reanatempl.util.base import get_short_identifier, read_object, write_object
from reanatempl.util.base import FORMAT_JSON
"""Constants for labels in workflow template metadata files."""
REANA_SERVER_URL = 'serverUrl'
REANA_ACCESS_TOKEN = 'accessToken'
"""Names of subfolders and files in the template handle directory."""
SETTINGS_FILE = '.settings'
WORKFLOW_FOLDER = 'workflow'
"""Labels for elements in the settings object that is stored on disk.
"""
LABEL_BACKEND = 'backend'
LABEL_DESCRIPTION = 'description'
LABEL_ID = 'id'
LABEL_NAME = 'name'
LABEL_TEMPLATE = 'template'
class TemplateHandle(object):
"""Reference to a REANA workflow template specification and any resources
(e.g., fixed files) that are associated with the template. This handle
allows users to create a running instance of the workflow specification
for a template on a REANA backend.
The workflow instances are referred to as runs. It is necessary to allow
multiple runs to be associated with a workflow template in parallel in case
there are multiple users that attempt to execute the workflow template at
the same time.
Template handles are usually maintained in a template store. For the purpose
of identification each template in the store has a unique identifier and
and optional descriptive name. There might also be a longer, more
comprehensive description associated with the template that can be used
to describe the activities of the workflow to a user.
This is an abstract class that is independent of the method that is used to
store and maintain workflow templates and their associated files.
"""
def __init__(
self, identifier, directory, template, name=None, description=None,
run_id_func=None
):
"""Initialize the unique template identifier, the descriptive template
name and the optional comprehensive template description.
Parameters
----------
identifier: string
Unique template identifier
directory: string
Path to template directory containing workflow and run folders
template: reanatempl.TemplateSpec
Workflow template spacification
name: string, optional
Descriptive template name
description: string, optional
Comprehensive description explaining the workflow computations to
a user
run_id_func: func, optional
Function to create unique run identifier. By default short identifer
are used.
"""
self.identifier = identifier
self.directory = os.path.abspath(directory)
self.template = template
self.name = name if not name is None else identifier
self.description = description
self.run_id_func = run_id_func if not run_id_func is None else get_short_identifier
@staticmethod
def create(
identifier=None, name=None, description=None, backend=None,
in_directory='.', workflow_dir=None, workflow_repo_url=None,
template_spec_file=None, id_func=get_short_identifier, max_attempts=100
):
"""Create file and folder structure for a new workflow template handle
in the given base directoy (in_directory). Assumes that either a
workflow directory or the Url of a remote Git repository is given.
Creates a new folder with unique name in the given base directory. The
folder will contain the .settings file that contains the handle metadata
and the template specification. The template specification is expected
to be contained in the given workflow directory or repository. If the
template_spec file is not given the method will look for a file with the
following name in the workflow directory (in the given order):
- reana-template.yml
- reana-template.yaml
- reana_template.yml
- reana_template.yaml
- template.yml
- template.yaml
- workflow.yml
- workflow.yaml
If none of the above files exist in the workflow directory a ValueError
is raised. The contents of the workflow directory will be copied to the
new template handle directory (as subfolder workflow). The template
directory will also contain a subfolder runs. With in the runs folder
subfolders for individual runs containing uploaded files will be created
when the user creates a new run.
Parameters
----------
identifier: string, optional
Unique identifier for template. If not given a UUID is generated.
name: string, optional
Descriptive name for the template (default is identifier)
description: string, optional
Comprehensive description of template workflow
backend: dict, optional
Optional specification of REANA server that is used to run workflow
instances
in_directory: string, optional
Base directory in which the template folder is created
(default is '.')
workflow_dir: string, optional
Directory containing the REANA workflow components, i.e., the fixed
files and the template specification (optional).
workflow_repo_url: string, optional
Git repository that contains the the REANA workflow components
template_spec_file: string, optional
Path to the workflow template specification file (absolute or
relative to the workflow directory)
id_func: func
Function to generate template folder identifier
max_attempts: int, optional
Maximum number of attempts to create a unique template folder
Returns
-------
reanatempl.util.template.base.TemplateHandle
"""
# Exactly one of workflow_directory and workflow_repo_url has to be not
# None. If both are None (or not None) a ValueError is raised.
if workflow_dir is None and workflow_repo_url is None:
raise ValueError('both \'workflow_dir\' and \'workflow_repo_url\' are missing')
elif not workflow_dir is None and not workflow_repo_url is None:
raise ValueError('cannot have both \'workflow_dir\' and \'workflow_repo_url\'')
# Validate backend dictionary if given
if not backend is None:
if len(backend) != 2:
raise ValueError('invalid backend specification')
for key in [REANA_SERVER_URL, REANA_ACCESS_TOKEN]:
if not key in backend:
raise ValueError('invalid backend specification')
# Use the given identifier function to create a new subfolder in the
# in_directory. First make sure that the directory exists.
if not os.path.isdir(in_directory):
raise ValueError('base directory \'' + str(in_directory) + '\' does not exist or is not a directory')
# Create a new unique folder for the template resources
folder_id, templ_dir = create_dir(
in_directory,
id_func=id_func,
max_attempts=max_attempts
)
# Use folder_id as identifier of no identifier was given
if identifier is None:
identifier = folder_id
# Use identifier as name if no name is given
if name is None:
name = identifier
try:
# Copy either the given workflow directory into the created template
# folder or clone the Git repository.
templ_wf_dir = os.path.join(templ_dir, WORKFLOW_FOLDER)
if not workflow_dir is None:
shutil.copytree(src=workflow_dir, dst=templ_wf_dir)
else:
git.Repo.clone_from(workflow_repo_url, templ_wf_dir)
# Find template specification file in the template workflow folder.
# If the file is not found the template directory is removed and a
# ValueError is raised.
template = read_template_file(
directory=templ_wf_dir,
filename=template_spec_file
)
except (IOError, OSError, ValueError) as ex:
# Make sure to cleanup by removing the created template folder
shutil.rmtree(templ_dir)
raise ValueError(ex)
# Write settings file
settings = {
LABEL_ID: identifier,
LABEL_NAME: name,
LABEL_TEMPLATE: template.to_dict()
}
if not description is None:
settings[LABEL_DESCRIPTION] = description
if not backend is None:
settings[LABEL_BACKEND] = backend
settings_file = os.path.join(templ_dir, SETTINGS_FILE)
write_object(settings_file, settings, format=FORMAT_JSON)
# Return handle
return TemplateHandle(
identifier=identifier,
name=name,
description=description,
template=template,
directory=templ_dir
)
def get_template_spec(self):
"""Get the REANA workflow template specification that is associated with
this object.
Returns
-------
reanatempl.TemplateSpec
"""
return self.template
@staticmethod
def load(directory):
"""Load parameterized workflow information from disk. Expects a
directory that contains at least the SETTINSG_FILE and WORKFLOW_FOLDER.
Parameters
----------
directory: string
Path to the base directory containing the template information
Returns
-------
reanatempl.util.template.base.TemplateHandle
"""
# Raise exception if the given argument is not a directory
if not os.path.isdir(directory):
raise ValueError('not a directory \'' + str(directory) + '\'')
# Raise an exception if the directory does not contain a SETTINGS_FILE
settings_file = os.path.join(directory, SETTINGS_FILE)
if not os.path.isfile(settings_file):
raise ValueError('missing file \'' + SETTINGS_FILE + '\'')
# Load template information from settings file. Will raise a ValueError
# if the file format is invalid.
obj = read_object(settings_file, format=FORMAT_JSON)
identifier = obj[LABEL_ID]
name = obj[LABEL_NAME]
description = None
if LABEL_DESCRIPTION in obj:
description = obj[LABEL_DESCRIPTION]
return TemplateHandle(
identifier=identifier,
name=name,
description=description,
template=TemplateSpec.from_dict(obj[LABEL_TEMPLATE]),
directory=directory
)
# ------------------------------------------------------------------------------
# Helper Methods
# ------------------------------------------------------------------------------
def BACKEND(serverUrl, accessToken):
"""Helper method to create a backend dictionary for creating a new template
handle. Expects a serverUrl for the REANA server API and the access token.
Raises ValueError if either of the given parameter is None.
Parameters
----------
serverUrl: String
Url of the REANA server API
accessToken: string
Access token for the REANA | |
future
- the `start_at` or `end_at` overlaps another shift for the same
employee
- If `Break`s are set in the request, a break `start_at`
must not be before the `Shift.start_at`. A break `end_at` must not be
after
the `Shift.end_at`
Args:
body (CreateShiftRequest): An object containing the fields to POST
for the request. See the corresponding object definition for
field details.
Returns:
CreateShiftResponse: Response from the API. Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
# Prepare query URL
_url_path = '/v2/labor/shifts'
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
_headers = {
'accept': 'application/json',
'content-type': 'application/json; charset=utf-8'
}
# Prepare and execute request
_request = self.config.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body))
OAuth2.apply(self.config, _request)
_response = self.execute_request(_request)
decoded = APIHelper.json_deserialize(_response.text)
if type(decoded) is dict:
_errors = decoded.get('errors')
else:
_errors = None
_result = ApiResponse(_response, body=decoded, errors=_errors)
return _result
def search_shifts(self,
body):
"""Does a POST request to /v2/labor/shifts/search.
Returns a paginated list of `Shift` records for a business.
The list to be returned can be filtered by:
- Location IDs **and**
- employee IDs **and**
- shift status (`OPEN`, `CLOSED`) **and**
- shift start **and**
- shift end **and**
- work day details
The list can be sorted by:
- `start_at`
- `end_at`
- `created_at`
- `updated_at`
Args:
body (SearchShiftsRequest): An object containing the fields to
POST for the request. See the corresponding object definition
for field details.
Returns:
SearchShiftsResponse: Response from the API. Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
# Prepare query URL
_url_path = '/v2/labor/shifts/search'
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
_headers = {
'accept': 'application/json',
'content-type': 'application/json; charset=utf-8'
}
# Prepare and execute request
_request = self.config.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body))
OAuth2.apply(self.config, _request)
_response = self.execute_request(_request)
decoded = APIHelper.json_deserialize(_response.text)
if type(decoded) is dict:
_errors = decoded.get('errors')
else:
_errors = None
_result = ApiResponse(_response, body=decoded, errors=_errors)
return _result
def delete_shift(self,
id):
"""Does a DELETE request to /v2/labor/shifts/{id}.
Deletes a `Shift`.
Args:
id (string): UUID for the `Shift` being deleted.
Returns:
DeleteShiftResponse: Response from the API. Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
# Prepare query URL
_url_path = '/v2/labor/shifts/{id}'
_url_path = APIHelper.append_url_with_template_parameters(_url_path, {
'id': id
})
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
_headers = {
'accept': 'application/json'
}
# Prepare and execute request
_request = self.config.http_client.delete(_query_url, headers=_headers)
OAuth2.apply(self.config, _request)
_response = self.execute_request(_request)
decoded = APIHelper.json_deserialize(_response.text)
if type(decoded) is dict:
_errors = decoded.get('errors')
else:
_errors = None
_result = ApiResponse(_response, body=decoded, errors=_errors)
return _result
def get_shift(self,
id):
"""Does a GET request to /v2/labor/shifts/{id}.
Returns a single `Shift` specified by id.
Args:
id (string): UUID for the `Shift` being retrieved.
Returns:
GetShiftResponse: Response from the API. Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
# Prepare query URL
_url_path = '/v2/labor/shifts/{id}'
_url_path = APIHelper.append_url_with_template_parameters(_url_path, {
'id': id
})
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
_headers = {
'accept': 'application/json'
}
# Prepare and execute request
_request = self.config.http_client.get(_query_url, headers=_headers)
OAuth2.apply(self.config, _request)
_response = self.execute_request(_request)
decoded = APIHelper.json_deserialize(_response.text)
if type(decoded) is dict:
_errors = decoded.get('errors')
else:
_errors = None
_result = ApiResponse(_response, body=decoded, errors=_errors)
return _result
def update_shift(self,
id,
body):
"""Does a PUT request to /v2/labor/shifts/{id}.
Updates an existing `Shift`.
When adding a `Break` to a `Shift`, any earlier `Breaks` in the
`Shift` have
the `end_at` property set to a valid RFC-3339 datetime string.
When closing a `Shift`, all `Break` instances in the shift must be
complete with `end_at`
set on each `Break`.
Args:
id (string): ID of the object being updated.
body (UpdateShiftRequest): An object containing the fields to POST
for the request. See the corresponding object definition for
field details.
Returns:
UpdateShiftResponse: Response from the API. Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
# Prepare query URL
_url_path = '/v2/labor/shifts/{id}'
_url_path = APIHelper.append_url_with_template_parameters(_url_path, {
'id': id
})
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
_headers = {
'accept': 'application/json',
'content-type': 'application/json; charset=utf-8'
}
# Prepare and execute request
_request = self.config.http_client.put(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body))
OAuth2.apply(self.config, _request)
_response = self.execute_request(_request)
decoded = APIHelper.json_deserialize(_response.text)
if type(decoded) is dict:
_errors = decoded.get('errors')
else:
_errors = None
_result = ApiResponse(_response, body=decoded, errors=_errors)
return _result
def list_team_member_wages(self,
team_member_id=None,
limit=None,
cursor=None):
"""Does a GET request to /v2/labor/team-member-wages.
Returns a paginated list of `TeamMemberWage` instances for a
business.
Args:
team_member_id (string, optional): Filter wages returned to only
those that are associated with the specified team member.
limit (int, optional): Maximum number of Team Member Wages to
return per page. Can range between 1 and 200. The default is
the maximum at 200.
cursor (string, optional): Pointer to the next page of Employee
Wage results to fetch.
Returns:
ListTeamMemberWagesResponse: Response from the API. Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
# Prepare query URL
_url_path = '/v2/labor/team-member-wages'
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_parameters = {
'team_member_id': team_member_id,
'limit': limit,
'cursor': cursor
}
_query_builder = APIHelper.append_url_with_query_parameters(
_query_builder,
_query_parameters
)
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
_headers = {
'accept': 'application/json'
}
# Prepare and execute request
_request = self.config.http_client.get(_query_url, headers=_headers)
OAuth2.apply(self.config, _request)
_response = self.execute_request(_request)
decoded = APIHelper.json_deserialize(_response.text)
if type(decoded) is dict:
_errors = decoded.get('errors')
else:
_errors = None
_result = ApiResponse(_response, body=decoded, errors=_errors)
return _result
def get_team_member_wage(self,
id):
"""Does a GET request to /v2/labor/team-member-wages/{id}.
Returns a single `TeamMemberWage` specified by id.
Args:
id (string): UUID for the `TeamMemberWage` being retrieved.
Returns:
GetTeamMemberWageResponse: Response from the API. Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
# Prepare query URL
_url_path = '/v2/labor/team-member-wages/{id}'
_url_path = APIHelper.append_url_with_template_parameters(_url_path, {
'id': id
})
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
_headers = {
'accept': 'application/json'
}
# Prepare and execute request
_request = self.config.http_client.get(_query_url, headers=_headers)
OAuth2.apply(self.config, _request)
_response = self.execute_request(_request)
decoded = APIHelper.json_deserialize(_response.text)
if type(decoded) is dict:
_errors = decoded.get('errors')
else:
_errors = None
_result = ApiResponse(_response, body=decoded, errors=_errors)
return _result
def list_workweek_configs(self,
limit=None,
cursor=None):
"""Does a GET request to /v2/labor/workweek-configs.
Returns a list of `WorkweekConfig` instances for a business.
Args:
limit (int, optional): Maximum number of Workweek Configs to
return per page.
cursor (string, optional): Pointer to the next page of Workweek
Config results to fetch.
Returns:
ListWorkweekConfigsResponse: Response from the API. Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
# Prepare query URL
_url_path = '/v2/labor/workweek-configs'
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_parameters = {
'limit': limit,
'cursor': cursor
}
_query_builder = APIHelper.append_url_with_query_parameters(
_query_builder,
_query_parameters
)
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
_headers = {
'accept': | |
import numpy as np
import torch
import yaml
def convert_to_yolo_labels(bbox, S, B, number_of_classes=20):
label = torch.zeros((S, S, (5 * B + number_of_classes)))
for box in bbox:
x, y, w, h, c = box
x_idx = int(x * S)
y_idx = int(y * S)
x_cell = (x * S) - int(x * S)
y_cell = (y * S) - int(y * S)
w, h = w * S, h * S
label[x_idx, y_idx, 0: 5] = torch.tensor([x_cell, y_cell, w, h, 1])
label[x_idx, y_idx, 5: 10] = torch.tensor([x_cell, y_cell, w, h, 1])
label[x_idx, y_idx, 10 + c] = 1
return label
import torch
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from collections import Counter
def intersection_over_union(boxes_preds, boxes_labels, box_format="midpoint"):
"""
Calculates intersection over union
Parameters:
boxes_preds (tensor): Predictions of Bounding Boxes (BATCH_SIZE, 4)
boxes_labels (tensor): Correct labels of Bounding Boxes (BATCH_SIZE, 4)
box_format (str): midpoint/corners, if boxes (x,y,w,h) or (x1,y1,x2,y2)
Returns:
tensor: Intersection over union for all examples
"""
if box_format == "midpoint":
box1_x1 = boxes_preds[..., 0:1] - boxes_preds[..., 2:3] / 2
box1_y1 = boxes_preds[..., 1:2] - boxes_preds[..., 3:4] / 2
box1_x2 = boxes_preds[..., 0:1] + boxes_preds[..., 2:3] / 2
box1_y2 = boxes_preds[..., 1:2] + boxes_preds[..., 3:4] / 2
box2_x1 = boxes_labels[..., 0:1] - boxes_labels[..., 2:3] / 2
box2_y1 = boxes_labels[..., 1:2] - boxes_labels[..., 3:4] / 2
box2_x2 = boxes_labels[..., 0:1] + boxes_labels[..., 2:3] / 2
box2_y2 = boxes_labels[..., 1:2] + boxes_labels[..., 3:4] / 2
if box_format == "corners":
box1_x1 = boxes_preds[..., 0:1]
box1_y1 = boxes_preds[..., 1:2]
box1_x2 = boxes_preds[..., 2:3]
box1_y2 = boxes_preds[..., 3:4] # (N, 1)
box2_x1 = boxes_labels[..., 0:1]
box2_y1 = boxes_labels[..., 1:2]
box2_x2 = boxes_labels[..., 2:3]
box2_y2 = boxes_labels[..., 3:4]
x1 = torch.max(box1_x1, box2_x1)
y1 = torch.max(box1_y1, box2_y1)
x2 = torch.min(box1_x2, box2_x2)
y2 = torch.min(box1_y2, box2_y2)
# .clamp(0) is for the case when they do not intersect
intersection = (x2 - x1).clamp(0) * (y2 - y1).clamp(0)
box1_area = abs((box1_x2 - box1_x1) * (box1_y2 - box1_y1))
box2_area = abs((box2_x2 - box2_x1) * (box2_y2 - box2_y1))
return intersection / (box1_area + box2_area - intersection + 1e-6)
def non_max_suppression(bboxes, iou_threshold, threshold, box_format="corners"):
"""
Does Non Max Suppression given bboxes
Parameters:
bboxes (list): list of lists containing all bboxes with each bboxes
specified as [class_pred, prob_score, x1, y1, x2, y2]
iou_threshold (float): threshold where predicted bboxes is correct
threshold (float): threshold to remove predicted bboxes (independent of IoU)
box_format (str): "midpoint" or "corners" used to specify bboxes
Returns:
list: bboxes after performing NMS given a specific IoU threshold
"""
assert type(bboxes) == list
bboxes = [box for box in bboxes if box[1] > threshold]
bboxes = sorted(bboxes, key=lambda x: x[1], reverse=True)
bboxes_after_nms = []
while bboxes:
chosen_box = bboxes.pop(0)
bboxes = [
box
for box in bboxes
if box[0] != chosen_box[0]
or intersection_over_union(
torch.tensor(chosen_box[2:]),
torch.tensor(box[2:]),
box_format=box_format,
)
< iou_threshold
]
bboxes_after_nms.append(chosen_box)
return bboxes_after_nms
def mean_average_precision(
pred_boxes, true_boxes, iou_threshold=0.5, box_format="midpoint", num_classes=20
):
"""
Calculates mean average precision
Parameters:
pred_boxes (list): list of lists containing all bboxes with each bboxes
specified as [train_idx, class_prediction, prob_score, x1, y1, x2, y2]
true_boxes (list): Similar as pred_boxes except all the correct ones
iou_threshold (float): threshold where predicted bboxes is correct
box_format (str): "midpoint" or "corners" used to specify bboxes
num_classes (int): number of classes
Returns:
float: mAP value across all classes given a specific IoU threshold
"""
# list storing all AP for respective classes
average_precisions = []
# used for numerical stability later on
epsilon = 1e-6
for c in range(num_classes):
detections = []
ground_truths = []
# Go through all predictions and targets,
# and only add the ones that belong to the
# current class c
for detection in pred_boxes:
if detection[1] == c:
detections.append(detection)
for true_box in true_boxes:
if true_box[1] == c:
ground_truths.append(true_box)
# find the amount of bboxes for each training example
# Counter here finds how many ground truth bboxes we get
# for each training example, so let's say img 0 has 3,
# img 1 has 5 then we will obtain a dictionary with:
# amount_bboxes = {0:3, 1:5}
amount_bboxes = Counter([gt[0] for gt in ground_truths])
# We then go through each key, val in this dictionary
# and convert to the following (w.r.t same example):
# ammount_bboxes = {0:torch.tensor[0,0,0], 1:torch.tensor[0,0,0,0,0]}
for key, val in amount_bboxes.items():
amount_bboxes[key] = torch.zeros(val)
# sort by box probabilities which is index 2
detections.sort(key=lambda x: x[2], reverse=True)
TP = torch.zeros((len(detections)))
FP = torch.zeros((len(detections)))
total_true_bboxes = len(ground_truths)
# If none exists for this class then we can safely skip
if total_true_bboxes == 0:
continue
for detection_idx, detection in enumerate(detections):
# Only take out the ground_truths that have the same
# training idx as detection
ground_truth_img = [
bbox for bbox in ground_truths if bbox[0] == detection[0]
]
num_gts = len(ground_truth_img)
best_iou = 0
for idx, gt in enumerate(ground_truth_img):
iou = intersection_over_union(
torch.tensor(detection[3:]),
torch.tensor(gt[3:]),
box_format=box_format,
)
if iou > best_iou:
best_iou = iou
best_gt_idx = idx
if best_iou > iou_threshold:
# only detect ground truth detection once
if amount_bboxes[detection[0]][best_gt_idx] == 0:
# true positive and add this bounding box to seen
TP[detection_idx] = 1
amount_bboxes[detection[0]][best_gt_idx] = 1
else:
FP[detection_idx] = 1
# if IOU is lower then the detection is a false positive
else:
FP[detection_idx] = 1
TP_cumsum = torch.cumsum(TP, dim=0)
FP_cumsum = torch.cumsum(FP, dim=0)
recalls = TP_cumsum / (total_true_bboxes + epsilon)
precisions = torch.divide(TP_cumsum, (TP_cumsum + FP_cumsum + epsilon))
precisions = torch.cat((torch.tensor([1]), precisions))
recalls = torch.cat((torch.tensor([0]), recalls))
# torch.trapz for numerical integration
average_precisions.append(torch.trapz(precisions, recalls))
return sum(average_precisions) / len(average_precisions)
def plot_image(image, boxes):
"""Plots predicted bounding boxes on the image"""
im = np.array(image)
height, width, _ = im.shape
# Create figure and axes
fig, ax = plt.subplots(1)
# Display the image
ax.imshow(im)
# box[0] is x midpoint, box[2] is width
# box[1] is y midpoint, box[3] is height
# Create a Rectangle potch
for box in boxes:
box = box[2:]
assert len(box) == 4, "Got more values than in x, y, w, h, in a box!"
upper_left_x = box[0] - box[2] / 2
upper_left_y = box[1] - box[3] / 2
rect = patches.Rectangle(
(upper_left_x * width, upper_left_y * height),
box[2] * width,
box[3] * height,
linewidth=1,
edgecolor="r",
facecolor="none",
)
# Add the patch to the Axes
ax.add_patch(rect)
plt.show()
def get_bboxes(
loader,
model,
iou_threshold,
threshold,
pred_format="cells",
box_format="midpoint",
device="cuda",
):
all_pred_boxes = []
all_true_boxes = []
# make sure model is in eval before get bboxes
model.eval()
train_idx = 0
for batch_idx, (x, labels) in enumerate(loader):
x = x.to(device)
labels = labels.to(device)
with torch.no_grad():
predictions = model(x)
batch_size = x.shape[0]
true_bboxes = cellboxes_to_boxes(labels)
bboxes = cellboxes_to_boxes(predictions)
for idx in range(batch_size):
nms_boxes = non_max_suppression(
bboxes[idx],
iou_threshold=iou_threshold,
threshold=threshold,
box_format=box_format,
)
# if batch_idx == 0 and idx == 0:
# plot_image(x[idx].permute(1,2,0).to("cpu"), nms_boxes)
# print(nms_boxes)
for nms_box in nms_boxes:
all_pred_boxes.append([train_idx] + nms_box)
for box in true_bboxes[idx]:
# many will get converted to 0 pred
if box[1] > threshold:
all_true_boxes.append([train_idx] + box)
train_idx += 1
model.train()
return all_pred_boxes, all_true_boxes
def convert_cellboxes(predictions, S=7):
"""
Converts bounding boxes output from Yolo with
an image split size of S into entire image ratios
rather than relative to cell ratios. Tried to do this
vectorized, but this resulted in quite difficult to read
code... Use as a black box? Or implement a more intuitive,
using 2 for loops iterating range(S) and convert them one
by one, resulting in a slower but more readable implementation.
"""
predictions = predictions.to("cpu")
batch_size = predictions.shape[0]
predictions = predictions.reshape(batch_size, 7, 7, 30)
bboxes1 = predictions[..., 21:25]
bboxes2 = predictions[..., 26:30]
scores = torch.cat(
(predictions[..., 20].unsqueeze(0), predictions[..., 25].unsqueeze(0)), dim=0
)
best_box = scores.argmax(0).unsqueeze(-1)
best_boxes = bboxes1 * (1 - best_box) + best_box * bboxes2
cell_indices = torch.arange(7).repeat(batch_size, 7, 1).unsqueeze(-1)
x = 1 / S * (best_boxes[..., :1] + cell_indices)
y = 1 / S * (best_boxes[..., 1:2] + cell_indices.permute(0, 2, 1, 3))
w_y = 1 / S * best_boxes[..., 2:4]
converted_bboxes = torch.cat((x, y, w_y), dim=-1)
predicted_class = predictions[..., :20].argmax(-1).unsqueeze(-1)
best_confidence = torch.max(predictions[..., 20], predictions[..., | |
man='22', pin='223344')
self.assertTrue(self.config.ryanpeiko.is_condition_met(self._hand(tiles)))
tiles = self._string_to_34_array(sou='111122223333', man='22')
self.assertTrue(self.config.ryanpeiko.is_condition_met(self._hand(tiles, 1)))
tiles = self._string_to_34_array(sou='112233', man='123', pin='23444')
self.assertFalse(self.config.ryanpeiko.is_condition_met(self._hand(tiles)))
tiles = self._string_to_136_array(sou='112233', man='33', pin='223344')
win_tile = self._string_to_136_tile(pin='3')
result = hand.estimate_hand_value(tiles, win_tile)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 3)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
melds = [self._make_meld(Meld.CHI, sou='123')]
result = hand.estimate_hand_value(tiles, win_tile, melds=melds)
self.assertNotEqual(result.error, None)
def test_is_sanshoku(self):
hand = HandCalculator()
tiles = self._string_to_34_array(sou='123', man='123', pin='12345677')
self.assertTrue(self.config.sanshoku.is_condition_met(self._hand(tiles)))
tiles = self._string_to_34_array(sou='123456', man='23455', pin='123')
self.assertFalse(self.config.sanshoku.is_condition_met(self._hand(tiles)))
tiles = self._string_to_136_array(sou='123456', man='12399', pin='123')
win_tile = self._string_to_136_tile(man='2')
result = hand.estimate_hand_value(tiles, win_tile)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 2)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
melds = [self._make_meld(Meld.CHI, sou='123')]
result = hand.estimate_hand_value(tiles, win_tile, melds=melds)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 1)
self.assertEqual(result.fu, 30)
self.assertEqual(len(result.yaku), 1)
def test_is_sanshoku_douko(self):
hand = HandCalculator()
tiles = self._string_to_34_array(sou='111', man='111', pin='11145677')
self.assertTrue(self.config.sanshoku_douko.is_condition_met(self._hand(tiles)))
tiles = self._string_to_34_array(sou='111', man='222', pin='33344455')
self.assertFalse(self.config.sanshoku_douko.is_condition_met(self._hand(tiles)))
tiles = self._string_to_136_array(sou='222', man='222', pin='22245699')
melds = [self._make_meld(Meld.CHI, sou='222')]
win_tile = self._string_to_136_tile(pin='9')
result = hand.estimate_hand_value(tiles, win_tile, melds=melds)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 2)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
def test_is_toitoi(self):
hand = HandCalculator()
tiles = self._string_to_34_array(sou='111333', man='333', pin='44555')
self.assertTrue(self.config.toitoi.is_condition_met(self._hand(tiles)))
tiles = self._string_to_34_array(sou='777', pin='777888999', honors='44')
self.assertTrue(self.config.toitoi.is_condition_met(self._hand(tiles, 1)))
tiles = self._string_to_136_array(sou='111333', man='333', pin='44555')
melds = [self._make_meld(Meld.PON, sou='111'), self._make_meld(Meld.PON, sou='333')]
win_tile = self._string_to_136_tile(pin='5')
result = hand.estimate_hand_value(tiles, win_tile, melds=melds)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 2)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
tiles = self._string_to_136_array(sou='777', pin='777888999', honors='44')
melds = [self._make_meld(Meld.PON, sou='777')]
win_tile = self._string_to_136_tile(pin='9')
result = hand.estimate_hand_value(tiles, win_tile, melds=melds)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 2)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
def test_is_sankantsu(self):
hand = HandCalculator()
tiles = self._string_to_136_array(sou='111333', man='123', pin='44666')
melds = [
self._make_meld(Meld.KAN, sou='1111'),
self._make_meld(Meld.KAN, sou='3333'),
self._make_meld(Meld.KAN, pin='6666'),
]
self.assertTrue(self.config.sankantsu.is_condition_met(hand, melds))
melds = [
self._make_meld(Meld.CHANKAN, sou='1111'),
self._make_meld(Meld.KAN, sou='3333'),
self._make_meld(Meld.KAN, pin='6666'),
]
win_tile = self._string_to_136_tile(man='3')
result = hand.estimate_hand_value(tiles, win_tile, melds=melds)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 2)
self.assertEqual(result.fu, 60)
self.assertEqual(len(result.yaku), 1)
def test_is_honroto(self):
hand = HandCalculator()
tiles = self._string_to_34_array(sou='111999', man='111', honors='11222')
self.assertTrue(self.config.honroto.is_condition_met(self._hand(tiles)))
tiles = self._string_to_34_array(pin='11', honors='22334466', man='1199')
self.assertTrue(self.config.honroto.is_condition_met(self._hand(tiles)))
tiles = self._string_to_136_array(sou='111999', man='111', honors='11222')
win_tile = self._string_to_136_tile(honors='2')
melds = [self._make_meld(Meld.PON, sou='111')]
result = hand.estimate_hand_value(tiles, win_tile, melds=melds)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 4)
self.assertEqual(result.fu, 50)
self.assertEqual(len(result.yaku), 2)
tiles = self._string_to_136_array(pin='11', honors='22334466', man='1199')
win_tile = self._string_to_136_tile(man='1')
result = hand.estimate_hand_value(tiles, win_tile)
self.assertEqual(result.fu, 25)
self.assertEqual(result.han, 4)
def test_is_sanankou(self):
hand = HandCalculator()
tiles = self._string_to_34_array(sou='111444', man='333', pin='44555')
win_tile = self._string_to_136_tile(sou='4')
melds = [
self._make_meld(Meld.PON, sou='444'),
self._make_meld(Meld.PON, sou='111')
]
self.assertFalse(self.config.sanankou.is_condition_met(self._hand(tiles), win_tile, melds, False))
melds = [
self._make_meld(Meld.PON, sou='111')
]
self.assertFalse(self.config.sanankou.is_condition_met(self._hand(tiles), win_tile, melds, False))
self.assertTrue(self.config.sanankou.is_condition_met(self._hand(tiles), win_tile, melds, True))
tiles = self._string_to_34_array(pin='444789999', honors='22333')
win_tile = self._string_to_136_tile(pin='9')
self.assertTrue(self.config.sanankou.is_condition_met(self._hand(tiles), win_tile, [], False))
melds = [
self._make_meld(Meld.CHI, pin='456')
]
tiles = self._string_to_34_array(pin='222456666777', honors='77')
win_tile = self._string_to_136_tile(pin='6')
self.assertFalse(self.config.sanankou.is_condition_met(self._hand(tiles), win_tile, melds, False))
tiles = self._string_to_136_array(sou='123444', man='333', pin='44555')
melds = [
self._make_meld(Meld.CHI, sou='123')
]
win_tile = self._string_to_136_tile(pin='5')
result = hand.estimate_hand_value(tiles, win_tile, melds=melds, config=self._make_hand_config(is_tsumo=True))
self.assertEqual(result.error, None)
self.assertEqual(result.han, 2)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
def test_is_shosangen(self):
hand = HandCalculator()
tiles = self._string_to_34_array(sou='123', man='345', honors='55666777')
self.assertTrue(self.config.shosangen.is_condition_met(self._hand(tiles)))
tiles = self._string_to_136_array(sou='123', man='345', honors='55666777')
win_tile = self._string_to_136_tile(honors='7')
result = hand.estimate_hand_value(tiles, win_tile)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 4)
self.assertEqual(result.fu, 50)
self.assertEqual(len(result.yaku), 3)
def test_is_chanta(self):
hand = HandCalculator()
tiles = self._string_to_34_array(sou='123', man='123789', honors='22333')
self.assertTrue(self.config.chanta.is_condition_met(self._hand(tiles)))
tiles = self._string_to_34_array(sou='111', man='111999', honors='22333')
self.assertFalse(self.config.chanta.is_condition_met(self._hand(tiles)))
tiles = self._string_to_34_array(sou='111999', man='111999', pin='11999')
self.assertFalse(self.config.chanta.is_condition_met(self._hand(tiles)))
tiles = self._string_to_136_array(sou='123', man='123789', honors='22333')
win_tile = self._string_to_136_tile(honors='3')
result = hand.estimate_hand_value(tiles, win_tile)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 2)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
melds = [self._make_meld(Meld.CHI, sou='123')]
result = hand.estimate_hand_value(tiles, win_tile, melds=melds)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 1)
self.assertEqual(result.fu, 30)
self.assertEqual(len(result.yaku), 1)
def test_is_junchan(self):
hand = HandCalculator()
tiles = self._string_to_34_array(sou='789', man='123789', pin='12399')
self.assertTrue(self.config.junchan.is_condition_met(self._hand(tiles)))
tiles = self._string_to_34_array(sou='111', man='111999', honors='22333')
self.assertFalse(self.config.junchan.is_condition_met(self._hand(tiles)))
tiles = self._string_to_34_array(sou='111999', man='111999', pin='11999')
self.assertFalse(self.config.junchan.is_condition_met(self._hand(tiles)))
tiles = self._string_to_136_array(sou='789', man='123789', pin='12399')
win_tile = self._string_to_136_tile(man='2')
result = hand.estimate_hand_value(tiles, win_tile)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 3)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
melds = [self._make_meld(Meld.CHI, sou='789')]
result = hand.estimate_hand_value(tiles, win_tile, melds=melds)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 2)
self.assertEqual(result.fu, 30)
self.assertEqual(len(result.yaku), 1)
def test_is_honitsu(self):
hand = HandCalculator()
tiles = self._string_to_34_array(man='123456789', honors='11122')
self.assertTrue(self.config.honitsu.is_condition_met(self._hand(tiles)))
tiles = self._string_to_34_array(man='123456789', pin='123', honors='22')
self.assertFalse(self.config.honitsu.is_condition_met(self._hand(tiles)))
tiles = self._string_to_34_array(man='12345666778899')
self.assertFalse(self.config.honitsu.is_condition_met(self._hand(tiles)))
tiles = self._string_to_136_array(man='123455667', honors='11122')
win_tile = self._string_to_136_tile(honors='2')
result = hand.estimate_hand_value(tiles, win_tile)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 3)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
melds = [self._make_meld(Meld.CHI, man='123')]
result = hand.estimate_hand_value(tiles, win_tile, melds=melds)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 2)
self.assertEqual(result.fu, 30)
self.assertEqual(len(result.yaku), 1)
def test_is_chinitsu(self):
hand = HandCalculator()
tiles = self._string_to_34_array(man='12345666778899')
self.assertTrue(self.config.chinitsu.is_condition_met(self._hand(tiles)))
tiles = self._string_to_34_array(man='123456778899', honors='22')
self.assertFalse(self.config.chinitsu.is_condition_met(self._hand(tiles)))
tiles = self._string_to_136_array(man='11234567677889')
win_tile = self._string_to_136_tile(man='1')
result = hand.estimate_hand_value(tiles, win_tile)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 6)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
melds = [self._make_meld(Meld.CHI, man='678')]
result = hand.estimate_hand_value(tiles, win_tile, melds=melds)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 5)
self.assertEqual(result.fu, 30)
self.assertEqual(len(result.yaku), 1)
def test_is_ittsu(self):
hand = HandCalculator()
tiles = self._string_to_34_array(man='123456789', sou='123', honors='22')
self.assertTrue(self.config.ittsu.is_condition_met(self._hand(tiles)))
tiles = self._string_to_34_array(man='112233456789', honors='22')
self.assertTrue(self.config.ittsu.is_condition_met(self._hand(tiles)))
tiles = self._string_to_34_array(man='122334567789', honors='11')
self.assertFalse(self.config.ittsu.is_condition_met(self._hand(tiles)))
tiles = self._string_to_136_array(man='123456789', sou='123', honors='22')
win_tile = self._string_to_136_tile(sou='3')
result = hand.estimate_hand_value(tiles, win_tile)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 2)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
melds = [self._make_meld(Meld.CHI, man='123')]
result = hand.estimate_hand_value(tiles, win_tile, melds=melds)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 1)
self.assertEqual(result.fu, 30)
self.assertEqual(len(result.yaku), 1)
def test_is_haku(self):
hand = HandCalculator()
tiles = self._string_to_34_array(sou='234567', man='23422', honors='555')
self.assertTrue(self.config.haku.is_condition_met(self._hand(tiles)))
tiles = self._string_to_136_array(sou='234567', man='23422', honors='555')
win_tile = self._string_to_136_tile(honors='5')
result = hand.estimate_hand_value(tiles, win_tile,
config=self._make_hand_config(is_tsumo=False, is_riichi=False))
self.assertEqual(result.error, None)
self.assertEqual(result.han, 1)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
def test_is_hatsu(self):
hand = HandCalculator()
tiles = self._string_to_34_array(sou='234567', man='23422', honors='666')
self.assertTrue(self.config.hatsu.is_condition_met(self._hand(tiles)))
tiles = self._string_to_136_array(sou='234567', man='23422', honors='666')
win_tile = self._string_to_136_tile(honors='6')
result = hand.estimate_hand_value(tiles, win_tile,
config=self._make_hand_config(is_tsumo=False, is_riichi=False))
self.assertEqual(result.error, None)
self.assertEqual(result.han, 1)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
def test_is_chun(self):
hand = HandCalculator()
tiles = self._string_to_34_array(sou='234567', man='23422', honors='777')
self.assertTrue(self.config.chun.is_condition_met(self._hand(tiles)))
tiles = self._string_to_136_array(sou='234567', man='23422', honors='777')
win_tile = self._string_to_136_tile(honors='7')
result = hand.estimate_hand_value(tiles, win_tile,
config=self._make_hand_config(is_tsumo=False, is_riichi=False))
self.assertEqual(result.error, None)
self.assertEqual(result.han, 1)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
def test_is_east(self):
player_wind, round_wind = EAST, WEST
hand = HandCalculator()
tiles = self._string_to_34_array(sou='234567', man='23422', honors='111')
self.assertTrue(self.config.east.is_condition_met(self._hand(tiles), player_wind, round_wind))
tiles = self._string_to_136_array(sou='234567', man='23422', honors='111')
win_tile = self._string_to_136_tile(honors='1')
result = hand.estimate_hand_value(tiles,
win_tile,
config=self._make_hand_config(
is_tsumo=False,
is_riichi=False,
player_wind=player_wind,
round_wind=round_wind
))
self.assertEqual(result.error, None)
self.assertEqual(result.han, 1)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
round_wind = EAST
result = hand.estimate_hand_value(tiles,
win_tile,
config=self._make_hand_config(
is_tsumo=False,
is_riichi=False,
player_wind=player_wind,
round_wind=round_wind
))
self.assertEqual(result.error, None)
self.assertEqual(result.han, 2)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 2)
def test_is_south(self):
player_wind, round_wind = SOUTH, EAST
hand = HandCalculator()
tiles = self._string_to_34_array(sou='234567', man='23422', honors='222')
self.assertTrue(self.config.south.is_condition_met(self._hand(tiles), player_wind, round_wind))
tiles = self._string_to_136_array(sou='234567', man='23422', honors='222')
win_tile = self._string_to_136_tile(honors='2')
result = hand.estimate_hand_value(tiles,
win_tile,
config=self._make_hand_config(
is_tsumo=False,
is_riichi=False,
player_wind=player_wind,
round_wind=round_wind
))
self.assertEqual(result.error, None)
self.assertEqual(result.han, 1)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
round_wind = SOUTH
result = hand.estimate_hand_value(tiles,
win_tile,
config=self._make_hand_config(
is_tsumo=False,
is_riichi=False,
player_wind=player_wind,
round_wind=round_wind
))
self.assertEqual(result.error, None)
self.assertEqual(result.han, 2)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 2)
def test_is_west(self):
player_wind, round_wind = WEST, EAST
hand = HandCalculator()
tiles = self._string_to_34_array(sou='234567', man='23422', honors='333')
self.assertTrue(self.config.west.is_condition_met(self._hand(tiles), player_wind, round_wind))
tiles = self._string_to_136_array(sou='234567', man='23422', honors='333')
win_tile = self._string_to_136_tile(honors='3')
result = hand.estimate_hand_value(tiles,
win_tile,
config=self._make_hand_config(
is_tsumo=False,
is_riichi=False,
player_wind=player_wind,
round_wind=round_wind
))
self.assertEqual(result.error, None)
self.assertEqual(result.han, 1)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
round_wind = WEST
result = hand.estimate_hand_value(tiles,
win_tile,
config=self._make_hand_config(
is_tsumo=False,
is_riichi=False,
player_wind=player_wind,
round_wind=round_wind))
self.assertEqual(result.error, None)
self.assertEqual(result.han, 2)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 2)
def test_is_north(self):
player_wind, round_wind = NORTH, EAST
hand = HandCalculator()
tiles = self._string_to_34_array(sou='234567', man='23422', honors='444')
self.assertTrue(self.config.north.is_condition_met(self._hand(tiles), player_wind, round_wind))
tiles = self._string_to_136_array(sou='234567', man='23422', honors='444')
win_tile = self._string_to_136_tile(honors='4')
result = hand.estimate_hand_value(tiles,
win_tile,
config=self._make_hand_config(
is_tsumo=False,
is_riichi=False,
player_wind=player_wind,
round_wind=round_wind))
self.assertEqual(result.error, None)
self.assertEqual(result.han, 1)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 1)
round_wind = NORTH
result = hand.estimate_hand_value(tiles,
win_tile,
config=self._make_hand_config(
is_tsumo=False,
is_riichi=False,
player_wind=player_wind,
round_wind=round_wind
))
self.assertEqual(result.error, None)
self.assertEqual(result.han, 2)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 2)
def test_dora_in_hand(self):
hand = HandCalculator()
# hand without yaku, but with dora should be consider as invalid
tiles = self._string_to_136_array(sou='345678', man='456789', honors='55')
win_tile = self._string_to_136_tile(sou='5')
dora_indicators = [self._string_to_136_tile(sou='5')]
melds = [self._make_meld(Meld.CHI, sou='678')]
result = hand.estimate_hand_value(tiles, win_tile, dora_indicators=dora_indicators, melds=melds)
self.assertNotEqual(result.error, None)
tiles = self._string_to_136_array(sou='123456', man='123456', pin='33')
win_tile = self._string_to_136_tile(man='6')
dora_indicators = [self._string_to_136_tile(pin='2')]
result = hand.estimate_hand_value(tiles, win_tile, dora_indicators=dora_indicators)
self.assertEqual(result.error, None)
self.assertEqual(result.han, 3)
self.assertEqual(result.fu, 30)
self.assertEqual(len(result.yaku), 2)
tiles = self._string_to_136_array(man='22456678', pin='123678')
win_tile = self._string_to_136_tile(man='2')
dora_indicators = [self._string_to_136_tile(man='1'), self._string_to_136_tile(pin='2')]
result = hand.estimate_hand_value(tiles, win_tile, dora_indicators=dora_indicators,
config=self._make_hand_config(is_tsumo=True))
self.assertEqual(result.error, None)
self.assertEqual(result.han, 4)
self.assertEqual(result.fu, 30)
self.assertEqual(len(result.yaku), 2)
# double dora
tiles = self._string_to_136_array(man='678', pin='34577', sou='123345')
win_tile = self._string_to_136_tile(pin='7')
dora_indicators = [self._string_to_136_tile(sou='4'), self._string_to_136_tile(sou='4')]
result = hand.estimate_hand_value(tiles, win_tile, dora_indicators=dora_indicators,
config=self._make_hand_config(is_tsumo=True))
self.assertEqual(result.error, None)
self.assertEqual(result.han, 3)
self.assertEqual(result.fu, 30)
self.assertEqual(len(result.yaku), 2)
# double dora and honor tiles
tiles = self._string_to_136_array(man='678', pin='345', sou='123345', honors='66')
win_tile = self._string_to_136_tile(pin='5')
dora_indicators = [self._string_to_136_tile(honors='5'), self._string_to_136_tile(honors='5')]
result = hand.estimate_hand_value(tiles, win_tile, dora_indicators=dora_indicators,
config=self._make_hand_config(is_riichi=True))
self.assertEqual(result.error, None)
self.assertEqual(result.han, 5)
self.assertEqual(result.fu, 40)
self.assertEqual(len(result.yaku), 2)
# double dora indicators and red fives
tiles = self._string_to_136_array(sou='12346', man='123678', pin='44')
win_tile = self._string_to_136_tile(pin='4')
tiles.append(FIVE_RED_SOU)
dora_indicators = [self._string_to_136_tile(pin='2'), self._string_to_136_tile(pin='2')]
result = hand.estimate_hand_value(tiles, win_tile, dora_indicators=dora_indicators,
config=self._make_hand_config(is_tsumo=True, has_aka_dora=True))
self.assertEqual(result.error, None)
self.assertEqual(result.han, 2)
self.assertEqual(result.fu, 30)
self.assertEqual(len(result.yaku), 2)
# dora in kan
tiles = self._string_to_136_array(man='777', pin='34577', sou='123345')
win_tile | |
<reponame>AnitaPetzler/AMOEBA
import copy
import emcee
import itertools
import numpy as np
import pickle
from scipy.interpolate import interpn
from scipy.special import logsumexp
import matplotlib.pyplot as plt
'''
......
.. ...
.. ..
.. .. .....
.. .. ... ...
.. .. ... ..
.. .. ... ..
.. .... ..... ..
.. ....... ..
.. ..
.. ..
... ..
................... b ..
... b ..
.. aaaaa a m mmm mmmm ooooo eeeee b bbbb aaaaa a ..
.. a aa m m m o o e e b b a aa .
.. a a m m m o o e eee b b a a .
.. aaaaa a m m m ooooo eeeee b bbbb aaaaa a .
... ..
.......... ..
....... ..
... ..
... ........ ..
... .... ... ..
.. ... .... ..
.. ... .. ..
.. ... .......
.. ..
.. ..
.... ....
.....
'''
'''
The four hyperfine levels of the OH ground rotational state:
1612 1665 1667 1720
_____________________ 4
___________|____|____ 3
_|____|____|____|____ 2
______|_________|____ 1
'''
# Some key parameters:
# number of burn iterations for emcee (100 is low, 10000 is high)
burn_iter=500
# number of final iterations for emcee (50 is low, 1000 is high)
final_iter=100
# number of walkers per gaussian (must be even and no less than 12, 60 is better)
nwalkers_mult=60
def main(source_name, vel_axes = None, tau_spectra = None,
Texp_spectra = [], tau_rms = [],
Texp_rms = [], Tbg = None, quiet = True,
best_result = 'median_actual', Bayes_threshold = 10.,
sigma_tolerance = 1.4, num_chan = 3,
seed=None, extra_gaussians=3,sig_vels=[],lfwhm_mean=None,lfwhm_sig=None):
'''
Performs fully automated gaussian decomposition. This code was written
specifically to decompose spectra of the four ground rotational state
transitions of the hydroxyl molecule, but can also be used to decompose
any set of simultaneous spectra.
Parameters:
source_name (str): name of source to be included with results reports
Keyword Arguments:
vel_axes (array-like): set of 4 1D arrays corresponding to the 4
spectra of the ground state transitions of OH.
tau_spectra (array-like): set of 4 1D arrays of optical depth vs
velocity (tau spectra as opposed to exp(-tau), etc) in the 4 ground
rotational state transitions of OH.
Texp_spectra (array-like): set of 4 1D arrays of continuum subtracted
expected brightness temperature in the 4 ground rotational state
transitions of OH: Texp=(Tex-Tbg)*(1-exp(-tau)).
Tbg (array-like): set of 4 background brightness temperatures at 1612,
1665, 1667 and 1720 MHz (K). This is any background continuum in
the `off-source' position: synchrotron, CMB.
quiet (boolean): whether or not to provide various outputs to terminal.
best_result (str): Which result from the markov chain is to be reported
as the best result 'median', 'median_actual', 'max' (note, all are
printed if quiet = False). 'median' returns the median position of
each parameter (may not correspond to an actual set of parameters
measured), 'median_actual' finds the point in the flattened chain
closest to the medians of each parameter and compares the lnprob
here to that of the actual medians, returns the one with better
lnprob, and 'max' returns the set of parameters with the highest
lnprob.
Bayes_threshold (float): minimum Bayes' Factor (K) required for the
fitting routine to attempt to fit an additional gaussian feature.
sigma_tolerance (float): factor used to identify 'significant' ranges
in the supplied spectra. Roughly related to sigma level but *NOT*
equivalent. Increase sigma_tolerance to reduce the range of spectra
identified.
Returns:
array-like: Full list of accepted parameters with upper and lower
bounds of credibile intervals. Format: [[1min, 1median, 1max],
[2min, 2median, 2max],...] for parameters 1, 2, etc.
'''
# Quick checks of input data:
if len(Texp_spectra) != 0:
for x in range(4):
if len(vel_axes[x]) != len(Texp_spectra[x]):
# print('Provided axes (' + str(x) + ') lengths do not match')
# print('\tvel axis length: '+str(len(vel_axes[x]))+
# ' spectrum axis length: '+str(len(Texp_spectra[x])))
return None
for x in range(4):
if len(vel_axes[x]) != len(tau_spectra[x]):
# print('Provided axes (' + str(x) + ') lengths do not match')
# print('\tvel axis length: '+str(len(vel_axes[x]))+
# ' spectrum axis length: '+str(len(tau_spectra[x])))
return None
# initialise data dictionary
full_data = {'source_name': source_name,
'vel_axes':{'1612':[],'1665':[],'1667':[],'1720':[]},
'tau_spectrum':{'1612':[],'1665':[],'1667':[],'1720':[]},
'tau_rms':{'1612':[],'1665':[],'1667':[],'1720':[]},
'Texp_spectrum':{'1612':[],'1665':[],'1667':[],'1720':[]},
'Texp_rms':{'1612':[],'1665':[],'1667':[],'1720':[]},
'Tbg':{'1612':[],'1665':[],'1667':[],'1720':[]},
'sig_vel_ranges':[[]]}
###############################################
# #
# Load Data into 'data' dictionary object #
# #
###############################################
if len(tau_rms) == 0:
full_data['tau_rms']['1612'] = findrms(tau_spectra[0])
full_data['tau_rms']['1665'] = findrms(tau_spectra[1])
full_data['tau_rms']['1667'] = findrms(tau_spectra[2])
full_data['tau_rms']['1720'] = findrms(tau_spectra[3])
else:
full_data['tau_rms']['1612'] = tau_rms[0]
full_data['tau_rms']['1665'] = tau_rms[1]
full_data['tau_rms']['1667'] = tau_rms[2]
full_data['tau_rms']['1720'] = tau_rms[3]
full_data['vel_axes']['1612'] = vel_axes[0]
full_data['tau_spectrum']['1612'] = tau_spectra[0]
full_data['vel_axes']['1665'] = vel_axes[1]
full_data['tau_spectrum']['1665'] = tau_spectra[1]
full_data['vel_axes']['1667'] = vel_axes[2]
full_data['tau_spectrum']['1667'] = tau_spectra[2]
full_data['vel_axes']['1720'] = vel_axes[3]
full_data['tau_spectrum']['1720'] = tau_spectra[3]
if len(Texp_spectra) != 0: #absorption and emission spectra are available
# (i.e. on-off observations)
if len(Texp_rms) == 0:
full_data['Texp_rms']['1612'] = findrms(Texp_spectra[0])
full_data['Texp_rms']['1665'] = findrms(Texp_spectra[1])
full_data['Texp_rms']['1667'] = findrms(Texp_spectra[2])
full_data['Texp_rms']['1720'] = findrms(Texp_spectra[3])
else:
full_data['Texp_rms']['1612'] = Texp_rms[0]
full_data['Texp_rms']['1665'] = Texp_rms[1]
full_data['Texp_rms']['1667'] = Texp_rms[2]
full_data['Texp_rms']['1720'] = Texp_rms[3]
full_data['Tbg']['1612'] = Tbg[0]
full_data['Tbg']['1665'] = Tbg[1]
full_data['Tbg']['1667'] = Tbg[2]
full_data['Tbg']['1720'] = Tbg[3]
full_data['Texp_spectrum']['1612'] = Texp_spectra[0]
full_data['Texp_spectrum']['1665'] = Texp_spectra[1]
full_data['Texp_spectrum']['1667'] = Texp_spectra[2]
full_data['Texp_spectrum']['1720'] = Texp_spectra[3]
###############################################
# #
# Identify significant ranges #
# #
###############################################
if len(sig_vels)==0:
findranges(full_data, sigma_tolerance, num_chan)
print([source_name,full_data['sig_vel_ranges']])
else:
full_data['sig_vel_ranges']=sig_vels
###############################################
# #
# Fit gaussians #
# #
###############################################
print('Placing Gaussians')
final_p=placegaussians(full_data,Bayes_threshold,quiet,seed,
extra_gaussians=extra_gaussians,lfwhm_mean=lfwhm_mean,
lfwhm_sig=lfwhm_sig)
return final_p
##############################
# #
# Spectra #
# #
##############################
# |
# |
# \ | /
# \|/
# V
def findranges(data, sigma_tolerance, num_chan):
'''
Identifies velocity ranges likely to contain features. Adds
'sig_vel_ranges' (velocity ranges that satisfy a significance test) to the
'data' dictionary.
Parameters:
data (dict): observed spectra and other observed quantities (see
Main function)
sigma_tolerance (float): signal to noise ratio threshold for a channel
to be identified as 'significant'.
num_chan (int): number of consecutive channels that must be
'significant' to be reported order to check for significance
Returns:
dict: 'data' dictionary with updated 'sig_vel_ranges' keyword
'''
num_spec=4
vel_axes = [data['vel_axes']['1612'], data['vel_axes']['1665'],
data['vel_axes']['1667'], data['vel_axes']['1720']]
spectra = [ data['tau_spectrum']['1612'], data['tau_spectrum']['1665'],
data['tau_spectrum']['1667'], data['tau_spectrum']['1720']]
spec_rmss = [data['tau_rms']['1612'], data['tau_rms']['1665'],
data['tau_rms']['1667'], data['tau_rms']['1720']]
if 'Texp_spectrum' in data and data['Texp_spectrum']['1665'] != []:
num_spec+=4
vel_axes += [data['vel_axes']['1612'], data['vel_axes']['1665'],
data['vel_axes']['1667'], data['vel_axes']['1720']]
spectra += [data['Texp_spectrum']['1612'],
data['Texp_spectrum']['1665'],
data['Texp_spectrum']['1667'],
data['Texp_spectrum']['1720']]
spec_rmss += [data['Texp_rms']['1612'], data['Texp_rms']['1665'],
data['Texp_rms']['1667'], data['Texp_rms']['1720']]
sig_vel_list=[]
for spec in range(num_spec):
vel_axis=vel_axes[spec]
spectrum=spectra[spec]
spec_rms=spec_rmss[spec]
test_spec=[1 if x>=sigma_tolerance*spec_rms else -1 if
x<=-sigma_tolerance*spec_rms else 0 for x in spectrum]
for c in range(int(len(vel_axis)-num_chan)):
if (np.sum(test_spec[c:c+num_chan]) >= num_chan) or (np.sum(
test_spec[c:c+num_chan]) <= -num_chan):
for x in range(num_chan):
if sig_vel_list == []:
sig_vel_list=[vel_axis[int(c+x)]]
else:
sig_vel_list+=[vel_axis[int(c+x)]]
[av_chan,minv,maxv]=[np.mean([np.abs(v[1]-v[0]) for v in vel_axes]),
np.max([np.min(v) for v in vel_axes]),
np.min([np.max(v) for v in vel_axes])]
sig_vel_ranges = reducelist(sig_vel_list,2*num_chan*av_chan,minv,maxv)
# print(str([data['source_name'],sig_vel_ranges]))
data['sig_vel_ranges'] = sig_vel_ranges
return data
def findrms(spectrum): # returns rms
'''
Calculates the root mean square of 'spectrum'. This is intended as a
measure of noise only, so rms is calculated for several ranges, and the
median is returned.
Parameters:
spectrum (array-like): 1d array of values for which to compute rms
Returns:
float: Median rms of those calculated
'''
# print(spectrum)
a=len(spectrum)/20
a=int(a-a%1)
rms_list=[np.std(spectrum[int(20*(x-1)):int(20*(x-1)+30)])
for x in range(1,a)]
return np.median(rms_list)
def reducelist(vlist, spacing,minv,maxv):
'''
Takes a list of velocities with 'significant' signal (as determined by
'findranges') and identifies places where the spectra can be safely
segmented in order to minimise the length of spectra fit by
'placegaussians'.
Parameters:
vlist (array-like): unsorted list of velocity channels at which
'significant' signal exists in at least one spectrum.
spacing (float): extent in velocity (km/s) required to be
'insignificant' in order to allow spectra to be 'cut'. This should
equate to some small multiple (i.e. 2) of the 'num_chan' parameter
in 'findranges'.
Returns:
vlist_output (2D list): list of min and max velocity of each spectrum
segment, in the form [[v1min,v1max],...,[vnmin,vnmax]].
'''
vlist=sorted(vlist)
cut_list=[(vlist[x]+vlist[x+1])/2 for x in range(int(len(vlist)-1)) if
(vlist[x+1]-vlist[x])>=spacing]
if len(cut_list) == 0:
cut_list=[minv,maxv]
else:
if cut_list[0] >= minv:
cut_list = [minv] + cut_list
if cut_list[-1] <= maxv:
cut_list = cut_list + [maxv]
vlist_output=[[cut_list[x],cut_list[x+1]] for x in
range(int(len(cut_list)-1))]
return vlist_output
# |
# |
# \ | /
# \|/
# V
###############################
# #
# significant velocity ranges #
# #
###############################
# |
# |
# \ | /
# \|/
# V
def placegaussians(full_data, Bayes_threshold, quiet,
seed, extra_gaussians=3,lfwhm_mean=None,lfwhm_sig=None,logN1_mean=None,logN1_sigma=None):
'''
Manages the process of placing and evaluating gaussian features.
Parameters:
data (dict): observed spectra and other observed quantities (see
Main function)
Bayes_threshold (float): Bayes Factor required for a model to be
preferred
quiet (boolean): Whether or not to print outputs to terminal
best_result (str): Which result from the markov chain is to be reported
as the best result 'median', 'median_actual', 'max' (note, all are
printed if quiet = False). 'median' returns the median position of
each parameter (may not correspond to an actual set of parameters
measured), 'median_actual' finds the point in the flattened chain
closest to the medians of each parameter and compares the lnprob
here to that of the actual medians, returns the one with better
lnprob, and 'max' returns the set of parameters with the highest
lnprob.
Returns:
array: Full list of accepted parameters with upper and lower bounds of
credibile intervals. Format: [[1min, 1best, 1max], [2min, 2best,
2max],...] for parameters 1, 2, etc.
'''
accepted_full = []
for vel_range in full_data['sig_vel_ranges']:
print('current vel range = '+str(vel_range))
last_accepted_full = []
[min_vel, max_vel] = vel_range
data = trimdata(full_data, min_vel, max_vel)
num_gauss = 1
keep_going = True
extra = 0
null_evidence = nullevidence(data)
print(str([data['source_name'],vel_range,null_evidence]))
prev_evidence | |
...]]:
"""Find all indices of occurrences of self in patt. If the optional colours
are provided, in an occurrences the colours of the patterns have to match the
colours of the permutation.
Examples:
>>> list(Perm((2, 0, 1)).occurrences_in(Perm((5, 3, 0, 4, 2, 1))))
[(0, 1, 3), (0, 2, 3), (0, 2, 4), (0, 2, 5), (1, 2, 4), (1, 2, 5)]
>>> list(Perm((1, 0)).occurrences_in(Perm((1, 2, 3, 0))))
[(0, 3), (1, 3), (2, 3)]
>>> list(Perm((0,)).occurrences_in(Perm((1, 2, 3, 0))))
[(0,), (1,), (2,), (3,)]
>>> list(Perm().occurrences_in(Perm((1, 2, 3, 0))))
[()]
"""
self_colours, patt_colours = (None, None) if len(args) < 2 else args
n, patt = len(self), patt.get_perm()
if n == 0:
yield ()
return
if n > len(patt):
return
# The indices of the occurrence in perm
occurrence_indices = [0] * n
pattern_details = self._pattern_details()
# Define function that works with the above defined variables
# i is the index of the element in perm that is to be considered
# k is how many elements of the perm have already been added to
# occurrence
def occurrences(i, k):
elements_remaining = len(patt) - i
elements_needed = n - k
# lfi = left floor index
# lci = left ceiling index
# lbp = lower bound pre-computation
# ubp = upper bound pre-computation
lfi, lci, lbp, ubp = pattern_details[k]
# Set the bounds for the new element
if lfi == -1:
# The new element of the occurrence must be at least self[k];
# i.e., the k-th element of the pattern
# In this case, lbp = self[k]
lower_bound = lbp
else:
# The new element of the occurrence must be at least as far
# from its left floor as self[k] is from its left floor
# In this case, lbp = self[k] - self[lfi]
occurrence_left_floor = patt[occurrence_indices[lfi]]
lower_bound = occurrence_left_floor + lbp
if lci == -1:
# The new element of the occurrence must be at least as less
# than its maximum possible element---i.e., len(perm)---as
# self[k] is to its maximum possible element---i.e., len(self)
# In this case, ubp = len(self) - self[k]
upper_bound = len(patt) - ubp
else:
# The new element of the occurrence must be at least as less
# than its left ceiling as self[k] is to its left ceiling
# In this case, ubp = self[lci] - self[k]
upper_bound = patt[occurrence_indices[lci]] - ubp
# Loop over remaining elements of perm (actually i, the index)
while True:
if elements_remaining < elements_needed:
# Can't form an occurrence with remaining elements
return
element = patt[i]
compare_colours = (
self_colours is None or patt_colours[i] == self_colours[k]
)
if compare_colours and lower_bound <= element <= upper_bound:
occurrence_indices[k] = i
if elements_needed == 1:
yield tuple(occurrence_indices)
else:
yield from occurrences(i + 1, k + 1)
i, elements_remaining = i + 1, elements_remaining - 1
yield from occurrences(0, 0)
def occurrences_of(self, patt: "Patt") -> Union[Iterator[Tuple[int, ...]]]:
"""Find all indices of occurrences of patt in self. This method is complementary
to permuta.Perm.occurrences_in. It just calls patt.occurrences_in(self)
internally. See permuta.Perm.occurrences_in for documentation.
Examples:
>>> list(Perm((5, 3, 0, 4, 2, 1)).occurrences_of(Perm((2, 0, 1))))
[(0, 1, 3), (0, 2, 3), (0, 2, 4), (0, 2, 5), (1, 2, 4), (1, 2, 5)]
>>> list(Perm((1, 2, 3, 0)).occurrences_of(Perm((1, 0))))
[(0, 3), (1, 3), (2, 3)]
>>> list(Perm((1, 2, 3, 0)).occurrences_of(Perm((0,))))
[(0,), (1,), (2,), (3,)]
>>> list(Perm((1, 2, 3, 0)).occurrences_of(Perm()))
[()]
"""
return patt.occurrences_in(self)
def left_floor_and_ceiling(self) -> Iterator[Tuple[int, int]]:
"""For each element, return the pair of indices of (largest less, smalllest
greater) to the left, if they exist. If not, -1 is used instead.
Examples:
>>> list(Perm((2, 5, 0, 3, 6, 4, 7, 1)).left_floor_and_ceiling())
[(-1, -1), (0, -1), (-1, 0), (0, 1), (1, -1), (3, 1), (4, -1), (2, 0)]
"""
deq: Deque[Tuple[int, int]] = collections.deque()
smallest, biggest = -1, -1
for idx, val in enumerate(self):
if idx == 0:
deq.append((val, idx))
smallest, biggest = val, val
yield (-1, -1)
elif val < smallest:
# Rotate until smallest val is at front
while deq[0][0] != smallest:
deq.rotate(-1)
yield (-1, deq[0][1])
deq.appendleft((val, idx))
smallest = val
elif val > biggest:
# Rotate until biggest val is at end
while deq[-1][0] != biggest:
deq.rotate(-1)
yield (deq[-1][1], -1)
deq.append((val, idx))
biggest = val
else:
while not deq[-1][0] <= val <= deq[0][0]:
deq.rotate(1)
yield (deq[-1][1], deq[0][1])
deq.appendleft((val, idx))
def _pattern_details(self) -> List[Tuple[int, int, int, int]]:
if self._cached_pattern_details is None:
self._cached_pattern_details = [
(
floor,
ceiling,
val if floor == -1 else val - self[floor],
len(self) - val if ceiling == -1 else self[ceiling] - val,
)
for val, (floor, ceiling) in zip(self, self.left_floor_and_ceiling())
]
return self._cached_pattern_details
def apply(self, iterable: Iterable[ApplyType]) -> Tuple[ApplyType, ...]:
"""Permute an iterable using the perm.
Examples:
>>> Perm((4, 1, 2, 0, 3)).apply((1, 2, 3, 4, 5))
(5, 2, 3, 1, 4)
>>> Perm((4, 1, 2, 0, 3)).apply("abcde")
('e', 'b', 'c', 'a', 'd')
"""
iterable = tuple(iterable)
assert len(iterable) == len(self)
return tuple(iterable[index] for index in self)
permute = apply
@staticmethod
def _is_sorted(lis: List[int]) -> bool:
return all(val == idx for idx, val in enumerate(lis))
@staticmethod
def _stack_sort(perm_slice: List[int]) -> List[int]:
"""Helper function for the stack sorting function on perms"""
n = len(perm_slice)
if n in (0, 1):
return perm_slice
max_i, max_v = max(enumerate(perm_slice), key=lambda pos_elem: pos_elem[1])
# Recursively solve without largest
if max_i == 0:
n_lis = Perm._stack_sort(perm_slice[1:n])
elif max_i == n - 1:
n_lis = Perm._stack_sort(perm_slice[0 : n - 1])
else:
n_lis = Perm._stack_sort(perm_slice[0:max_i])
n_lis.extend(Perm._stack_sort(perm_slice[max_i + 1 : n]))
n_lis.append(max_v)
return n_lis
def stack_sort(self) -> "Perm":
"""Stack sorting the permutation"""
return Perm(Perm._stack_sort(list(self)))
def stack_sortable(self) -> bool:
"""Returns true if perm is stack sortable."""
return self.stack_sort().is_increasing()
def pop_stack_sort(self) -> "Perm":
"""Pop-stack sorting the permutation"""
stack: Deque[int] = collections.deque()
result: List[int] = []
for num in self:
if stack and num > stack[0]:
result.extend(stack)
stack.clear()
stack.appendleft(num)
result.extend(stack)
return Perm(result)
def pop_stack_sortable(self) -> bool:
"""Returns true if perm is pop-stack sortable."""
return self.pop_stack_sort().is_increasing()
@staticmethod
def _bubble_sort(perm_slice: List[int]) -> List[int]:
"""Helper function for the bubble sorting function on perms"""
n = len(perm_slice)
if n in (0, 1):
return perm_slice
max_i, max_v = max(enumerate(perm_slice), key=lambda pos_elem: pos_elem[1])
# Recursively solve without largest
if max_i == 0:
n_lis = perm_slice[1:n]
elif max_i == n - 1:
n_lis = Perm._bubble_sort(perm_slice[0 : n - 1])
else:
n_lis = Perm._bubble_sort(perm_slice[0:max_i])
n_lis.extend(perm_slice[max_i + 1 : n])
n_lis.append(max_v)
return n_lis
def bubble_sort(self) -> "Perm":
"""Bubble sorting the permutation"""
return Perm(Perm._bubble_sort(list(self)))
def bubble_sortable(self) -> bool:
"""Returns true if perm is stack sortable."""
return self.bubble_sort().is_increasing()
@staticmethod
def _quick_sort(perm_slice: List[int]) -> List[int]:
"""Helper function for the quick sorting function on perms"""
assert not perm_slice or set(perm_slice) == set(
range(min(perm_slice), max(perm_slice) + 1)
)
n = len(perm_slice)
if n == 0:
return perm_slice
maxind = -1
# Note that perm does not need standardizing as sfp uses left to right maxima.
for maxind in Perm(perm_slice).strong_fixed_points():
pass
if maxind != -1:
lis: List[int] = (
Perm._quick_sort(perm_slice[:maxind])
+ [perm_slice[maxind]]
+ Perm._quick_sort(perm_slice[maxind + 1 :])
)
else:
firstval = perm_slice[0]
lis = (
list(filter(lambda x: x < firstval, perm_slice))
+ [perm_slice[0]]
+ list(filter(lambda x: x > firstval, perm_slice))
)
return lis
def quick_sort(self) -> "Perm":
"""Quick sorting the permutation"""
return Perm(Perm._quick_sort(list(self)))
def quick_sortable(self) -> bool:
"""Returns true if perm is quicksort sortable."""
return self.quick_sort().is_increasing()
def bkv_sortable(self, patterns: Tuple[Patt, ...] = ()) -> bool:
"""Check if a permutation is BKV sortable.
See:
https://arxiv.org/pdf/1907.08142.pdf
https://arxiv.org/pdf/2004.01812.pdf
"""
# See
n = len(self)
inp = collections.deque(self)
# the right stack read from top to bottom
# the left stack read from top to bottom
right_stack: Deque[int] = collections.deque([])
left_stack: Deque[int] = collections.deque([])
expected = 0
print(self)
while expected < n:
print("inp", inp)
print("left_stack", left_stack)
print("right_stack", right_stack)
print("------------------------------")
if inp:
right_stack.appendleft(inp[0])
if Perm.to_standard(right_stack).avoids(*patterns):
inp.popleft()
continue
right_stack.popleft()
if right_stack:
left_stack.appendleft(right_stack[0])
if Perm.to_standard(left_stack).is_increasing():
right_stack.popleft()
continue
left_stack.popleft()
assert left_stack
# Normally, we would gather elements from left stack but since we only care
| |
# -*- coding: utf-8 -*-
"""
Zurich Instruments LabOne Python API Example
Python API Example for the Software Trigger (ziDAQRecorder) Core Module. This
example demonstrates how to obtain bursts of demodulator data when a
demodulator's R value is larger than a threshold (defined above the lowpass
filtered value of the demodulator's R) value using an tracking edge trigger.
The ziDAQRecorder Module implements software triggering which operates
analogously to the types of triggering found in laboratory oscilloscopes. The
ziDAQRecorder Module has a non-blocking (asynchronous) interface, it starts it's
own thread to communicate with the data server.
Note: This example requires a feedback cable between Signal Output 1 and Signal
Input 1 and changes the signal output's amplitude in order to create a signal
upon which to trigger.
"""
# Copyright 2016 Zurich Instruments AG
from __future__ import print_function
import time
import numpy as np
import zhinst.utils
def run_example(device_id, amplitude=0.25, do_plot=False):
"""Run the example: Record bursts of demodulator sample data when a
demodulator's R becomes larger than a specified threshold and a tracking
trigger using ziPython's Software Trigger (ziDAQRecorder) Module.
Requirements:
Hardware configuration: Connect signal output 1 to signal input 1 with a
BNC cable.
Arguments:
device_id (str): The ID of the device to run the example with. For
example, `dev2006` or `uhf-dev2006`.
amplitude (float, optional): The amplitude to set on the signal output.
do_plot (bool, optional): Specify whether to plot the recorded
data. Default is no plot output.
Returns:
data (dict of list): A list of data as returned by the Software Trigger's
read() command. The dict contains the subscribed and triggered data and
the software trigger's lowpass filter values.
Raises:
RuntimeError: If the device is not "discoverable" from the API.
See the "LabOne Programing Manual" for further help, available:
- On Windows via the Start-Menu:
Programs -> Zurich Instruments -> Documentation
- On Linux in the LabOne .tar.gz archive in the "Documentation"
sub-folder.
"""
apilevel_example = 6 # The API level supported by this example.
# Call a zhinst utility function that returns:
# - an API session `daq` in order to communicate with devices via the data server.
# - the device ID string that specifies the device branch in the server's node hierarchy.
# - the device's discovery properties.
err_msg = "This example only supports instruments with demodulators."
(daq, device, props) = zhinst.utils.create_api_session(device_id, apilevel_example,
required_devtype='.*LI|.*IA|.*IS',
required_err_msg=err_msg)
zhinst.utils.api_server_version_check(daq)
# Create a base configuration: Disable all available outputs, awgs, demods, scopes,...
zhinst.utils.disable_everything(daq, device)
# Now configure the instrument for this experiment. The following channels
# and indices work on all device configurations. The values below may be
# changed if the instrument has multiple input/output channels and/or either
# the Multifrequency or Multidemodulator options installed.
out_channel = 0
out_mixer_channel = zhinst.utils.default_output_mixer_channel(props)
in_channel = 0
demod_index = 0
osc_index = 0
demod_rate = 10e3
time_constant = 0.01
frequency = 400e3
exp_setting = [['/%s/sigins/%d/ac' % (device, in_channel), 0],
['/%s/sigins/%d/imp50' % (device, in_channel), 0],
['/%s/sigins/%d/range' % (device, in_channel), 3*amplitude],
['/%s/demods/%d/enable' % (device, demod_index), 1],
['/%s/demods/%d/rate' % (device, demod_index), demod_rate],
['/%s/demods/%d/adcselect' % (device, demod_index), in_channel],
['/%s/demods/%d/order' % (device, demod_index), 4],
['/%s/demods/%d/timeconstant' % (device, demod_index), time_constant],
['/%s/demods/%d/oscselect' % (device, demod_index), osc_index],
['/%s/demods/%d/harmonic' % (device, demod_index), 1],
['/%s/oscs/%d/freq' % (device, osc_index), frequency],
['/%s/sigouts/%d/on' % (device, out_channel), 1],
['/%s/sigouts/%d/enables/%d' % (device, out_channel, out_mixer_channel), 1],
['/%s/sigouts/%d/range' % (device, out_channel), 1],
['/%s/sigouts/%d/amplitudes/%d' % (device, out_channel, out_mixer_channel), amplitude]]
# Some other device-type dependent configuration may be required. For
# example, disable the signal inputs `diff` and the signal outputs `add` for
# HF2 instruments.
if props['devicetype'].startswith('HF2'):
exp_setting.append(['/%s/sigins/%d/diff' % (device, in_channel), 0])
exp_setting.append(['/%s/sigouts/%d/add' % (device, out_channel), 0])
daq.set(exp_setting)
# Wait for the demodulator filter to settle.
timeconstant_set = daq.getDouble('/%s/demods/%d/timeconstant' % (device, demod_index))
time.sleep(10*timeconstant_set)
# Perform a global synchronisation between the device and the data server:
# Ensure that 1. the settings have taken effect on the device before issuing
# the poll() command and 2. clear the API's data buffers. Note: the sync()
# must be issued after waiting for the demodulator filter to settle above.
daq.sync()
# Create an instance of the Software Trigger Module (ziDAQRecorder class).
trigger = daq.record()
# Below we will generate num_pulses pulses on the signal outputs in order to
# demonstrate the triggering functionality. We'll configure the Software
# Trigger's threshold according to these levels.
sigouts_high = 1.5*amplitude
sigouts_low = 1.0*amplitude
num_pulses = 20
# Configure the Software Trigger Module.
trigger.set('trigger/device', device)
# We will trigger on the demodulator sample's R value.
trigger_path = '/%s/demods/%d/sample' % (device, demod_index)
triggernode = trigger_path + '.r'
trigger.set('trigger/0/triggernode', triggernode)
# Use an edge trigger.
trigger.set('trigger/0/type', 4) # 4 = tracking edge
trigger.set('trigger/0/bandwidth', 2)
# Trigger on the positive edge.
trigger.set('trigger/0/edge', 1) # 1 = positive
# The set the trigger level.
trigger_level = (sigouts_high - sigouts_low)/5
print("Setting trigger/0/level to {:.3f}.".format(trigger_level))
trigger.set('trigger/0/level', trigger_level)
# Set the trigger hysteresis to a percentage of the trigger level: This
# ensures that triggering is robust in the presence of noise. The trigger
# becomes armed when the signal passes through the hysteresis value and will
# then actually trigger if the signal additionally passes through the
# trigger level. The hysteresis value is applied negatively for a positive
# edge trigger relative to the trigger level (positively for a negative edge
# trigger).
trigger_hysteresis = 0.5*trigger_level
print("Setting trigger/0/hysteresis {:.3f}.".format(trigger_hysteresis))
trigger.set('trigger/0/hysteresis', trigger_hysteresis)
# The number of times to trigger.
trigger_count = int(num_pulses/2)
trigger.set('trigger/0/count', trigger_count)
trigger.set('trigger/0/holdoff/count', 0)
trigger.set('trigger/0/holdoff/time', 0.100)
trigger_delay = -0.050
trigger.set('trigger/0/delay', trigger_delay)
# The length of time to record each time we trigger
trigger_duration = 0.300
trigger.set('trigger/0/duration', trigger_duration)
# Do not extend the recording of the trigger frame if another
# trigger arrives within trigger_duration.
trigger.set('trigger/0/retrigger', 0)
# The size of the internal buffer used to record triggers (in seconds), this
# should be larger than trigger_duration.
buffer_size = 2*trigger_duration
trigger.set('trigger/buffersize', buffer_size)
trigger.set('trigger/historylength', 100)
# We subscribe to the same demodulator sample we're triggering on, but we
# could additionally subscribe to other node paths.
trigger.subscribe('/%s/demods/%d/sample' % (device, demod_index))
# Start the Software Trigger's thread.
trigger.execute()
time.sleep(2*buffer_size)
# Generate some pulses on the signal outputs by changing the signal output
# mixer's amplitude. This is for demonstration only and is not necessary to
# configure the module, we simply generate a signal upon which we can trigger.
daq.setDouble('/%s/sigouts/%d/amplitudes/%d' % (device, out_channel, out_mixer_channel),
sigouts_low)
daq.sync()
time.sleep(0.5)
for i in range(num_pulses):
daq.setDouble('/%s/sigouts/%d/amplitudes/%d' % (device, out_channel, out_mixer_channel),
sigouts_low*(1 + 0.05*np.random.uniform(-1, 1, 1)[0]))
daq.sync()
time.sleep(0.2)
daq.setDouble('/%s/sigouts/%d/amplitudes/%d' % (device, out_channel, out_mixer_channel),
sigouts_high*(1 + 0.05*np.random.uniform(-1, 1, 1)[0]))
daq.sync()
time.sleep(0.1)
# Check and display the progress.
progress = trigger.progress()
print("Recorder progress (acquiring {:d} triggers): {:.2%}.".format(trigger_count, progress[0]), end="\r")
# Check whether the recorder has finished.
if trigger.finished():
print("\nTrigger is finished.")
break
print("")
daq.setDouble('/%s/sigouts/%d/amplitudes/%d' % (device, out_channel, out_mixer_channel), sigouts_low)
# Wait for the Software Trigger's buffers to finish processing the triggers.
time.sleep(2*buffer_size)
# Read the Software Trigger's data, this command can also be executed before
# trigger.finished() is True. In that case data recorded up to that point in
# time is returned and we would still need to issue read() at the end to
# fetch the rest of the data.
return_flat_data_dict = True
data = trigger.read(return_flat_data_dict)
# Stop the Module (this is also ok if trigger.finished() is True).
trigger.finish()
# Stop the Module's thread and clear the memory.
trigger.clear()
# Check that the dictionary returned is non-empty.
assert data, "read() returned an empty data dictionary, did you subscribe to any paths?"
# Note: data could be empty if no data arrived, e.g., if the demods were
# disabled or had rate 0
assert trigger_path in data, "no data recorded: data dictionary has no key `{}`.".format(trigger_path)
samples = data[trigger_path]
print("Software Trigger's read() returned {} signal segments.".format(len(samples)))
assert len(samples) == trigger_count, \
"Unexpected number of signal segments returned: `{}`. Expected: `{}`.".format(len(samples), trigger_count)
# Get the sampling rate of the device's ADCs, the device clockbase.
clockbase = float(daq.getInt('/%s/clockbase' % device))
# Use the clockbase to calculate the duration of the first signal segment's
| |
versionadded:: 2.0
Attributes
------------
name: :class:`str`
The name of the group. If not given, it defaults to a lower-case
kebab-case version of the class name.
description: :class:`str`
The description of the group. This shows up in the UI to describe
the group. If not given, it defaults to the docstring of the
class shortened to 100 characters.
default_permissions: Optional[:class:`~discord.Permissions`]
The default permissions that can execute this group on Discord. Note
that server administrators can override this value in the client.
Setting an empty permissions field will disallow anyone except server
administrators from using the command in a guild.
Due to a Discord limitation, this does not work on subcommands.
guild_only: :class:`bool`
Whether the group should only be usable in guild contexts.
Defaults to ``False``.
Due to a Discord limitation, this does not work on subcommands.
parent: Optional[:class:`Group`]
The parent group. ``None`` if there isn't one.
"""
__discord_app_commands_group_children__: ClassVar[List[Union[Command[Any, ..., Any], Group]]] = []
__discord_app_commands_skip_init_binding__: bool = False
__discord_app_commands_group_name__: str = MISSING
__discord_app_commands_group_description__: str = MISSING
__discord_app_commands_guild_only__: bool = MISSING
__discord_app_commands_default_permissions__: Optional[Permissions] = MISSING
__discord_app_commands_has_module__: bool = False
def __init_subclass__(
cls,
*,
name: str = MISSING,
description: str = MISSING,
guild_only: bool = MISSING,
default_permissions: Optional[Permissions] = MISSING,
) -> None:
if not cls.__discord_app_commands_group_children__:
children: List[Union[Command[Any, ..., Any], Group]] = [
member for member in cls.__dict__.values() if isinstance(member, (Group, Command)) and member.parent is None
]
cls.__discord_app_commands_group_children__ = children
found = set()
for child in children:
if child.name in found:
raise TypeError(f'Command {child.name!r} is a duplicate')
found.add(child.name)
if len(children) > 25:
raise TypeError('groups cannot have more than 25 commands')
if name is MISSING:
cls.__discord_app_commands_group_name__ = validate_name(_to_kebab_case(cls.__name__))
else:
cls.__discord_app_commands_group_name__ = validate_name(name)
if description is MISSING:
if cls.__doc__ is None:
cls.__discord_app_commands_group_description__ = '…'
else:
cls.__discord_app_commands_group_description__ = _shorten(cls.__doc__)
else:
cls.__discord_app_commands_group_description__ = description
if guild_only is not MISSING:
cls.__discord_app_commands_guild_only__ = guild_only
if default_permissions is not MISSING:
cls.__discord_app_commands_default_permissions__ = default_permissions
if cls.__module__ != __name__:
cls.__discord_app_commands_has_module__ = True
def __init__(
self,
*,
name: str = MISSING,
description: str = MISSING,
parent: Optional[Group] = None,
guild_ids: Optional[List[int]] = None,
guild_only: bool = MISSING,
default_permissions: Optional[Permissions] = MISSING,
):
cls = self.__class__
self.name: str = validate_name(name) if name is not MISSING else cls.__discord_app_commands_group_name__
self.description: str = description or cls.__discord_app_commands_group_description__
self._attr: Optional[str] = None
self._owner_cls: Optional[Type[Any]] = None
self._guild_ids: Optional[List[int]] = guild_ids or getattr(cls, '__discord_app_commands_default_guilds__', None)
if default_permissions is MISSING:
if cls.__discord_app_commands_default_permissions__ is MISSING:
default_permissions = None
else:
default_permissions = cls.__discord_app_commands_default_permissions__
self.default_permissions: Optional[Permissions] = default_permissions
if guild_only is MISSING:
if cls.__discord_app_commands_guild_only__ is MISSING:
guild_only = False
else:
guild_only = cls.__discord_app_commands_guild_only__
self.guild_only: bool = guild_only
if not self.description:
raise TypeError('groups must have a description')
self.parent: Optional[Group] = parent
self.module: Optional[str]
if cls.__discord_app_commands_has_module__:
self.module = cls.__module__
else:
try:
# This is pretty hacky
# It allows the module to be fetched if someone just constructs a bare Group object though.
self.module = inspect.currentframe().f_back.f_globals['__name__'] # type: ignore
except (AttributeError, IndexError):
self.module = None
self._children: Dict[str, Union[Command, Group]] = {}
bindings: Dict[Group, Group] = {}
for child in self.__discord_app_commands_group_children__:
# commands and groups created directly in this class (no parent)
copy = (
child._copy_with(parent=self, binding=self, bindings=bindings, set_on_binding=False)
if not cls.__discord_app_commands_skip_init_binding__
else child
)
self._children[copy.name] = copy
if copy._attr and not cls.__discord_app_commands_skip_init_binding__:
setattr(self, copy._attr, copy)
if parent is not None:
if parent.parent is not None:
raise ValueError('groups can only be nested at most one level')
parent.add_command(self)
def __set_name__(self, owner: Type[Any], name: str) -> None:
self._attr = name
self.module = owner.__module__
self._owner_cls = owner
def _copy_with(
self,
*,
parent: Optional[Group],
binding: Binding,
bindings: MutableMapping[Group, Group] = MISSING,
set_on_binding: bool = True,
) -> Group:
bindings = {} if bindings is MISSING else bindings
cls = self.__class__
copy = cls.__new__(cls)
copy.name = self.name
copy._guild_ids = self._guild_ids
copy.description = self.description
copy.parent = parent
copy.module = self.module
copy.default_permissions = self.default_permissions
copy.guild_only = self.guild_only
copy._attr = self._attr
copy._owner_cls = self._owner_cls
copy._children = {}
bindings[self] = copy
for child in self._children.values():
child_copy = child._copy_with(parent=copy, binding=binding, bindings=bindings)
child_copy.parent = copy
copy._children[child_copy.name] = child_copy
if isinstance(child_copy, Group) and child_copy._attr and set_on_binding:
if binding.__class__ is child_copy._owner_cls:
setattr(binding, child_copy._attr, child_copy)
elif child_copy._owner_cls is copy.__class__:
setattr(copy, child_copy._attr, child_copy)
if copy._attr and set_on_binding:
setattr(parent or binding, copy._attr, copy)
return copy
def to_dict(self) -> Dict[str, Any]:
# If this has a parent command then it's part of a subcommand group
# Otherwise, it's just a regular command
option_type = 1 if self.parent is None else AppCommandOptionType.subcommand_group.value
base: Dict[str, Any] = {
'name': self.name,
'description': self.description,
'type': option_type,
'options': [child.to_dict() for child in self._children.values()],
}
if self.parent is None:
base['dm_permission'] = not self.guild_only
base['default_member_permissions'] = self.default_permissions and self.default_permissions.value
return base
@property
def root_parent(self) -> Optional[Group]:
"""Optional[:class:`Group`]: The parent of this group."""
return self.parent
@property
def qualified_name(self) -> str:
""":class:`str`: Returns the fully qualified group name.
The qualified name includes the parent name as well. For example,
in a group like ``/foo bar`` the qualified name is ``foo bar``.
"""
if self.parent is None:
return self.name
return f'{self.parent.name} {self.name}'
def _get_internal_command(self, name: str) -> Optional[Union[Command[Any, ..., Any], Group]]:
return self._children.get(name)
@property
def commands(self) -> List[Union[Command[Any, ..., Any], Group]]:
"""List[Union[:class:`Command`, :class:`Group`]]: The commands that this group contains."""
return list(self._children.values())
def walk_commands(self) -> Generator[Union[Command[Any, ..., Any], Group], None, None]:
"""An iterator that recursively walks through all commands that this group contains.
Yields
---------
Union[:class:`Command`, :class:`Group`]
The commands in this group.
"""
for command in self._children.values():
yield command
if isinstance(command, Group):
yield from command.walk_commands()
async def on_error(self, interaction: Interaction, error: AppCommandError) -> None:
"""|coro|
A callback that is called when a child's command raises an :exc:`AppCommandError`.
To get the command that failed, :attr:`discord.Interaction.command` should be used.
The default implementation does nothing.
Parameters
-----------
interaction: :class:`~discord.Interaction`
The interaction that is being handled.
error: :exc:`AppCommandError`
The exception that was raised.
"""
pass
def error(self, coro: ErrorFunc) -> ErrorFunc:
"""A decorator that registers a coroutine as a local error handler.
The local error handler is called whenever an exception is raised in a child command.
The error handler must take 2 parameters, the interaction and the error.
The error passed will be derived from :exc:`AppCommandError`.
Parameters
-----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the local error handler.
Raises
-------
TypeError
The coroutine passed is not actually a coroutine, or is an invalid coroutine.
"""
if not inspect.iscoroutinefunction(coro):
raise TypeError('The error handler must be a coroutine.')
params = inspect.signature(coro).parameters
if len(params) != 2:
raise TypeError('The error handler must have 2 parameters.')
self.on_error = coro # type: ignore
return coro
async def interaction_check(self, interaction: Interaction) -> bool:
"""|coro|
A callback that is called when an interaction happens within the group
that checks whether a command inside the group should be executed.
This is useful to override if, for example, you want to ensure that the
interaction author is a given user.
The default implementation of this returns ``True``.
.. note::
If an exception occurs within the body then the check
is considered a failure and error handlers such as
:meth:`on_error` is called. See :exc:`AppCommandError`
for more information.
Parameters
-----------
interaction: :class:`~discord.Interaction`
The interaction that occurred.
Returns
---------
:class:`bool`
Whether the view children's callbacks should be called.
"""
return True
def add_command(self, command: Union[Command[Any, ..., Any], Group], /, *, override: bool = False) -> None:
"""Adds a command or group to this group's internal list of commands.
Parameters
-----------
command: Union[:class:`Command`, :class:`Group`]
The command or group to add.
override: :class:`bool`
Whether to override a pre-existing command or group with the same name.
If ``False`` then an exception is raised.
Raises
-------
CommandAlreadyRegistered
The command or group is already registered. Note that the :attr:`CommandAlreadyRegistered.guild_id`
attribute will always be ``None`` in this case.
ValueError
There are too many commands already registered or the group is too
deeply nested.
TypeError
The wrong command type was passed.
"""
if not isinstance(command, (Command, Group)):
raise TypeError(f'expected Command or Group not {command.__class__!r}')
if isinstance(command, Group) and self.parent is not None:
# In a tree | |
0.1793, "depth": 13}
if obj[10]<=1.0:
return 'False'
elif obj[10]>1.0:
return 'False'
else: return 'False'
elif obj[6]>3:
# {"feature": "Restaurant20to50", "instances": 4, "metric_value": 0.25, "depth": 13}
if obj[10]<=-1.0:
return 'False'
elif obj[10]>-1.0:
return 'True'
else: return 'True'
else: return 'False'
else: return 'False'
elif obj[4]>3:
# {"feature": "Bar", "instances": 26, "metric_value": 0.3798, "depth": 11}
if obj[8]<=0.0:
# {"feature": "Restaurant20to50", "instances": 16, "metric_value": 0.2897, "depth": 12}
if obj[10]>0.0:
# {"feature": "Education", "instances": 9, "metric_value": 0.1944, "depth": 13}
if obj[6]<=0:
return 'False'
elif obj[6]>0:
return 'False'
else: return 'False'
elif obj[10]<=0.0:
# {"feature": "Education", "instances": 7, "metric_value": 0.381, "depth": 13}
if obj[6]<=1:
return 'False'
elif obj[6]>1:
return 'False'
else: return 'False'
else: return 'False'
elif obj[8]>0.0:
# {"feature": "Education", "instances": 10, "metric_value": 0.4444, "depth": 12}
if obj[6]>0:
# {"feature": "Restaurant20to50", "instances": 9, "metric_value": 0.4167, "depth": 13}
if obj[10]<=1.0:
return 'True'
elif obj[10]>1.0:
return 'False'
else: return 'False'
elif obj[6]<=0:
return 'False'
else: return 'False'
else: return 'False'
else: return 'False'
elif obj[7]<=1:
# {"feature": "Education", "instances": 19, "metric_value": 0.4164, "depth": 10}
if obj[6]>0:
# {"feature": "Restaurant20to50", "instances": 10, "metric_value": 0.4, "depth": 11}
if obj[10]<=1.0:
# {"feature": "Age", "instances": 9, "metric_value": 0.4, "depth": 12}
if obj[4]<=3:
# {"feature": "Bar", "instances": 5, "metric_value": 0.2667, "depth": 13}
if obj[8]>0.0:
return 'True'
elif obj[8]<=0.0:
return 'True'
else: return 'True'
elif obj[4]>3:
# {"feature": "Bar", "instances": 4, "metric_value": 0.3333, "depth": 13}
if obj[8]<=0.0:
return 'True'
elif obj[8]>0.0:
return 'False'
else: return 'False'
else: return 'False'
elif obj[10]>1.0:
return 'False'
else: return 'False'
elif obj[6]<=0:
# {"feature": "Restaurant20to50", "instances": 9, "metric_value": 0.0, "depth": 11}
if obj[10]<=1.0:
return 'False'
elif obj[10]>1.0:
return 'True'
else: return 'True'
else: return 'False'
else: return 'False'
elif obj[3]<=0:
# {"feature": "Age", "instances": 79, "metric_value": 0.4525, "depth": 9}
if obj[4]<=6:
# {"feature": "Occupation", "instances": 72, "metric_value": 0.4806, "depth": 10}
if obj[7]<=17:
# {"feature": "Education", "instances": 63, "metric_value": 0.4916, "depth": 11}
if obj[6]<=3:
# {"feature": "Bar", "instances": 62, "metric_value": 0.4907, "depth": 12}
if obj[8]<=2.0:
# {"feature": "Restaurant20to50", "instances": 61, "metric_value": 0.4913, "depth": 13}
if obj[10]>-1.0:
return 'False'
elif obj[10]<=-1.0:
return 'False'
else: return 'False'
elif obj[8]>2.0:
return 'True'
else: return 'True'
elif obj[6]>3:
return 'True'
else: return 'True'
elif obj[7]>17:
# {"feature": "Education", "instances": 9, "metric_value": 0.2222, "depth": 11}
if obj[6]>1:
return 'False'
elif obj[6]<=1:
# {"feature": "Bar", "instances": 4, "metric_value": 0.3333, "depth": 12}
if obj[8]>0.0:
# {"feature": "Restaurant20to50", "instances": 3, "metric_value": 0.3333, "depth": 13}
if obj[10]<=2.0:
return 'False'
elif obj[10]>2.0:
return 'False'
else: return 'False'
elif obj[8]<=0.0:
return 'True'
else: return 'True'
else: return 'True'
else: return 'False'
elif obj[4]>6:
return 'False'
else: return 'False'
else: return 'False'
else: return 'False'
elif obj[11]>0:
# {"feature": "Education", "instances": 177, "metric_value": 0.4858, "depth": 7}
if obj[6]<=2:
# {"feature": "Occupation", "instances": 144, "metric_value": 0.4859, "depth": 8}
if obj[7]<=14.164944200311755:
# {"feature": "Bar", "instances": 123, "metric_value": 0.4902, "depth": 9}
if obj[8]>-1.0:
# {"feature": "Restaurant20to50", "instances": 121, "metric_value": 0.4909, "depth": 10}
if obj[10]<=2.0:
# {"feature": "Age", "instances": 119, "metric_value": 0.4941, "depth": 11}
if obj[4]>0:
# {"feature": "Children", "instances": 93, "metric_value": 0.4985, "depth": 12}
if obj[5]<=0:
# {"feature": "Gender", "instances": 59, "metric_value": 0.4982, "depth": 13}
if obj[3]<=0:
return 'False'
elif obj[3]>0:
return 'False'
else: return 'False'
elif obj[5]>0:
# {"feature": "Gender", "instances": 34, "metric_value": 0.4971, "depth": 13}
if obj[3]>0:
return 'True'
elif obj[3]<=0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[4]<=0:
# {"feature": "Gender", "instances": 26, "metric_value": 0.3669, "depth": 12}
if obj[3]<=0:
# {"feature": "Children", "instances": 13, "metric_value": 0.2577, "depth": 13}
if obj[5]<=0:
return 'True'
elif obj[5]>0:
return 'True'
else: return 'True'
elif obj[3]>0:
# {"feature": "Children", "instances": 13, "metric_value": 0.4718, "depth": 13}
if obj[5]<=0:
return 'False'
elif obj[5]>0:
return 'False'
else: return 'False'
else: return 'False'
else: return 'True'
elif obj[10]>2.0:
return 'True'
else: return 'True'
elif obj[8]<=-1.0:
return 'False'
else: return 'False'
elif obj[7]>14.164944200311755:
# {"feature": "Bar", "instances": 21, "metric_value": 0.3429, "depth": 9}
if obj[8]>0.0:
# {"feature": "Restaurant20to50", "instances": 15, "metric_value": 0.3636, "depth": 10}
if obj[10]<=1.0:
# {"feature": "Age", "instances": 11, "metric_value": 0.3636, "depth": 11}
if obj[4]<=4:
# {"feature": "Gender", "instances": 9, "metric_value": 0.4, "depth": 12}
if obj[3]>0:
# {"feature": "Children", "instances": 5, "metric_value": 0.3, "depth": 13}
if obj[5]<=0:
return 'False'
elif obj[5]>0:
return 'False'
else: return 'False'
elif obj[3]<=0:
# {"feature": "Children", "instances": 4, "metric_value": 0.5, "depth": 13}
if obj[5]<=0:
return 'True'
elif obj[5]>0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[4]>4:
return 'True'
else: return 'True'
elif obj[10]>1.0:
return 'True'
else: return 'True'
elif obj[8]<=0.0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[6]>2:
# {"feature": "Restaurant20to50", "instances": 33, "metric_value": 0.3663, "depth": 8}
if obj[10]<=1.0:
# {"feature": "Occupation", "instances": 26, "metric_value": 0.3067, "depth": 9}
if obj[7]>3:
# {"feature": "Children", "instances": 17, "metric_value": 0.1412, "depth": 10}
if obj[5]<=0:
return 'False'
elif obj[5]>0:
# {"feature": "Age", "instances": 5, "metric_value": 0.4, "depth": 11}
if obj[4]>0:
# {"feature": "Gender", "instances": 4, "metric_value": 0.3333, "depth": 12}
if obj[3]>0:
# {"feature": "Bar", "instances": 3, "metric_value": 0.0, "depth": 13}
if obj[8]>0.0:
return 'False'
elif obj[8]<=0.0:
return 'True'
else: return 'True'
elif obj[3]<=0:
return 'True'
else: return 'True'
elif obj[4]<=0:
return 'False'
else: return 'False'
else: return 'False'
elif obj[7]<=3:
# {"feature": "Children", "instances": 9, "metric_value": 0.4333, "depth": 10}
if obj[5]<=0:
# {"feature": "Age", "instances": 5, "metric_value": 0.4, "depth": 11}
if obj[4]>4:
# {"feature": "Bar", "instances": 4, "metric_value": 0.3333, "depth": 12}
if obj[8]<=0.0:
# {"feature": "Gender", "instances": 3, "metric_value": 0.3333, "depth": 13}
if obj[3]<=0:
return 'False'
elif obj[3]>0:
return 'False'
else: return 'False'
elif obj[8]>0.0:
return 'True'
else: return 'True'
elif obj[4]<=4:
return 'True'
else: return 'True'
elif obj[5]>0:
# {"feature": "Age", "instances": 4, "metric_value": 0.3333, "depth": 11}
if obj[4]>1:
# {"feature": "Gender", "instances": 3, "metric_value": 0.4444, "depth": 12}
if obj[3]<=1:
# {"feature": "Bar", "instances": 3, "metric_value": 0.4444, "depth": 13}
if obj[8]<=0.0:
return 'False'
else: return 'False'
else: return 'False'
elif obj[4]<=1:
return 'False'
else: return 'False'
else: return 'False'
else: return 'False'
elif obj[10]>1.0:
# {"feature": "Age", "instances": 7, "metric_value": 0.2381, "depth": 9}
if obj[4]>0:
# {"feature": "Gender", "instances": 6, "metric_value": 0.1667, "depth": 10}
if obj[3]<=0:
return 'True'
elif obj[3]>0:
# {"feature": "Occupation", "instances": 2, "metric_value": 0.0, "depth": 11}
if obj[7]>12:
return 'True'
elif obj[7]<=12:
return 'False'
else: return 'False'
else: return 'True'
elif obj[4]<=0:
return 'False'
else: return 'False'
else: return 'True'
else: return 'False'
else: return 'True'
elif obj[1]>3:
# {"feature": "Age", "instances": 157, "metric_value": 0.4687, "depth": 6}
if obj[4]<=4:
# {"feature": "Occupation", "instances": 126, "metric_value": 0.4834, "depth": 7}
if obj[7]<=8.73015873015873:
# {"feature": "Bar", "instances": 67, "metric_value": 0.4636, "depth": 8}
if obj[8]<=3.0:
# {"feature": "Education", "instances": 66, "metric_value": 0.4657, "depth": 9}
if obj[6]<=1:
# {"feature": "Restaurant20to50", "instances": 36, "metric_value": 0.419, "depth": 10}
if obj[10]>-1.0:
# {"feature": "Children", "instances": 35, "metric_value": 0.4305, "depth": 11}
if obj[5]<=0:
# {"feature": "Gender", "instances": 20, "metric_value": 0.4101, "depth": 12}
if obj[3]<=0:
# {"feature": "Direction_same", "instances": 11, "metric_value": 0.4628, "depth": 13}
if obj[11]<=0:
return 'True'
else: return 'True'
elif obj[3]>0:
# {"feature": "Direction_same", "instances": 9, "metric_value": 0.3457, "depth": 13}
if obj[11]<=0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[5]>0:
# {"feature": "Gender", "instances": 15, "metric_value": 0.4267, "depth": 12}
if obj[3]>0:
# {"feature": "Direction_same", "instances": 10, "metric_value": 0.48, "depth": 13}
if obj[11]<=0:
return 'True'
else: return 'True'
elif obj[3]<=0:
# {"feature": "Direction_same", "instances": 5, "metric_value": 0.32, "depth": 13}
if obj[11]<=0:
return 'True'
else: return 'True'
else: return 'True'
else: return 'True'
elif obj[10]<=-1.0:
return 'False'
else: return 'False'
elif obj[6]>1:
# {"feature": "Restaurant20to50", "instances": 30, "metric_value": 0.4494, "depth": 10}
if obj[10]>0.0:
# {"feature": "Gender", "instances": 27, "metric_value": 0.4937, "depth": 11}
if obj[3]<=0:
# {"feature": "Children", "instances": 20, "metric_value": 0.4933, "depth": 12}
if obj[5]<=0:
# {"feature": "Direction_same", "instances": 15, "metric_value": 0.4978, "depth": 13}
if obj[11]<=0:
return 'True'
else: return 'True'
elif obj[5]>0:
# {"feature": "Direction_same", "instances": 5, "metric_value": 0.48, "depth": 13}
if obj[11]<=0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[3]>0:
# {"feature": "Children", "instances": 7, "metric_value": 0.4857, "depth": 12}
if obj[5]<=0:
# {"feature": "Direction_same", "instances": 5, "metric_value": 0.48, "depth": 13}
if obj[11]<=0:
return 'False'
else: return 'False'
elif obj[5]>0:
# {"feature": "Direction_same", "instances": 2, "metric_value": 0.5, "depth": 13}
if obj[11]<=0:
return 'True'
else: return 'True'
else: return 'True'
else: return 'False'
elif obj[10]<=0.0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[8]>3.0:
return 'False'
else: return 'False'
elif obj[7]>8.73015873015873:
# {"feature": "Bar", "instances": 59, "metric_value": 0.4588, "depth": 8}
if obj[8]<=1.0:
# {"feature": "Gender", "instances": 42, "metric_value": 0.458, "depth": 9}
if obj[3]>0:
# {"feature": "Restaurant20to50", "instances": 21, "metric_value": 0.3556, "depth": 10}
if obj[10]<=1.0:
# {"feature": "Children", "instances": 15, "metric_value": 0.4405, "depth": 11}
if obj[5]<=0:
# {"feature": "Education", "instances": 8, "metric_value": 0.375, "depth": 12}
if obj[6]<=2:
# {"feature": "Direction_same", "instances": 6, "metric_value": 0.5, "depth": 13}
if obj[11]<=0:
return 'False'
else: return 'False'
elif obj[6]>2:
return 'False'
else: return 'False'
elif obj[5]>0:
# {"feature": "Education", "instances": 7, "metric_value": 0.3429, "depth": 12}
if obj[6]<=2:
# {"feature": "Direction_same", "instances": 5, "metric_value": 0.48, "depth": 13}
if obj[11]<=0:
return 'True'
else: return 'True'
elif obj[6]>2:
return 'True'
else: return 'True'
else: return 'True'
elif obj[10]>1.0:
return 'False'
else: return 'False'
elif obj[3]<=0:
# {"feature": "Education", "instances": 21, "metric_value": 0.4074, "depth": 10}
if obj[6]<=2:
# {"feature": "Restaurant20to50", "instances": 18, "metric_value": 0.4375, "depth": 11}
if obj[10]<=1.0:
# {"feature": "Children", "instances": 16, "metric_value": 0.4909, "depth": 12}
if obj[5]<=0:
# {"feature": "Direction_same", "instances": 11, "metric_value": 0.4959, "depth": 13}
if obj[11]<=0:
return 'True'
else: return 'True'
elif obj[5]>0:
# {"feature": "Direction_same", "instances": 5, "metric_value": 0.48, "depth": 13}
if obj[11]<=0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[10]>1.0:
return 'True'
else: return 'True'
elif obj[6]>2:
return 'True'
else: return 'True'
else: return 'True'
elif obj[8]>1.0:
# {"feature": "Children", "instances": 17, "metric_value": 0.3137, "depth": 9}
if obj[5]<=0:
# {"feature": "Restaurant20to50", "instances": 12, "metric_value": 0.3704, "depth": 10}
if obj[10]<=1.0:
# {"feature": "Education", "instances": 9, "metric_value": 0.4889, "depth": 11}
if obj[6]<=0:
# {"feature": "Gender", "instances": 5, "metric_value": 0.48, "depth": 12}
if obj[3]<=0:
# {"feature": "Direction_same", "instances": 5, "metric_value": 0.48, "depth": 13}
if obj[11]<=0:
return 'False'
else: return 'False'
else: return 'False'
elif obj[6]>0:
# {"feature": "Gender", "instances": 4, "metric_value": 0.5, "depth": 12}
if obj[3]<=0:
# {"feature": "Direction_same", "instances": 4, "metric_value": 0.5, "depth": 13}
if obj[11]<=0:
return 'False'
else: return 'False'
else: return 'False'
else: return 'False'
elif obj[10]>1.0:
return 'False'
else: return 'False'
elif obj[5]>0:
return 'False'
else: return 'False'
else: return 'False'
else: return 'False'
elif obj[4]>4:
# {"feature": "Occupation", "instances": 31, "metric_value": 0.28, "depth": 7}
if obj[7]>4:
# {"feature": "Bar", "instances": 24, "metric_value": 0.1667, "depth": 8}
if obj[8]<=0.0:
return 'True'
elif obj[8]>0.0:
# {"feature": "Education", "instances": 9, "metric_value": 0.3333, "depth": 9}
if obj[6]<=2:
# {"feature": "Restaurant20to50", "instances": 6, "metric_value": 0.25, "depth": 10}
if obj[10]<=1.0:
# {"feature": "Children", "instances": 4, "metric_value": 0.25, "depth": 11}
if obj[5]>0:
return 'False'
elif obj[5]<=0:
# {"feature": "Gender", "instances": 2, "metric_value": 0.5, "depth": 12}
if obj[3]<=0:
# {"feature": "Direction_same", "instances": 2, | |
else ""
PrintColorString("%s %s"% (self._function_description,
waiting_dots), end="")
try:
result = func(*args, **kargs)
result_time = time.time() - timestart
if not self._print_before_call:
PrintColorString("%s (%ds)" % (self._function_description,
result_time),
TextColors.OKGREEN)
if self._print_status:
evaluated_result = self._result_evaluator(result)
if evaluated_result.is_result_ok:
PrintColorString("OK! (%ds)" % (result_time),
TextColors.OKGREEN)
else:
PrintColorString("Fail! (%ds)" % (result_time),
TextColors.FAIL)
PrintColorString("Error: %s" %
evaluated_result.result_message,
TextColors.FAIL)
return result
except:
if self._print_status:
PrintColorString("Fail! (%ds)" % (time.time() - timestart),
TextColors.FAIL)
raise
return DecoratorFunction
def PickFreePort():
"""Helper to pick a free port.
Returns:
Integer, a free port number.
"""
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_socket.bind(("", 0))
port = tcp_socket.getsockname()[1]
tcp_socket.close()
return port
def CheckPortFree(port):
"""Check the availablity of the tcp port.
Args:
Integer, a port number.
Raises:
PortOccupied: This port is not available.
"""
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
tcp_socket.bind(("", port))
except socket.error:
raise errors.PortOccupied("Port (%d) is taken, please choose another "
"port." % port)
tcp_socket.close()
def _ExecuteCommand(cmd, args):
"""Execute command.
Args:
cmd: Strings of execute binary name.
args: List of args to pass in with cmd.
Raises:
errors.NoExecuteBin: Can't find the execute bin file.
"""
bin_path = FindExecutable(cmd)
if not bin_path:
raise errors.NoExecuteCmd("unable to locate %s" % cmd)
command = [bin_path] + args
logger.debug("Running '%s'", ' '.join(command))
with open(os.devnull, "w") as dev_null:
subprocess.check_call(command, stderr=dev_null, stdout=dev_null)
def ReleasePort(port):
"""Release local port.
Args:
port: Integer of local port number.
"""
try:
with open(os.devnull, "w") as dev_null:
subprocess.check_call(_RELEASE_PORT_CMD % port,
stderr=dev_null, stdout=dev_null, shell=True)
except subprocess.CalledProcessError:
logger.debug("The port %d is available.", constants.WEBRTC_LOCAL_PORT)
def EstablishWebRTCSshTunnel(ip_addr, rsa_key_file, ssh_user,
extra_args_ssh_tunnel=None):
"""Create ssh tunnels for webrtc.
# TODO(151418177): Before fully supporting webrtc feature, we establish one
# WebRTC tunnel at a time. so always delete the previous connection before
# establishing new one.
Args:
ip_addr: String, use to build the adb & vnc tunnel between local
and remote instance.
rsa_key_file: String, Private key file path to use when creating
the ssh tunnels.
ssh_user: String of user login into the instance.
extra_args_ssh_tunnel: String, extra args for ssh tunnel connection.
"""
ReleasePort(constants.WEBRTC_LOCAL_PORT)
try:
port_mapping = [PORT_MAPPING % {
"local_port":port["local"],
"target_port":port["target"]} for port in WEBRTC_PORTS_MAPPING]
ssh_tunnel_args = _SSH_TUNNEL_ARGS % {
"rsa_key_file": rsa_key_file,
"ssh_user": ssh_user,
"ip_addr": ip_addr,
"port_mapping":" ".join(port_mapping)}
ssh_tunnel_args_list = shlex.split(ssh_tunnel_args)
if extra_args_ssh_tunnel != None:
ssh_tunnel_args_list.extend(shlex.split(extra_args_ssh_tunnel))
_ExecuteCommand(constants.SSH_BIN, ssh_tunnel_args_list)
except subprocess.CalledProcessError as e:
PrintColorString("\n%s\nFailed to create ssh tunnels, retry with '#acloud "
"reconnect'." % e, TextColors.FAIL)
# TODO(147337696): create ssh tunnels tear down as adb and vnc.
# pylint: disable=too-many-locals
def AutoConnect(ip_addr, rsa_key_file, target_vnc_port, target_adb_port,
ssh_user, client_adb_port=None, extra_args_ssh_tunnel=None):
"""Autoconnect to an AVD instance.
Args:
ip_addr: String, use to build the adb & vnc tunnel between local
and remote instance.
rsa_key_file: String, Private key file path to use when creating
the ssh tunnels.
target_vnc_port: Integer of target vnc port number.
target_adb_port: Integer of target adb port number.
ssh_user: String of user login into the instance.
client_adb_port: Integer, Specified adb port to establish connection.
extra_args_ssh_tunnel: String, extra args for ssh tunnel connection.
Returns:
NamedTuple of (vnc_port, adb_port) SSHTUNNEL of the connect, both are
integers.
"""
local_adb_port = client_adb_port or PickFreePort()
port_mapping = [PORT_MAPPING % {
"local_port":local_adb_port,
"target_port":target_adb_port}]
local_free_vnc_port = None
if target_vnc_port:
local_free_vnc_port = PickFreePort()
port_mapping += [PORT_MAPPING % {
"local_port":local_free_vnc_port,
"target_port":target_vnc_port}]
try:
ssh_tunnel_args = _SSH_TUNNEL_ARGS % {
"rsa_key_file": rsa_key_file,
"port_mapping": " ".join(port_mapping),
"ssh_user": ssh_user,
"ip_addr": ip_addr}
ssh_tunnel_args_list = shlex.split(ssh_tunnel_args)
if extra_args_ssh_tunnel != None:
ssh_tunnel_args_list.extend(shlex.split(extra_args_ssh_tunnel))
_ExecuteCommand(constants.SSH_BIN, ssh_tunnel_args_list)
except subprocess.CalledProcessError as e:
PrintColorString("\n%s\nFailed to create ssh tunnels, retry with '#acloud "
"reconnect'." % e, TextColors.FAIL)
return ForwardedPorts(vnc_port=None, adb_port=None)
try:
adb_connect_args = _ADB_CONNECT_ARGS % {"adb_port": local_adb_port}
_ExecuteCommand(constants.ADB_BIN, adb_connect_args.split())
except subprocess.CalledProcessError:
PrintColorString("Failed to adb connect, retry with "
"'#acloud reconnect'", TextColors.FAIL)
return ForwardedPorts(vnc_port=local_free_vnc_port,
adb_port=local_adb_port)
def GetAnswerFromList(answer_list, enable_choose_all=False):
"""Get answer from a list.
Args:
answer_list: list of the answers to choose from.
enable_choose_all: True to choose all items from answer list.
Return:
List holding the answer(s).
"""
print("[0] to exit.")
start_index = 1
max_choice = len(answer_list)
for num, item in enumerate(answer_list, start_index):
print("[%d] %s" % (num, item))
if enable_choose_all:
max_choice += 1
print("[%d] for all." % max_choice)
choice = -1
while True:
try:
choice = six.moves.input("Enter your choice[0-%d]: " % max_choice)
choice = int(choice)
except ValueError:
print("'%s' is not a valid integer.", choice)
continue
# Filter out choices
if choice == 0:
sys.exit(constants.EXIT_BY_USER)
if enable_choose_all and choice == max_choice:
return answer_list
if choice < 0 or choice > max_choice:
print("please choose between 0 and %d" % max_choice)
else:
return [answer_list[choice-start_index]]
def LaunchVNCFromReport(report, avd_spec, no_prompts=False):
"""Launch vnc client according to the instances report.
Args:
report: Report object, that stores and generates report.
avd_spec: AVDSpec object that tells us what we're going to create.
no_prompts: Boolean, True to skip all prompts.
"""
for device in report.data.get("devices", []):
if device.get(constants.VNC_PORT):
LaunchVncClient(device.get(constants.VNC_PORT),
avd_width=avd_spec.hw_property["x_res"],
avd_height=avd_spec.hw_property["y_res"],
no_prompts=no_prompts)
else:
PrintColorString("No VNC port specified, skipping VNC startup.",
TextColors.FAIL)
def LaunchBrowserFromReport(report):
"""Open browser when autoconnect to webrtc according to the instances report.
Args:
report: Report object, that stores and generates report.
"""
PrintColorString("(This is an experimental project for webrtc, and since "
"the certificate is self-signed, Chrome will mark it as "
"an insecure website. keep going.)",
TextColors.WARNING)
for device in report.data.get("devices", []):
if device.get("ip"):
LaunchBrowser(constants.WEBRTC_LOCAL_HOST,
constants.WEBRTC_LOCAL_PORT)
def LaunchBrowser(ip_addr, port):
"""Launch browser to connect the webrtc AVD.
Args:
ip_addr: String, use to connect to webrtc AVD on the instance.
port: Integer, port number.
"""
webrtc_link = _WEBRTC_URL % {
"webrtc_ip": ip_addr,
"webrtc_port": port}
if os.environ.get(_ENV_DISPLAY, None):
webbrowser.open_new_tab(webrtc_link)
else:
PrintColorString("Remote terminal can't support launch webbrowser.",
TextColors.FAIL)
PrintColorString("WebRTC AVD URL: %s "% webrtc_link)
def LaunchVncClient(port, avd_width=None, avd_height=None, no_prompts=False):
"""Launch ssvnc.
Args:
port: Integer, port number.
avd_width: String, the width of avd.
avd_height: String, the height of avd.
no_prompts: Boolean, True to skip all prompts.
"""
try:
os.environ[_ENV_DISPLAY]
except KeyError:
PrintColorString("Remote terminal can't support VNC. "
"Skipping VNC startup. "
"VNC server is listening at 127.0.0.1:{}.".format(port),
TextColors.FAIL)
return
if IsSupportedPlatform() and not FindExecutable(_VNC_BIN):
if no_prompts or GetUserAnswerYes(_CONFIRM_CONTINUE):
try:
PrintColorString("Installing ssvnc vnc client... ", end="")
sys.stdout.flush()
CheckOutput(_CMD_INSTALL_SSVNC, shell=True)
PrintColorString("Done", TextColors.OKGREEN)
except subprocess.CalledProcessError as cpe:
PrintColorString("Failed to install ssvnc: %s" %
cpe.output, TextColors.FAIL)
return
else:
return
ssvnc_env = os.environ.copy()
ssvnc_env.update(_SSVNC_ENV_VARS)
# Override SSVNC_SCALE
if avd_width or avd_height:
scale_ratio = CalculateVNCScreenRatio(avd_width, avd_height)
ssvnc_env["SSVNC_SCALE"] = str(scale_ratio)
logger.debug("SSVNC_SCALE:%s", scale_ratio)
ssvnc_args = _CMD_START_VNC % {"bin": FindExecutable(_VNC_BIN),
"port": port}
subprocess.Popen(ssvnc_args.split(), env=ssvnc_env)
def PrintDeviceSummary(report):
"""Display summary of devices.
-Display device details from the report instance.
report example:
'data': [{'devices':[{'instance_name': 'ins-f6a397-none-53363',
'ip': u'192.168.3.11'}]}]
-Display error message from report.error.
Args:
report: A Report instance.
"""
PrintColorString("\n")
PrintColorString("Device summary:")
for device in report.data.get("devices", []):
adb_serial = "(None)"
adb_port = device.get("adb_port")
if adb_port:
adb_serial = constants.LOCALHOST_ADB_SERIAL % adb_port
instance_name = device.get("instance_name")
instance_ip = device.get("ip")
instance_details = "" if not instance_name else "(%s[%s])" % (
instance_name, instance_ip)
PrintColorString(" - device serial: %s %s" % (adb_serial,
instance_details))
PrintColorString(" export ANDROID_SERIAL=%s" % adb_serial)
# TODO(b/117245508): Help user to delete instance if it got created.
if report.errors:
error_msg = "\n".join(report.errors)
PrintColorString("Fail in:\n%s\n" % error_msg, TextColors.FAIL)
def CalculateVNCScreenRatio(avd_width, avd_height):
"""calculate the vnc screen scale ratio to fit into user's monitor.
Args:
avd_width: String, the width of avd.
avd_height: String, the height of avd.
Return:
Float, scale ratio for vnc client.
"""
try:
import Tkinter
# Some python interpreters may not be configured for Tk, just return default scale ratio.
except ImportError:
try:
import tkinter as Tkinter
except ImportError:
PrintColorString(
"no module named tkinter, vnc display scale were not be fit."
"please run 'sudo apt-get install python3-tk' to install it.")
return _DEFAULT_DISPLAY_SCALE
root = Tkinter.Tk()
margin = 100 # leave some space on user's monitor.
screen_height = root.winfo_screenheight() - margin
screen_width = root.winfo_screenwidth() - margin
scale_h = _DEFAULT_DISPLAY_SCALE
scale_w = _DEFAULT_DISPLAY_SCALE
if float(screen_height) < float(avd_height):
scale_h = round(float(screen_height) / float(avd_height), 1)
if float(screen_width) < float(avd_width):
scale_w = round(float(screen_width) / float(avd_width), 1)
logger.debug("scale_h: %s (screen_h: %s/avd_h: %s),"
" scale_w: %s (screen_w: %s/avd_w: %s)",
scale_h, screen_height, avd_height,
scale_w, screen_width, avd_width)
# Return the larger scale-down ratio.
return scale_h if scale_h < scale_w else scale_w
def IsCommandRunning(command):
"""Check if command is running.
Args:
command: String of command name.
Returns:
Boolean, True if command is running. False otherwise.
"""
try:
with open(os.devnull, "w") as dev_null:
subprocess.check_call([constants.CMD_PGREP, "-af", command],
stderr=dev_null, stdout=dev_null)
return True
except subprocess.CalledProcessError:
return False
def AddUserGroupsToCmd(cmd, user_groups):
| |
drawBodePlot(f,mag,phase,title)
Draws a bode plot
Required parameters:
f : Frequency vector (Hz)
mag : Magnitude vector(dB)
phase : Phase vector (deg)
Optional parameters:
title : Plot title
Returns nothing
"""
addBodePlot(f,mag,phase)
showBodePlot(title)
def drawBodeFromComplex(f,v,title='Bode Plot'):
"""
@drawBodeFromComplex
drawBodeFromComplex(f,v,title)
Draws a bode plot
Required parameters:
f : Frequency vector (Hz)
v : Complex vector
Optional parameters:
title : Plot title
Returns nothing
"""
addBodeFromComplex(f,v)
showBodePlot(title)
#################### S PLOT HELPER FUNCTIONS ######################
# Global variables
pzPlotPoles = []
pzPlotZeros = []
pzPlotLabels = []
pzPlotColors = []
def addPoleZeroPlot(poles=[],zeros=[],label=None,color='blue'):
"""
@addPoleZeroPlot
addPoleZeroPlot(poles,zeros,title,color)
Adds poles to the current plot
Parameters:
poles : List of poles
zeros : List of zeros
label : Label (optional)
color : Color of symbols (defaults to 'blue')
Returns nothing
See also showPoleZeroPlot
"""
global pzPlotPoles,pzPlotZeros,pzPlotLabels,pzPlotColors
pzPlotPoles.append(poles)
pzPlotZeros.append(zeros)
pzPlotLabels.append(label)
pzPlotColors.append(color)
def showPoleZeroPlot(title='Pole(x) / Zero(o) plot',location='best'):
"""
@showPoleZeroPlot
showPoleZeroPlot(title,location)
Draws a pole-zero plot after calls to addPoleZeroPlot
Optional parameters:
title : Title for the plot
location : Location for the legend
"""
global pzPlotPoles,pzPlotZeros,pzPlotLabels,pzPlotColors
labelBox = False
fig=_plotStart()
ax=_subplotStart(fig,111,title,'Real axis','Imaginary axis')
for poles,zeros,label,color in zip(pzPlotPoles
,pzPlotZeros,pzPlotLabels,pzPlotColors):
showLabel = (label != None)
if len(poles):
re = np.real(poles)
im = np.imag(poles)
if showLabel:
pl.scatter(re,im,marker='x',label=label,color=color)
labelBox=True
showLabel = False
else:
pl.scatter(re,im,marker='x',color=color)
if len(zeros):
re = np.real(zeros)
im = np.imag(zeros)
if showLabel:
pl.scatter(re,im,marker='x',label=label,color=color)
labelBox=True
else:
pl.scatter(re,im,marker='o',color=color)
# Zero lines
ax.axvline(x=0,linewidth=1, color='black', linestyle='--')
ax.axhline(y=0,linewidth=1, color='black', linestyle='--')
if labelBox == True:
pl.legend(loc=location)
_subplotEnd(ax)
_plotEnd()
# Reset lists
pzPlotPoles = []
pzPlotZeros = []
pzPlotLabels = []
pzPlotColors = []
def drawPoleZeroPlot(poles=[],zeros=[]
,title='Pole(x) & Zero(o) plot'
,color='blue'):
"""
@drawPoleZeroPlot
drawPoleZeroPlot(poles,zeros,title,color)
Draw a poles-zero plot
Parameters:
poles : List of poles
zeros : List of zeros
title : Graph title (optional)
color : Color of symbols (optional)
Returns nothing
"""
addPoleZeroPlot(poles,zeros,color=color)
showPoleZeroPlot()
def damping(pole):
"""
@damping
damping(pole)
Returns the damping associated to a single pole
The results make no sense for real poles
0 : Undamped (Oscillator)
<1 : Underdamped (Decaying oscillations)
1 : Critically damped or Overdamped (No oscillations)
"""
return -np.real(pole)/np.absolute(pole)
def q(pole):
"""
@q
q(pole)
Returns the Q factor associated to a single pole
The result make no sense for real poles
"""
damp = damping(pole)
return 1.0/(2.0*damp)
######################### LINBLK CLASS ############################
"""
@linblk
class linblk
Linear block class
A new object can be created with:
>> l1 = linblk() # H(s) = 1
>> l2 = linblk([1],[1,1/p1]) # H(s) = 1 / ( 1 + s/p1 )
Or you can also use linFromPZ or lin1
Additional topics:
linFromPZ, lin1, operators, methods
@operators
Operators available on the linblk class:
str : Shows numerator/denominator
* : Cascade of two systems
/ : Cascade with second system pole <-> zero
+ : System output addition for same input
- : Negation operator
- : System substraction
@methods
Methods available on the linblk class:
They are seachable as help topics
nf : Negative feedback nf()
pf : Positive feedback pf
eval : Evaluation in s plane
weval : Evaluation at jw
bode : Pode plot
freqR : Frequency response
showBode : Bode plot
addBode : Add Bode plot
poles : List of poles
zeros : List of zeros
gain : System gain
addPZplot : Add PZ plot
showPZplot : PZ plot
printPZ : Print PZ list
clean : PZ cancelation
pzRange : Range for all PZ
plotSplane : Linear 3D Magnitude "s" plot
bode3Dmag : Log 3D Magnitude "s" plot
bode3Dphase : Log 3D Phase "s" plot
'''
'''
@nf
L1.nf(L2)
L2 gives negative feedback on L1
Retuns composite system
@pf
L1.nf(L2)
L2 gives positive feedback on L1
Retuns composite system
@eval
L1.eval(x)
Evaluate the system on a point of the s plane
x : Complex value
Returns a complex value
@weval
L1.weval(w)
Evaluate the system on a point on the imaginary axis
w : Value on the j axis (Real value)
Returns a complex value
@bode
L1.bode(f)
Generates the bode plot vector results
f : Frequency vector
Returns:
mag : Magnitude vector (dB)
phase : Phase vector (deg)
@freqR
L1.freqR(f):
Generates the frequency response as a vector
f : Frequency vector
Returns frecuency response (complex)
@showBode
L1.showBode(f,title):
Shows the bode plot of the system
f : Frequency vector
title : Plot title (optional)
Returns nothing
@addBode
L1.addBode(f,title,label)
Add the bode plot to the current image
f : Frequency vector
title : Plot title (optional)
label : Plot label (optional)
Use showPlot() to see the final image
Returns noting
@poles
L1.poles()
Gives the list of poles of the system
@zeros
L1.zeros()
Gives the list of zeros of the system
@gain
gain()
Gives the gain of the system
We define gain as the quotient of the first coef (in increase order)
of num and den that is not zero
@addPZplot
L1.addPZplot(title,color)
Add the pole-zero plot to the current image
title : Plot title (optional)
color : Color used (optional)
Use showPlot() to see the final image
Returns nothing
@showPZplot
L1.showPZplot(title,color):
Show he pole-zero plot of the system
title : Plot title (optional)
color : Color used (optional)
Returns nothing
@printPZ
L1.printPZ()
Show poles and zeros on screen
Returns nothing
@clean
L1.clean(ratio)
Eliminates poles and zeros that cancel each other
A pole and a zero are considered equal if their distance
is lower than 1/ratio its magnitude
ratio : Ratio to cancel PZ (default = 1000)
Returns a new object
@pzRange
L1.pzRange()
Returns in a tuple the range in the complex domain
that includes all the poles and zeros
@plotSplane
L1.plotSplane(zmax)
Plots the magnitude of the evaluation of the
system inside the s plane in dB(magnitude)
zmax : Maximum in Z axis (dB) (Optional)
Returns nothing
@bode3Dmag
L1.bode3Dmag(sfmax,zmax)
Plots the magnitude of the evaluation of the
system inside the s plane in dB(magnitude)
The plot uses log10 of frequency in the axes
fmax : Maximum frequency (optional)
zmax : Maximum in Z axis (dB) (optional)
Returns nothing
@bode3Dphase
L1.bode3Dphase(fmax)
Plots the phase of the evaluation of the
system inside the s plane in dB(magnitude)
The plot uses log10 of frequency in the axes
fmax : Maximum frequency
Returns nothing
"""
class linblk():
def __init__(self,num=[1.0],den=[1.0]):
"""
linblk Class constructor
A new object can be created with:
>> l1 = linblk() # H(s) = 1 block
>> l2 = linblk([1],[1,1/p1]) # H(s) = 1 / ( 1 + s/p1 )
"""
self.num = P.Polynomial(num)
self.den = P.Polynomial(den)
def __str__(self):
"""
Converts a linblk object to string
Shows the numerator and denominator
"""
st = str(self.num.coef) + ' / ' + str(self.den.coef)
return st
def __mul__(self,other):
"""
Multiplication operator (*)
Returns a cascade of two systems
"""
obj = linblk()
obj.num = self.num * other.num
obj.den = self.den * other.den
return obj
def __div__(self,other):
"""
Division operator (//)
Returns a cascade of the first system with
the second one changing poles to zeros
"""
obj = linblk()
obj.num = self.num * other.den
obj.den = self.den * other.num
return obj
def __truediv__(self,other):
"""
True Division operator (/)
Returns a cascade of the first system with
the second one changing poles to zeros
"""
obj = linblk()
obj.num = self.num * other.den
obj.den = self.den * other.num
return obj
def __add__(self,other):
"""
Addition operator (+)
Returns a system that whose output is the sum of
two systems with the same input
"""
obj = linblk()
obj.num = (self.num * other.den) + (self.den*other.num)
obj.den = self.den * other.den
return obj
def __sub__(self,other):
"""
Substraction operator (+)
Returns a system that whose output is the substraction of
two systems with the same input
"""
obj = linblk()
obj.num = (self.num * other.den) - (self.den*other.num)
obj.den = self.den * other.den
return obj
def __neg__(self):
"""
Negation operator (-)
Returns a system with sign change
"""
obj = linblk()
obj.num = -self.num
obj.den = self.den
return obj
def nf(self,other):
"""
Negative feedback
Use other system to give negative feedback
"""
obj = linblk()
obj.num = self.num * other.den
obj.den = (self.den * other.den) + (self.num * other.num)
return obj
def pf(self,other):
"""
Positive feedback
Use other system to give positive feedback
"""
obj = linblk()
obj.num = self.num * other.den
obj.den = (self.den * other.den) - | |
<filename>openid/test/test_message.py
# -*- coding: utf-8 -*-
from openid import message
from openid import oidutil
from openid.extensions import sreg
import urllib.request
import urllib.parse
import urllib.error
import unittest
def mkGetArgTest(ns, key, expected=None):
def test(self):
a_default = object()
self.assertEqual(self.msg.getArg(ns, key), expected)
if expected is None:
self.assertEqual(
self.msg.getArg(ns, key, a_default), a_default)
self.assertRaises(
KeyError, self.msg.getArg, ns, key, message.no_default)
else:
self.assertEqual(
self.msg.getArg(ns, key, a_default), expected)
self.assertEqual(
self.msg.getArg(ns, key, message.no_default), expected)
return test
class EmptyMessageTest(unittest.TestCase):
def setUp(self):
self.msg = message.Message()
def test_toPostArgs(self):
self.assertEqual(self.msg.toPostArgs(), {})
def test_toArgs(self):
self.assertEqual(self.msg.toArgs(), {})
def test_toKVForm(self):
self.assertEqual(self.msg.toKVForm(), b'')
def test_toURLEncoded(self):
self.assertEqual(self.msg.toURLEncoded(), '')
def test_toURL(self):
base_url = 'http://base.url/'
self.assertEqual(self.msg.toURL(base_url), base_url)
def test_getOpenID(self):
self.assertEqual(self.msg.getOpenIDNamespace(), None)
def test_getKeyOpenID(self):
# Could reasonably return None instead of raising an
# exception. I'm not sure which one is more right, since this
# case should only happen when you're building a message from
# scratch and so have no default namespace.
self.assertRaises(message.UndefinedOpenIDNamespace,
self.msg.getKey, message.OPENID_NS, 'foo')
def test_getKeyBARE(self):
self.assertEqual(self.msg.getKey(message.BARE_NS, 'foo'), 'foo')
def test_getKeyNS1(self):
self.assertEqual(self.msg.getKey(message.OPENID1_NS, 'foo'), None)
def test_getKeyNS2(self):
self.assertEqual(self.msg.getKey(message.OPENID2_NS, 'foo'), None)
def test_getKeyNS3(self):
self.assertEqual(self.msg.getKey('urn:nothing-significant', 'foo'),
None)
def test_hasKey(self):
# Could reasonably return False instead of raising an
# exception. I'm not sure which one is more right, since this
# case should only happen when you're building a message from
# scratch and so have no default namespace.
self.assertRaises(message.UndefinedOpenIDNamespace,
self.msg.hasKey, message.OPENID_NS, 'foo')
def test_hasKeyBARE(self):
self.assertEqual(self.msg.hasKey(message.BARE_NS, 'foo'), False)
def test_hasKeyNS1(self):
self.assertEqual(self.msg.hasKey(message.OPENID1_NS, 'foo'), False)
def test_hasKeyNS2(self):
self.assertEqual(self.msg.hasKey(message.OPENID2_NS, 'foo'), False)
def test_hasKeyNS3(self):
self.assertEqual(self.msg.hasKey('urn:nothing-significant', 'foo'),
False)
def test_getAliasedArgSuccess(self):
msg = message.Message.fromPostArgs({'openid.ns.test': 'urn://foo',
'openid.test.flub': 'bogus'})
actual_uri = msg.getAliasedArg('ns.test', message.no_default)
self.assertEqual("urn://foo", actual_uri)
def test_getAliasedArgFailure(self):
msg = message.Message.fromPostArgs({'openid.test.flub': 'bogus'})
self.assertRaises(KeyError,
msg.getAliasedArg, 'ns.test', message.no_default)
def test_getArg(self):
# Could reasonably return None instead of raising an
# exception. I'm not sure which one is more right, since this
# case should only happen when you're building a message from
# scratch and so have no default namespace.
self.assertRaises(message.UndefinedOpenIDNamespace,
self.msg.getArg, message.OPENID_NS, 'foo')
test_getArgBARE = mkGetArgTest(message.BARE_NS, 'foo')
test_getArgNS1 = mkGetArgTest(message.OPENID1_NS, 'foo')
test_getArgNS2 = mkGetArgTest(message.OPENID2_NS, 'foo')
test_getArgNS3 = mkGetArgTest('urn:nothing-significant', 'foo')
def test_getArgs(self):
# Could reasonably return {} instead of raising an
# exception. I'm not sure which one is more right, since this
# case should only happen when you're building a message from
# scratch and so have no default namespace.
self.assertRaises(message.UndefinedOpenIDNamespace,
self.msg.getArgs, message.OPENID_NS)
def test_getArgsBARE(self):
self.assertEqual(self.msg.getArgs(message.BARE_NS), {})
def test_getArgsNS1(self):
self.assertEqual(self.msg.getArgs(message.OPENID1_NS), {})
def test_getArgsNS2(self):
self.assertEqual(self.msg.getArgs(message.OPENID2_NS), {})
def test_getArgsNS3(self):
self.assertEqual(self.msg.getArgs('urn:nothing-significant'), {})
def test_updateArgs(self):
self.assertRaises(message.UndefinedOpenIDNamespace,
self.msg.updateArgs, message.OPENID_NS,
{'does not': 'matter'})
def _test_updateArgsNS(self, ns):
update_args = {
'<NAME>': '<NAME>',
'Magnolia Electric Co.': '<NAME>',
}
self.assertEqual(self.msg.getArgs(ns), {})
self.msg.updateArgs(ns, update_args)
self.assertEqual(self.msg.getArgs(ns), update_args)
def test_updateArgsBARE(self):
self._test_updateArgsNS(message.BARE_NS)
def test_updateArgsNS1(self):
self._test_updateArgsNS(message.OPENID1_NS)
def test_updateArgsNS2(self):
self._test_updateArgsNS(message.OPENID2_NS)
def test_updateArgsNS3(self):
self._test_updateArgsNS('urn:nothing-significant')
def test_setArg(self):
self.assertRaises(message.UndefinedOpenIDNamespace,
self.msg.setArg, message.OPENID_NS,
'does not', 'matter')
def _test_setArgNS(self, ns):
key = 'Camper van Beethoven'
value = '<NAME>'
self.assertEqual(self.msg.getArg(ns, key), None)
self.msg.setArg(ns, key, value)
self.assertEqual(self.msg.getArg(ns, key), value)
def test_setArgBARE(self):
self._test_setArgNS(message.BARE_NS)
def test_setArgNS1(self):
self._test_setArgNS(message.OPENID1_NS)
def test_setArgNS2(self):
self._test_setArgNS(message.OPENID2_NS)
def test_setArgNS3(self):
self._test_setArgNS('urn:nothing-significant')
def test_setArgToNone(self):
self.assertRaises(AssertionError, self.msg.setArg,
message.OPENID1_NS, 'op_endpoint', None)
def test_delArg(self):
# Could reasonably raise KeyError instead of raising
# UndefinedOpenIDNamespace. I'm not sure which one is more
# right, since this case should only happen when you're
# building a message from scratch and so have no default
# namespace.
self.assertRaises(message.UndefinedOpenIDNamespace,
self.msg.delArg, message.OPENID_NS, 'key')
def _test_delArgNS(self, ns):
key = 'Camper van Beethoven'
self.assertRaises(KeyError, self.msg.delArg, ns, key)
def test_delArgBARE(self):
self._test_delArgNS(message.BARE_NS)
def test_delArgNS1(self):
self._test_delArgNS(message.OPENID1_NS)
def test_delArgNS2(self):
self._test_delArgNS(message.OPENID2_NS)
def test_delArgNS3(self):
self._test_delArgNS('urn:nothing-significant')
def test_isOpenID1(self):
self.assertFalse(self.msg.isOpenID1())
def test_isOpenID2(self):
self.assertFalse(self.msg.isOpenID2())
class OpenID1MessageTest(unittest.TestCase):
def setUp(self):
self.msg = message.Message.fromPostArgs({
'openid.mode': 'error',
'openid.error': 'unit test'
})
def test_toPostArgs(self):
self.assertEqual(self.msg.toPostArgs(), {
'openid.mode': 'error',
'openid.error': 'unit test'
})
def test_toArgs(self):
self.assertEqual(self.msg.toArgs(), {
'mode': 'error',
'error': 'unit test'
})
def test_toKVForm(self):
self.assertEqual(self.msg.toKVForm(),
b'error:unit test\nmode:error\n')
def test_toURLEncoded(self):
self.assertEqual(self.msg.toURLEncoded(),
'openid.error=unit+test&openid.mode=error')
def test_toURL(self):
base_url = 'http://base.url/'
actual = self.msg.toURL(base_url)
actual_base = actual[:len(base_url)]
self.assertEqual(actual_base, base_url)
self.assertEqual(actual[len(base_url)], '?')
query = actual[len(base_url) + 1:]
parsed = urllib.parse.parse_qs(query)
self.assertEqual(parsed, {
'openid.mode': ['error'],
'openid.error': ['unit test']
})
def test_getOpenID(self):
self.assertEqual(self.msg.getOpenIDNamespace(), message.OPENID1_NS)
def test_getKeyOpenID(self):
self.assertEqual(self.msg.getKey(message.OPENID_NS, 'mode'),
'openid.mode')
def test_getKeyBARE(self):
self.assertEqual(self.msg.getKey(message.BARE_NS, 'mode'), 'mode')
def test_getKeyNS1(self):
self.assertEqual(
self.msg.getKey(message.OPENID1_NS, 'mode'), 'openid.mode')
def test_getKeyNS2(self):
self.assertEqual(self.msg.getKey(message.OPENID2_NS, 'mode'), None)
def test_getKeyNS3(self):
self.assertEqual(
self.msg.getKey('urn:nothing-significant', 'mode'), None)
def test_hasKey(self):
self.assertEqual(self.msg.hasKey(message.OPENID_NS, 'mode'), True)
def test_hasKeyBARE(self):
self.assertEqual(self.msg.hasKey(message.BARE_NS, 'mode'), False)
def test_hasKeyNS1(self):
self.assertEqual(self.msg.hasKey(message.OPENID1_NS, 'mode'), True)
def test_hasKeyNS2(self):
self.assertEqual(
self.msg.hasKey(message.OPENID2_NS, 'mode'), False)
def test_hasKeyNS3(self):
self.assertEqual(
self.msg.hasKey('urn:nothing-significant', 'mode'), False)
test_getArgNSBARE = mkGetArgTest(message.BARE_NS, 'mode')
test_getArgNS = mkGetArgTest(message.OPENID_NS, 'mode', 'error')
test_getArgNS1 = mkGetArgTest(message.OPENID1_NS, 'mode', 'error')
test_getArgNS2 = mkGetArgTest(message.OPENID2_NS, 'mode')
test_getArgNS3 = mkGetArgTest('urn:nothing-significant', 'mode')
def test_getArgs(self):
self.assertEqual(self.msg.getArgs(message.OPENID_NS), {
'mode': 'error',
'error': 'unit test',
})
def test_getArgsBARE(self):
self.assertEqual(self.msg.getArgs(message.BARE_NS), {})
def test_getArgsNS1(self):
self.assertEqual(self.msg.getArgs(message.OPENID1_NS), {
'mode': 'error',
'error': 'unit test',
})
def test_getArgsNS2(self):
self.assertEqual(self.msg.getArgs(message.OPENID2_NS), {})
def test_getArgsNS3(self):
self.assertEqual(self.msg.getArgs('urn:nothing-significant'), {})
def _test_updateArgsNS(self, ns, before=None):
if before is None:
before = {}
update_args = {
'<NAME>': '<NAME>',
'Magnolia Electric Co.': '<NAME>',
}
self.assertEqual(self.msg.getArgs(ns), before)
self.msg.updateArgs(ns, update_args)
after = dict(before)
after.update(update_args)
self.assertEqual(self.msg.getArgs(ns), after)
def test_updateArgs(self):
self._test_updateArgsNS(message.OPENID_NS,
before={'mode': 'error',
'error': 'unit test'})
def test_updateArgsBARE(self):
self._test_updateArgsNS(message.BARE_NS)
def test_updateArgsNS1(self):
self._test_updateArgsNS(message.OPENID1_NS,
before={'mode': 'error',
'error': 'unit test'})
def test_updateArgsNS2(self):
self._test_updateArgsNS(message.OPENID2_NS)
def test_updateArgsNS3(self):
self._test_updateArgsNS('urn:nothing-significant')
def _test_setArgNS(self, ns):
key = 'Camper van Beethoven'
value = '<NAME>'
self.assertEqual(self.msg.getArg(ns, key), None)
self.msg.setArg(ns, key, value)
self.assertEqual(self.msg.getArg(ns, key), value)
def test_setArg(self):
self._test_setArgNS(message.OPENID_NS)
def test_setArgBARE(self):
self._test_setArgNS(message.BARE_NS)
def test_setArgNS1(self):
self._test_setArgNS(message.OPENID1_NS)
def test_setArgNS2(self):
self._test_setArgNS(message.OPENID2_NS)
def test_setArgNS3(self):
self._test_setArgNS('urn:nothing-significant')
def _test_delArgNS(self, ns):
key = 'Camper van Beethoven'
value = '<NAME>'
self.assertRaises(KeyError, self.msg.delArg, ns, key)
self.msg.setArg(ns, key, value)
self.assertEqual(self.msg.getArg(ns, key), value)
self.msg.delArg(ns, key)
self.assertEqual(self.msg.getArg(ns, key), None)
def test_delArg(self):
self._test_delArgNS(message.OPENID_NS)
def test_delArgBARE(self):
self._test_delArgNS(message.BARE_NS)
def test_delArgNS1(self):
self._test_delArgNS(message.OPENID1_NS)
def test_delArgNS2(self):
self._test_delArgNS(message.OPENID2_NS)
def test_delArgNS3(self):
self._test_delArgNS('urn:nothing-significant')
def test_isOpenID1(self):
self.assertTrue(self.msg.isOpenID1())
def test_isOpenID2(self):
self.assertFalse(self.msg.isOpenID2())
class OpenID1ExplicitMessageTest(unittest.TestCase):
def setUp(self):
self.msg = message.Message.fromPostArgs({
'openid.mode': 'error',
'openid.error': 'unit test',
'openid.ns': message.OPENID1_NS
})
def test_toPostArgs(self):
self.assertEqual(self.msg.toPostArgs(), {
'openid.mode': 'error',
'openid.error': 'unit test',
'openid.ns': message.OPENID1_NS,
})
def test_toArgs(self):
self.assertEqual(self.msg.toArgs(), {
'mode': 'error',
'error': 'unit test',
'ns': message.OPENID1_NS,
})
def test_toKVForm(self):
self.assertEqual(
self.msg.toKVForm(),
bytes('error:unit test\nmode:error\nns:%s\n' %
message.OPENID1_NS, encoding="utf-8"))
def test_toURLEncoded(self):
self.assertEqual(
self.msg.toURLEncoded(),
'openid.error=unit+test&openid.mode=error&openid.ns=http%3A%2F%2Fopenid.net%2Fsignon%2F1.0')
def test_toURL(self):
base_url = 'http://base.url/'
actual = self.msg.toURL(base_url)
actual_base = actual[:len(base_url)]
self.assertEqual(actual_base, base_url)
self.assertEqual(actual[len(base_url)], '?')
query = actual[len(base_url) + 1:]
parsed = urllib.parse.parse_qs(query)
self.assertEqual(parsed, {
'openid.mode': ['error'],
'openid.error': ['unit test'],
'openid.ns': [message.OPENID1_NS]
})
def test_isOpenID1(self):
self.assertTrue(self.msg.isOpenID1())
class OpenID2MessageTest(unittest.TestCase):
def setUp(self):
self.msg = message.Message.fromPostArgs({
'openid.mode': 'error',
'openid.error': 'unit test',
'openid.ns': message.OPENID2_NS
})
self.msg.setArg(message.BARE_NS, "xey", "value")
def test_toPostArgs(self):
self.assertEqual(
self.msg.toPostArgs(), {
'openid.mode': 'error',
'openid.error': 'unit test',
'openid.ns': message.OPENID2_NS,
'xey': 'value',
})
def test_toPostArgs_bug_with_utf8_encoded_values(self):
msg = message.Message.fromPostArgs({'openid.mode': 'error',
'openid.error': 'unit test',
'openid.ns': message.OPENID2_NS
})
msg.setArg(message.BARE_NS, 'ünicöde_key', 'ünicöde_välüe')
self.assertEqual(msg.toPostArgs(),
{'openid.mode': 'error',
'openid.error': 'unit test',
'openid.ns': message.OPENID2_NS,
'ünicöde_key': 'ünicöde_välüe',
})
def test_toArgs(self):
# This method can't tolerate BARE_NS.
self.msg.delArg(message.BARE_NS, "xey")
self.assertEqual(self.msg.toArgs(), {
'mode': 'error',
'error': 'unit test',
'ns': message.OPENID2_NS,
})
def test_toKVForm(self):
# Can't tolerate BARE_NS in kvform
self.msg.delArg(message.BARE_NS, "xey")
self.assertEqual(
self.msg.toKVForm(),
bytes('error:unit test\nmode:error\nns:%s\n' %
message.OPENID2_NS, encoding="utf-8"))
def _test_urlencoded(self, s):
expected = ('openid.error=unit+test&openid.mode=error&'
'openid.ns=%s&xey=value' % (
urllib.parse.quote(message.OPENID2_NS, ''),))
self.assertEqual(s, expected)
def test_toURLEncoded(self):
self._test_urlencoded(self.msg.toURLEncoded())
def test_toURL(self):
base_url = 'http://base.url/'
actual = self.msg.toURL(base_url)
actual_base = actual[:len(base_url)]
self.assertEqual(actual_base, base_url)
self.assertEqual(actual[len(base_url)], '?')
query = actual[len(base_url) + 1:]
self._test_urlencoded(query)
def test_getOpenID(self):
self.assertEqual(self.msg.getOpenIDNamespace(), message.OPENID2_NS)
def test_getKeyOpenID(self):
self.assertEqual(self.msg.getKey(message.OPENID_NS, 'mode'),
'openid.mode')
def test_getKeyBARE(self):
self.assertEqual(self.msg.getKey(message.BARE_NS, 'mode'), 'mode')
def test_getKeyNS1(self):
self.assertEqual(
self.msg.getKey(message.OPENID1_NS, 'mode'), None)
def test_getKeyNS2(self):
self.assertEqual(
self.msg.getKey(message.OPENID2_NS, 'mode'), 'openid.mode')
def test_getKeyNS3(self):
self.assertEqual(
self.msg.getKey('urn:nothing-significant', 'mode'), None)
def test_hasKeyOpenID(self):
self.assertEqual(self.msg.hasKey(message.OPENID_NS, 'mode'), True)
def test_hasKeyBARE(self):
self.assertEqual(self.msg.hasKey(message.BARE_NS, 'mode'), False)
def test_hasKeyNS1(self):
self.assertEqual(
self.msg.hasKey(message.OPENID1_NS, 'mode'), False)
def test_hasKeyNS2(self):
self.assertEqual(
self.msg.hasKey(message.OPENID2_NS, 'mode'), True)
def test_hasKeyNS3(self):
self.assertEqual(
self.msg.hasKey('urn:nothing-significant', 'mode'), False)
test_getArgBARE = mkGetArgTest(message.BARE_NS, 'mode')
test_getArgNS = mkGetArgTest(message.OPENID_NS, 'mode', 'error')
test_getArgNS1 = mkGetArgTest(message.OPENID1_NS, 'mode')
test_getArgNS2 = mkGetArgTest(message.OPENID2_NS, 'mode', 'error')
test_getArgNS3 = mkGetArgTest('urn:nothing-significant', 'mode')
def test_getArgsOpenID(self):
self.assertEqual(self.msg.getArgs(message.OPENID_NS), {
'mode': 'error',
'error': 'unit test',
})
def test_getArgsBARE(self):
self.assertEqual(self.msg.getArgs(message.BARE_NS),
{'xey': 'value'})
def test_getArgsNS1(self):
self.assertEqual(self.msg.getArgs(message.OPENID1_NS), {})
def test_getArgsNS2(self):
self.assertEqual(self.msg.getArgs(message.OPENID2_NS), {
'mode': 'error',
'error': 'unit test',
})
def test_getArgsNS3(self):
self.assertEqual(self.msg.getArgs('urn:nothing-significant'), {})
def _test_updateArgsNS(self, ns, before=None):
if before is None:
before = {}
update_args = {
'<NAME>': '<NAME>',
'Magnolia Electric Co.': '<NAME>',
}
self.assertEqual(self.msg.getArgs(ns), before)
self.msg.updateArgs(ns, update_args)
after = dict(before)
after.update(update_args)
self.assertEqual(self.msg.getArgs(ns), after)
def test_updateArgsOpenID(self):
self._test_updateArgsNS(message.OPENID_NS,
before={'mode': 'error',
'error': 'unit test'})
def test_updateArgsBARE(self):
self._test_updateArgsNS(message.BARE_NS,
before={'xey': 'value'})
def test_updateArgsNS1(self):
self._test_updateArgsNS(message.OPENID1_NS)
def test_updateArgsNS2(self):
self._test_updateArgsNS(message.OPENID2_NS,
before={'mode': 'error',
'error': 'unit test'})
def test_updateArgsNS3(self):
self._test_updateArgsNS('urn:nothing-significant')
def _test_setArgNS(self, ns):
key = 'Camper van Beethoven'
value = '<NAME>'
self.assertEqual(self.msg.getArg(ns, key), None)
self.msg.setArg(ns, key, value)
self.assertEqual(self.msg.getArg(ns, key), value)
def test_setArgOpenID(self):
self._test_setArgNS(message.OPENID_NS)
def test_setArgBARE(self):
self._test_setArgNS(message.BARE_NS)
def test_setArgNS1(self):
self._test_setArgNS(message.OPENID1_NS)
def test_setArgNS2(self):
self._test_setArgNS(message.OPENID2_NS)
def test_setArgNS3(self):
| |
<gh_stars>1-10
""" Automated model order selection (AMOS) algorithm for spectral graph clustering (SGC)
"""
# Author: <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME>, Fellow, IEEE <<EMAIL>>
# License: BSD 3 clause
# Copyright: University of Michigan
from __future__ import division
import warnings
from math import asin
from sympy import binomial
import numpy as np
from scipy.sparse.linalg import norm as normSparse
from scipy.sparse.linalg import eigsh
from scipy.sparse import eye, spdiags, issparse, csr_matrix
from scipy.sparse.csgraph import connected_components
from scipy.stats import chi2, norm
from sklearn.cluster import KMeans as skKmeans
from joblib import Parallel,delayed
def controlIdxLen(idx):
""" Scipy has an issue if the array idx is only with a length of one
"""
if idx.size == 1:
idx = idx[0]
return idx
###################### AMOS ######################
def spectral_bound_est_weighted(Acc,labels,nest,k,alge_trace,verbose=False):
""" Phase transition bounds estimation
"""
if(len(alge_trace) != k):
# error
raise Exception('error', 'len(alge_trace) != k')
nmax = np.max(nest)
nmin = np.min(nest)
alge_trace_min = np.min(alge_trace)
num_interedge=0;
inter_edge_weight=0;
West = np.zeros((k, k))
west = 0
for i in range(0,k):
idx = np.nonzero(i==labels)[0]
idx = idx.reshape(idx.shape+(1,))
for j in range(i+1,k):
idx2 = np.nonzero(j==labels)[0]
idx2 = idx2.reshape(idx2.shape+(1,))
# scipy has an issue with single array value
idx2 = controlIdxLen(idx2)
tmpW= Acc[idx,np.transpose(idx2)]
temp = tmpW.nonzero()
nnz = tmpW[temp]
lenZero = len(temp[0])
if(lenZero == 0):
West[i][j] = 0;
else:
West[i][j] = np.mean(nnz)
num_interedge += lenZero
inter_edge_weight += nnz.sum()
if(num_interedge): west = inter_edge_weight / num_interedge
tmp = alge_trace_min/(k-1)
tLB = tmp / nmax;
tUB = tmp / nmin;
return tLB, tUB, West, west
def confidence_interval_spec_new(Aconn,k,labels,nest,alpha,verbose=False):
""" Homogeneous RIM test
"""
sym = int(binomial(k, 2))
# Chi-square inverse cumulative distribution function :
upp_quan = chi2.ppf(1-alpha/2, (sym-1),k/2)
low_quan = chi2.ppf(alpha/2, (sym-1),k/2)
# MLE estimate
n = len(labels);
m = len(Aconn.nonzero()[0])/2;
mest = np.zeros((k,k));
Pest = np.zeros((k,k));
for i in range(0,k):
idx = np.nonzero(i==labels)[0]
idx = idx.reshape(idx.shape+(1,))
idx = controlIdxLen(idx)
for j in range(i,k):
idx2 = np.nonzero(j==labels)[0]
idx2 = idx2.reshape(idx2.shape+(1,))
idx2 = np.transpose(controlIdxLen(idx2))
if(i == j):
mest[i][j]= len(Aconn[idx,idx2].nonzero()[0])/2
else:
mest[i][j]= len(Aconn[idx,idx2].nonzero()[0])
# Pest is triangle
for i in range(0,k):
for j in range(i+1,k):
if((np.dot(nest[i],nest[j])) == 0):
if(verbose): print 'zero cluster size'
else:
Pest[i,j] = mest[i][j]/np.dot(nest[i],nest[j])
pest=2*(m-mest.trace())/(np.dot(n,n)-np.sum(np.square(nest)))
LB_approx=0; UB_approx=0;
PestTmp = Pest;
PestTmp[PestTmp == 0]=1;
if(k>=3):
log1 = np.log(PestTmp)
log1[np.isneginf(log1)] = 0
log2 = np.log(1-PestTmp)
log2[np.isneginf(log2)] = 0
log3 = np.log(pest)
if(log3 == float('Inf')):
log3 = 0
log4 = np.log(1-pest)
if(log4 == float('Inf')):
log4 = 0
tmp = 2*np.multiply(mest,log1).sum() + 2*np.multiply(np.add(np.outer(nest,nest),-mest),log2).sum()
tmp += -2*(m-mest.trace())*log3
tmp += -(n*n-sum(np.square(nest))-2*(m-mest.trace()))*log4
if((tmp<=upp_quan)and(tmp>=low_quan)):
CI_ind=1;
else:
CI_ind=0;
else:
CI_ind=1;
return CI_ind,mest,pest,Pest
def estimate_Inhom_Weight(i,k,labels,Pest,tLB,West):
""" Inhomogeneous RIM phase transition test
"""
c=3/8;
tmp = 1
idx = np.nonzero(i==labels)[0]
idx = idx.reshape(idx.shape+(1,))
for j in range(i+1,k):
idx2 = np.nonzero(j==labels)[0]
idx2 = idx2.reshape(idx2.shape+(1,))
n1 = len(idx)
n2 = len(idx2)
n = n1*n2;
if(Pest[i][j] == 0):
tmp = tmp*(0 < tLB)
elif (Pest[i][j]==1):
tmp = tmp*(West[i,j] < tLB)
else:
x1 = asin(np.sqrt(tLB/West[i,j]+(c/n)/(1+2*c/n)));
x2 = asin(np.sqrt(Pest[i,j]+(c/n)/(1+2*c/n)));
x = np.sqrt(4*n+2)*(x1-x2);
tmp *= norm.cdf(x);
return tmp
def confidence_interval_inhom_RIM_Anscombe_InhomWeight(beta,West,Pest,tLB,k,labels,n_jobs,verbose=False):
results = Parallel(n_jobs=n_jobs, verbose=verbose)(delayed(estimate_Inhom_Weight)(i,k,labels,Pest,tLB,West) for i in range(0,k))
if(reduce(lambda a, b: a * b, results)>=1-beta):
CI_ind=1;
else:
CI_ind=0;
return CI_ind
def compute_alge_trace(idx,Acc,k,verbose=False):
""" Compute partial eigenvalue sum
"""
Atmp = Acc[idx,np.transpose(idx)]
n = Atmp.shape[0]
d = Atmp.sum(axis=1)
D = spdiags(np.transpose(d).reshape(-1),0,n,n,format='csr')
L = np.add(D,-Atmp)
if(n<=1):
if(verbose): print 'single or no cluster'
return 0
elif (n<=k):
if(verbose): print 'small cluster'
return Atmp.sum()
else:
return eigsh(L,k=k,which='SM',return_eigenvectors=False).sum()
def compute_alge_trace_parallel(labels,Acc,i,k):
idx = np.nonzero(i==labels)[0]
idx = idx.reshape(idx.shape+(1,))
idx = controlIdxLen(idx)
return compute_alge_trace(idx,Acc,k), len(idx)
def rimTest(Aconn,labels,k,Acc,pth,n_jobs=1,verbose=False):
""" V-test for testing the fitness of RIM, with p-value computation
"""
flag_CI = True
ci_condition = 0
results = Parallel(n_jobs, verbose=verbose)(delayed(compute_alge_trace_parallel)(labels,Acc,i,k) for i in range(0,k))
alge_trace, nest = zip(*results)
# p-value
# local homogeneity testing
Pvalue = np.zeros((k, k))
for i in range(0,k):
idx = np.nonzero(i==labels)[0]
idx = idx.reshape(idx.shape+(1,))
idx = controlIdxLen(idx)
for j in range(i+1,k):
idx2 = np.nonzero(j==labels)[0]
idx2 = idx2.reshape(idx2.shape+(1,))
idx2 = controlIdxLen(idx2)
tempC= Aconn[idx,idx2.T]
zeros = tempC.nonzero()
nnz = tempC[zeros]
lenZero = len(zeros[0])
if(lenZero == 0 or lenZero == nest[i]*nest[j]):
Pvalue[i][j] = 1;
else:
n1 = len(idx)
n2 = len(idx2)
x = tempC.sum(axis=1)
ide = np.full(tempC.shape, 1,np.double)
y = (ide-tempC).sum(axis=1)
X = np.dot(np.transpose(x),x)-x.sum()
Y = np.dot(np.transpose(y),y)-y.sum()
N = n1*n2*(n2-1)
V = np.square(np.sqrt(X)+np.sqrt(Y))
Z = (V-N)/np.sqrt(2*N)
nrm = norm.cdf(Z)
Pvalue[i][j] = 2*np.minimum(nrm,1-nrm)
if(Pvalue[i][j] < pth):
# RIM Pvalue
if(verbose): print 'Reject RIM'
flag_CI = False;
break;
else:
continue
break;
if(flag_CI):
if(verbose): print 'PASS RIM'
ci_condition = 1;
return flag_CI,ci_condition,nest, alge_trace
class AMOS():
def __init__(self, k=2, Kmax=50, alpha=0.05,
beta=0.05,pth=10^-5,Kmeans_replicate=50, n_jobs=1,
verbose=False):
""" Automated model order selection (AMOS) algorithm for spectral graph clustering (SGC)
Parameters
----------
k - number of clusters - start with 2 partitions
Kmax - maximum number of allowed clusters, smaller value of Kmax can speed up the computation process.
alpha - confidence interval parameter for homogeneous RIM test
beta - confidence interval parameter for inhomogeneous RIM test
pth - significance level for V-test
Kmeans_replicate - Number of time the k-means algorithm will be run.
verbose - whether to print intermediate results
n_jobs - the number of jobs to run in parallel. If -1, then the number of jobs is set to the number of cores.
"""
self.k = k
self.Kmax = Kmax
self.alpha = alpha
self.beta = beta
self.pth = pth
self.Kmeans_replicate = Kmeans_replicate
self.verbose = verbose
self.n_jobs = n_jobs
def check_matrix(self):
"""Evaluation of the input matrix A
"""
# check if the matrix is a Scipy sparse Matrix
if not issparse(self.Aconn):
self.Aconn = csr_matrix(self.Aconn)
# check symmetry
C = self.Aconn-self.Aconn.transpose()
err = normSparse(C)
if(err > 1e-10):
raise NameError('adjacency matrix is not symmetric')
# check connectivity
num_comp = connected_components(self.Aconn)[0]
if(num_comp != 1):
raise NameError('graph is not connected')
# check nonnegativity
if(self.Aconn[self.Aconn < 0.0].shape[1] > 0):
raise NameError('negative weight detected')
def get_eig_vector_Kmax(self,sigma=10e-10):
""" Compute Kmax smallest eigenpairs
Parameters
----------
sigma - shift regularizer
Returns
---------
Acc - Regularized adjacency matrix
eigVector_Kmax - Kmax eigenvalues
"""
self.check_matrix()
n = self.Aconn.shape[0]
if(n < self.Kmax):
raise NameError('Kmax is too high (> n)')
d = self.Aconn.sum(axis=0)
Dinv = spdiags((1/np.sqrt(d)).reshape(-1),0,n,n)
# regularized adjacency matrix Acc
Acc = Dinv.dot(self.Aconn.dot(Dinv));
Acc = np.add(Acc,np.transpose(Acc))/2
# Graph Laplacian matrix of the regularized adjacency matrix
D = spdiags(Acc.sum(axis=0),0,n,n,format='csr');
L = np.add(D, -Acc);
eigenvalues, eigVector_Kmax = eigsh(np.add(eye(n).multiply(sigma),L),k=self.Kmax,which='SM')
eigValue_Kmax = np.add(eigenvalues, -sigma*eye(self.Kmax).diagonal()).clip(min=0)
# sorted eigenvalues and eigenvectors in ascending order
idx = eigValue_Kmax.argsort()
eigVector_Kmax = eigVector_Kmax[:,idx]
return Acc, eigVector_Kmax
def predict(self,Aconn):
""" Predict the number of clusters
Parameters
----------
Aconn - Adjacency matrix of an undirected, weighted, and connected graph, which is a Scipy sparse matrix.
Returns:
---------
Number of clusters K,
Identified clusters (labels)
"""
num_pass_cases = 1 #stop at the minimal partition that satisfies the phase transition analysis
flag=1; flag_CI=1; num_pass=0;
self.Aconn = Aconn
Acc, eigVector_Kmax = self.get_eig_vector_Kmax()
k = self.k
west= 0;tLB=0;tUB = 0;
while(flag):
# Obtain K clusters with spectral clustering
if(self.verbose): print('k=%i clusters'%k)
eigVector_k = eigVector_Kmax[:,1:k]
kmeans = skKmeans(n_clusters=k, init='k-means++', n_init=self.Kmeans_replicate,n_jobs=self.n_jobs,copy_x=False)
labels = kmeans.fit_predict(eigVector_k)
# local homogeneity testing
flag_CI,ci_condition,nest,alge_trace = rimTest(self.Aconn,labels,k,Acc,self.pth,n_jobs=self.n_jobs,verbose=self.verbose)
# Confidence Interval of homogeneous RIM for k=2
if(flag_CI):
# confidence interval
CI_ind,mest,pest,Pest = confidence_interval_spec_new(self.Aconn,k,labels,nest,self.alpha,self.verbose)
tLB, tUB, West, west = spectral_bound_est_weighted(Acc,labels,nest,k,alge_trace)
# case k >= 3
if k >= 3:
# 'k >3'
ci_condition = CI_ind;
if(self.verbose): print 'ci_condition',ci_condition
if(ci_condition):
if(self.verbose): print 'within ',str(100*(1-self.alpha)),' % confidence interval, HomRIM'
flag_InRIM=0;
else:
if(self.verbose): print 'NOT within ',str(100*(1-self.alpha)),' % confidence interval, HomRIM'
flag_InRIM=1;
# homogeneous RIM phase transition test
if(ci_condition):
test = west*pest
if(test<tLB):
# the rows of each Yk is identical and cluster-wise distinct such that SGC can be successful
if(self.verbose): print 'relieble'
if(k==2):
num_pass=num_pass+1;
if(num_pass==num_pass_cases):
flag=0;
# k>=3
elif(ci_condition):
num_pass=num_pass+1;
if(num_pass==num_pass_cases):
flag=0;
elif(test<tUB):
if(self.verbose): print 'intermediate'
else:
# the row sum of each Yk is zero, and the incoher- ence of the entries in Yk make it impossible for SGC to separate the clusters
if(self.verbose): print 'unreliable'
elif(flag_InRIM):
# inhomogeneous RIM test
CI_ind_InRIM = confidence_interval_inhom_RIM_Anscombe_InhomWeight(self.beta,West,Pest,tLB,k,labels,n_jobs=self.n_jobs,verbose=self.verbose);
if(self.verbose): print 'Anscombe'
if(CI_ind_InRIM):
flag=0;
if(self.verbose): print 'within ',str(100*(1-self.beta)),' % confidence interval, InHomRIM'
else:
if(self.verbose): print 'NOT within ',str(100*(1-self.beta)),' % confidence | |
<filename>stubs/micropython-v1_17-esp32/builtins.py
"""
Module: 'builtins' on micropython-v1.17-esp32
"""
# MCU: {'ver': 'v1.17', 'port': 'esp32', 'arch': 'xtensawin', 'sysname': 'esp32', 'release': '1.17.0', 'name': 'micropython', 'mpy': 10757, 'version': '1.17.0', 'machine': 'ESP32 module (spiram) with ESP32', 'build': '', 'nodename': 'esp32', 'platform': 'esp32', 'family': 'micropython'}
# Stubber: 1.5.4
from typing import Any
class ArithmeticError(Exception):
""""""
class AssertionError(Exception):
""""""
class AttributeError(Exception):
""""""
class EOFError(Exception):
""""""
Ellipsis: Any ## <class ''> = Ellipsis
class GeneratorExit:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
class ImportError(Exception):
""""""
class IndentationError(Exception):
""""""
class IndexError(Exception):
""""""
class KeyError(Exception):
""""""
class KeyboardInterrupt(Exception):
""""""
class LookupError(Exception):
""""""
class MemoryError(Exception):
""""""
class NameError(Exception):
""""""
class NotImplementedError(Exception):
""""""
class OSError(Exception):
""""""
class OverflowError(Exception):
""""""
class RuntimeError(Exception):
""""""
class StopIteration(Exception):
""""""
class SyntaxError(Exception):
""""""
class SystemExit(Exception):
""""""
class TypeError(Exception):
""""""
class ValueError(Exception):
""""""
class ZeroDivisionError(Exception):
""""""
def abs(*args, **kwargs) -> Any:
...
def all(*args, **kwargs) -> Any:
...
def any(*args, **kwargs) -> Any:
...
class bool:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
class bytearray:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
def append(self, *args, **kwargs) -> Any:
...
def extend(self, *args, **kwargs) -> Any:
...
def decode(self, *args, **kwargs) -> Any:
...
class bytes:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
def count(self, *args, **kwargs) -> Any:
...
def endswith(self, *args, **kwargs) -> Any:
...
def find(self, *args, **kwargs) -> Any:
...
def format(self, *args, **kwargs) -> Any:
...
def index(self, *args, **kwargs) -> Any:
...
def isalpha(self, *args, **kwargs) -> Any:
...
def isdigit(self, *args, **kwargs) -> Any:
...
def islower(self, *args, **kwargs) -> Any:
...
def isspace(self, *args, **kwargs) -> Any:
...
def isupper(self, *args, **kwargs) -> Any:
...
def join(self, *args, **kwargs) -> Any:
...
def lower(self, *args, **kwargs) -> Any:
...
def lstrip(self, *args, **kwargs) -> Any:
...
def replace(self, *args, **kwargs) -> Any:
...
def rfind(self, *args, **kwargs) -> Any:
...
def rindex(self, *args, **kwargs) -> Any:
...
def rsplit(self, *args, **kwargs) -> Any:
...
def rstrip(self, *args, **kwargs) -> Any:
...
def split(self, *args, **kwargs) -> Any:
...
def startswith(self, *args, **kwargs) -> Any:
...
def strip(self, *args, **kwargs) -> Any:
...
def upper(self, *args, **kwargs) -> Any:
...
def center(self, *args, **kwargs) -> Any:
...
def decode(self, *args, **kwargs) -> Any:
...
def partition(self, *args, **kwargs) -> Any:
...
def rpartition(self, *args, **kwargs) -> Any:
...
def splitlines(self, *args, **kwargs) -> Any:
...
def callable(*args, **kwargs) -> Any:
...
def chr(*args, **kwargs) -> Any:
...
class dict:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
def clear(self, *args, **kwargs) -> Any:
...
def copy(self, *args, **kwargs) -> Any:
...
def get(self, *args, **kwargs) -> Any:
...
def items(self, *args, **kwargs) -> Any:
...
def keys(self, *args, **kwargs) -> Any:
...
def pop(self, *args, **kwargs) -> Any:
...
def popitem(self, *args, **kwargs) -> Any:
...
def setdefault(self, *args, **kwargs) -> Any:
...
def update(self, *args, **kwargs) -> Any:
...
def values(self, *args, **kwargs) -> Any:
...
@classmethod
def fromkeys(cls, *args, **kwargs) -> Any:
...
def dir(*args, **kwargs) -> Any:
...
def divmod(*args, **kwargs) -> Any:
...
def eval(*args, **kwargs) -> Any:
...
def exec(*args, **kwargs) -> Any:
...
def getattr(*args, **kwargs) -> Any:
...
def globals(*args, **kwargs) -> Any:
...
def hasattr(*args, **kwargs) -> Any:
...
def hash(*args, **kwargs) -> Any:
...
def id(*args, **kwargs) -> Any:
...
class int:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
@classmethod
def from_bytes(cls, *args, **kwargs) -> Any:
...
def to_bytes(self, *args, **kwargs) -> Any:
...
def isinstance(*args, **kwargs) -> Any:
...
def issubclass(*args, **kwargs) -> Any:
...
def iter(*args, **kwargs) -> Any:
...
def len(*args, **kwargs) -> Any:
...
class list:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
def append(self, *args, **kwargs) -> Any:
...
def clear(self, *args, **kwargs) -> Any:
...
def copy(self, *args, **kwargs) -> Any:
...
def count(self, *args, **kwargs) -> Any:
...
def extend(self, *args, **kwargs) -> Any:
...
def index(self, *args, **kwargs) -> Any:
...
def insert(self, *args, **kwargs) -> Any:
...
def pop(self, *args, **kwargs) -> Any:
...
def remove(self, *args, **kwargs) -> Any:
...
def reverse(self, *args, **kwargs) -> Any:
...
def sort(self, *args, **kwargs) -> Any:
...
def locals(*args, **kwargs) -> Any:
...
class map:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
def next(*args, **kwargs) -> Any:
...
class object:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
def open(*args, **kwargs) -> Any:
...
def ord(*args, **kwargs) -> Any:
...
def pow(*args, **kwargs) -> Any:
...
def print(*args, **kwargs) -> Any:
...
class range:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
def repr(*args, **kwargs) -> Any:
...
def round(*args, **kwargs) -> Any:
...
class set:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
def clear(self, *args, **kwargs) -> Any:
...
def copy(self, *args, **kwargs) -> Any:
...
def pop(self, *args, **kwargs) -> Any:
...
def remove(self, *args, **kwargs) -> Any:
...
def update(self, *args, **kwargs) -> Any:
...
def add(self, *args, **kwargs) -> Any:
...
def difference(self, *args, **kwargs) -> Any:
...
def difference_update(self, *args, **kwargs) -> Any:
...
def discard(self, *args, **kwargs) -> Any:
...
def intersection(self, *args, **kwargs) -> Any:
...
def intersection_update(self, *args, **kwargs) -> Any:
...
def isdisjoint(self, *args, **kwargs) -> Any:
...
def issubset(self, *args, **kwargs) -> Any:
...
def issuperset(self, *args, **kwargs) -> Any:
...
def symmetric_difference(self, *args, **kwargs) -> Any:
...
def symmetric_difference_update(self, *args, **kwargs) -> Any:
...
def union(self, *args, **kwargs) -> Any:
...
def setattr(*args, **kwargs) -> Any:
...
def sorted(*args, **kwargs) -> Any:
...
class str:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
def count(self, *args, **kwargs) -> Any:
...
def endswith(self, *args, **kwargs) -> Any:
...
def find(self, *args, **kwargs) -> Any:
...
def format(self, *args, **kwargs) -> Any:
...
def index(self, *args, **kwargs) -> Any:
...
def isalpha(self, *args, **kwargs) -> Any:
...
def isdigit(self, *args, **kwargs) -> Any:
...
def islower(self, *args, **kwargs) -> Any:
...
def isspace(self, *args, **kwargs) -> Any:
...
def isupper(self, *args, **kwargs) -> Any:
...
def join(self, *args, **kwargs) -> Any:
...
def lower(self, *args, **kwargs) -> Any:
...
def lstrip(self, *args, **kwargs) -> Any:
...
def replace(self, *args, **kwargs) -> Any:
...
def rfind(self, *args, **kwargs) -> Any:
...
def rindex(self, *args, **kwargs) -> Any:
...
def rsplit(self, *args, **kwargs) -> Any:
...
def rstrip(self, *args, **kwargs) -> Any:
...
def split(self, *args, **kwargs) -> Any:
...
def startswith(self, *args, **kwargs) -> Any:
...
def strip(self, *args, **kwargs) -> Any:
...
def upper(self, *args, **kwargs) -> Any:
...
def center(self, *args, **kwargs) -> Any:
...
def encode(self, *args, **kwargs) -> Any:
...
def partition(self, *args, **kwargs) -> Any:
...
def rpartition(self, *args, **kwargs) -> Any:
...
def splitlines(self, *args, **kwargs) -> Any:
...
def sum(*args, **kwargs) -> Any:
...
class super:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
class tuple:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
def count(self, *args, **kwargs) -> Any:
...
def index(self, *args, **kwargs) -> Any:
...
class type:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
class zip:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
NotImplemented: Any ## <class ''> = NotImplemented
class StopAsyncIteration:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
class UnicodeError(Exception):
""""""
class ViperTypeError(Exception):
""""""
def bin(*args, **kwargs) -> Any:
...
def compile(*args, **kwargs) -> Any:
...
class complex:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
def delattr(*args, **kwargs) -> Any:
...
class enumerate:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
def execfile(*args, **kwargs) -> Any:
...
class filter:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
class float:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
class frozenset:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
def copy(self, *args, **kwargs) -> Any:
...
def difference(self, *args, **kwargs) -> Any:
...
def intersection(self, *args, **kwargs) -> Any:
...
def isdisjoint(self, *args, **kwargs) -> Any:
...
def issubset(self, *args, **kwargs) -> Any:
...
def issuperset(self, *args, **kwargs) -> Any:
...
def symmetric_difference(self, *args, **kwargs) -> Any:
...
def union(self, *args, **kwargs) -> Any:
...
def help(*args, **kwargs) -> Any:
...
def hex(*args, **kwargs) -> Any:
...
def input(*args, **kwargs) -> Any:
...
def max(*args, **kwargs) -> Any:
...
class memoryview:
""""""
def __init__(self, *argv, **kwargs) -> None:
""""""
...
def min(*args, **kwargs) -> Any:
...
def oct(*args, **kwargs) | |
#
# calcpos.py -- module for wrapping astronomical ephemeris calculations
#
import math
# third-party imports
import numpy as np
from datetime import datetime, timedelta
from dateutil import tz
import dateutil.parser
# right now we just have pyephem...
import ephem
# Constants
#earth_radius = 6378160.0
# TODO: more precise calculation
#minute = 0.0006944444444444444
def alt2airmass(alt_deg):
xp = 1.0 / math.sin(math.radians(alt_deg + 244.0/(165.0 + 47*alt_deg**1.1)))
return xp
am_inv = []
for alt in range(0, 91):
alt_deg = float(alt)
am = alt2airmass(alt_deg)
am_inv.append((am, alt_deg))
def airmass2alt(am):
# TODO: horribly inefficient lookup--FIX!
for (x, alt_deg) in am_inv:
if x <= am:
return alt_deg
return 90.0
#### Classes ####
class Observer(object):
"""
Observer
"""
def __init__(self, name, timezone=None, longitude=None, latitude=None,
elevation=None, pressure=None, temperature=None,
date=None, description=None):
super(Observer, self).__init__()
self.name = name
self.timezone = timezone
self.longitude = longitude
self.latitude = latitude
self.elevation = elevation
self.pressure = pressure
self.temperature = temperature
self.date = date
self.horizon = -1 * np.sqrt(2 * elevation / ephem.earth_radius)
if timezone is None:
# default to UTC
timezone = tz.UTC
self.tz_local = timezone
self.tz_utc = tz.UTC
self.site = self.get_site(date=date)
# used for sunset, sunrise calculations
self.horizon6 = -1.0 * ephem.degrees('06:00:00.0')
self.horizon12 = -1.0 * ephem.degrees('12:00:00.0')
self.horizon18 = -1.0 * ephem.degrees('18:00:00.0')
self.sun = ephem.Sun()
self.moon = ephem.Moon()
self.sun.compute(self.site)
self.moon.compute(self.site)
def get_site(self, date=None, horizon_deg=None):
site = ephem.Observer()
site.lon = self.longitude
site.lat = self.latitude
site.elevation = self.elevation
site.pressure = self.pressure
site.temp = self.temperature
if horizon_deg != None:
site.horizon = math.radians(horizon_deg)
else:
site.horizon = self.horizon
site.epoch = 2000.0
if date is None:
date = datetime.utcnow().replace(tzinfo=self.tz_utc)
site.date = ephem.Date(self.date_to_utc(date))
return site
def date_to_utc(self, date):
"""Convert a datetime to UTC.
NOTE: If the datetime object is not timezone aware, it is
assumed to be in the timezone of the observer.
"""
if date.tzinfo is not None:
# date is timezone-aware
date = date.astimezone(self.tz_utc)
else:
# date is a naive date: assume expressed in local time
date = date.replace(tzinfo=self.tz_local)
# and converted to UTC
date = date.astimezone(self.tz_utc)
return date
def date_to_local(self, date):
"""Convert a datetime to the observer's timezone.
NOTE: If the datetime object is not timezone aware, it is
assumed to be in UTC.
"""
if date.tzinfo is not None:
# date is timezone-aware
date = date.astimezone(self.tz_local)
else:
# date is a naive date: assume expressed in UTC
date = date.replace(tzinfo=self.tz_utc)
# and converted to local time
date = date.astimezone(self.tz_local)
return date
def set_date(self, date):
"""Set the date for the observer. This is converted and
stored internally in the timezone set for the observer.
"""
self.date = self.date_to_local(date)
# ephem deals only in UTC
self.site.date = ephem.Date(self.date_to_utc(self.date))
def radec_of(self, az_deg, alt_deg):
ra, dec = self.site.radec_of(np.radians(az_deg), np.radians(alt_deg))
ra_deg, dec_deg = np.degrees([ra, dec])
return ra_deg, dec_deg
def azalt_of(self, ra_deg, dec_deg):
body = ephem.FixedBody()
body._ra = np.radians(ra_deg)
body._dec = np.radians(dec_deg)
body.compute(self.site)
az_deg, alt_deg = np.degrees([body.az, body.alt])
return az_deg, alt_deg
def calc(self, body, time_start):
return body.calc(self, time_start)
def get_date(self, date_str, timezone=None):
"""Get a datetime object, converted from a date string.
The timezone is assumed to be that of the observer, unless
explicitly supplied in the `timezone` kwarg.
"""
if timezone is None:
timezone = self.tz_local
dt = dateutil.parser.parse(date_str)
date = dt.replace(tzinfo=timezone)
return date
## def _observable(self, target, time_start, time_stop,
## el_min_deg, el_max_deg,
## airmass=None):
## c1 = self.calc(target, time_start)
## c2 = self.calc(target, time_stop)
## return ((el_min_deg <= c1.alt_deg <= el_max_deg) and
## (el_min_deg <= c2.alt_deg <= el_max_deg)
## and
## ((airmass is None) or ((c1.airmass <= airmass) and
## (c2.airmass <= airmass))))
def observable(self, target, time_start, time_stop,
el_min_deg, el_max_deg, time_needed,
airmass=None, moon_sep=None):
"""
Return True if `target` is observable between `time_start` and
`time_stop`, defined by whether it is between elevation `el_min`
and `el_max` during that period, and whether it meets the minimum
airmass.
"""
# set observer's horizon to elevation for el_min or to achieve
# desired airmass
if airmass != None:
# compute desired altitude from airmass
alt_deg = airmass2alt(airmass)
min_alt_deg = max(alt_deg, el_min_deg)
else:
min_alt_deg = el_min_deg
site = self.get_site(date=time_start, horizon_deg=min_alt_deg)
d1 = self.calc(target, time_start)
# TODO: worry about el_max_deg
# important: ephem only deals with UTC!!
time_start_utc = ephem.Date(self.date_to_utc(time_start))
time_stop_utc = ephem.Date(self.date_to_utc(time_stop))
#print("period (UT): %s to %s" % (time_start_utc, time_stop_utc))
if d1.alt_deg >= min_alt_deg:
# body is above desired altitude at start of period
# so calculate next setting
time_rise = time_start_utc
time_set = site.next_setting(target.body._body,
start=time_start_utc)
#print("body already up: set=%s" % (time_set))
else:
# body is below desired altitude at start of period
try:
time_rise = site.next_rising(target.body._body,
start=time_start_utc)
time_set = site.next_setting(target.body._body,
start=time_start_utc)
except ephem.NeverUpError:
return (False, None, None)
#print("body not up: rise=%s set=%s" % (time_rise, time_set))
## if time_rise < time_set:
## print("body still rising, below threshold")
## # <-- body is still rising, just not high enough yet
## else:
## # <-- body is setting
## print("body setting, below threshold")
## # calculate rise time backward from end of period
## #time_rise = site.previous_rising(target.body, start=time_stop_utc)
## pass
if time_rise < time_start_utc:
diff = time_rise - time_start_utc
## raise AssertionError("time rise (%s) < time start (%s)" % (
## time_rise, time_start))
print(("WARNING: time rise (%s) < time start (%s)" % (
time_rise, time_start)))
time_rise = time_start_utc
# last observable time is setting or end of period,
# whichever comes first
time_end = min(time_set, time_stop_utc)
# calculate duration in seconds (subtracting two ephem Date
# objects seems to give a fraction in days)
duration = (time_end - time_rise) * 86400.0
# object is observable as long as the duration that it is
# up is as long or longer than the time needed
diff = duration - float(time_needed)
#can_obs = diff > -0.001
can_obs = duration > time_needed
#print("can_obs=%s duration=%f needed=%f diff=%f" % (
# can_obs, duration, time_needed, diff))
# convert times back to datetime's
time_rise = self.date_to_local(time_rise.datetime())
time_end = self.date_to_local(time_end.datetime())
return (can_obs, time_rise, time_end)
def distance(self, tgt1, tgt2, time_start):
c1 = self.calc(tgt1, time_start)
c2 = self.calc(tgt2, time_start)
d_alt = c1.alt_deg - c2.alt_deg
d_az = c1.az_deg - c2.az_deg
return (d_alt, d_az)
def _set_site_date(self, date):
if not isinstance(date, ephem.Date):
if date is None:
date = self.date
date = self.date_to_utc(date)
date = ephem.Date(date)
self.site.date = date
def sunset(self, date=None):
"""Returns sunset in observer's time."""
self.site.horizon = self.horizon
self._set_site_date(date)
r_date = self.site.next_setting(self.sun)
r_date = self.date_to_local(r_date.datetime())
return r_date
def sunrise(self, date=None):
"""Returns sunrise in observer's time."""
self.site.horizon = self.horizon
self._set_site_date(date)
r_date = self.site.next_rising(self.sun)
r_date = self.date_to_local(r_date.datetime())
return r_date
def evening_twilight_6(self, date=None):
"""Returns evening 6 degree civil twilight(civil dusk) in observer's time.
"""
self.site.horizon = self.horizon6
self._set_site_date(date)
r_date = self.site.next_setting(self.sun)
r_date = self.date_to_local(r_date.datetime())
return r_date
def evening_twilight_12(self, date=None):
"""Returns evening 12 degree (nautical) twilight in observer's time.
"""
self.site.horizon = self.horizon12
self._set_site_date(date)
r_date = self.site.next_setting(self.sun)
r_date = self.date_to_local(r_date.datetime())
return r_date
def evening_twilight_18(self, date=None):
"""Returns evening 18 degree (civil) twilight in observer's time.
"""
self.site.horizon = self.horizon18
self._set_site_date(date)
r_date = self.site.next_setting(self.sun)
r_date = self.date_to_local(r_date.datetime())
return r_date
def morning_twilight_6(self, date=None):
"""Returns morning 6 degree civil twilight(civil dawn) in observer's time.
"""
self.site.horizon = self.horizon6
self._set_site_date(date)
r_date = self.site.next_rising(self.sun)
r_date = self.date_to_local(r_date.datetime())
return r_date
def morning_twilight_12(self, date=None):
"""Returns morning 12 degree (nautical) twilight in observer's time.
"""
self.site.horizon = self.horizon12
self._set_site_date(date)
r_date = self.site.next_rising(self.sun)
r_date = self.date_to_local(r_date.datetime())
return r_date
def morning_twilight_18(self, date=None):
"""Returns morning 18 degree (civil) twilight in observer's time.
"""
self.site.horizon = self.horizon18
self._set_site_date(date)
r_date = self.site.next_rising(self.sun)
r_date = self.date_to_local(r_date.datetime())
return r_date
def sun_set_rise_times(self, date=None):
"""Sunset, sunrise and twilight times. Returns a tuple with
(sunset, 12d, 18d, 18d, 12d, sunrise) in observer's time.
"""
rstimes = (self.sunset(date=date),
self.evening_twilight_12(date=date),
self.evening_twilight_18(date=date),
self.morning_twilight_18(date=date),
self.morning_twilight_12(date=date),
self.sunrise(date=date))
return rstimes
def moon_rise(self, date=None):
"""Returns moon rise time in observer's time."""
self._set_site_date(date)
moonrise = self.site.next_rising(self.moon)
moonrise = self.date_to_local(moonrise.datetime())
## if moonrise < self.sunset():
## moonrise = None
return moonrise
def moon_set(self, date=None):
"""Returns moon set time in observer's time."""
self._set_site_date(date)
moonset = self.site.next_setting(self.moon)
moonset = self.date_to_local(moonset.datetime())
## if moonset > self.sunrise():
## moonset = None
return moonset
def moon_phase(self, date=None):
"""Returns moon percentage of illumination."""
self._set_site_date(date)
self.moon.compute(self.site)
return self.moon.moon_phase
def night_center(self, date=None):
"""Returns night center in observer's time."""
sunset = self.sunset(date=date)
sunrise = self.sunrise(date=sunset)
center = sunset + timedelta(0, (sunrise - sunset).total_seconds() | |
from functools import reduce
import uuid
import re
import copy
class Expression:
""" Abstract taintable Expression. """
def __init__(self, taint=()):
if self.__class__ is Expression:
raise TypeError
assert isinstance(taint, (tuple, frozenset))
super().__init__()
self._taint = frozenset(taint)
def __repr__(self):
return "<{:s} at {:x}{:s}>".format(type(self).__name__, id(self), self.taint and "-T" or "")
@property
def is_tainted(self):
return len(self._taint) != 0
@property
def taint(self):
return self._taint
def issymbolic(value):
"""
Helper to determine whether an object is symbolic (e.g checking
if data read from memory is symbolic)
:param object value: object to check
:return: whether `value` is symbolic
:rtype: bool
"""
return isinstance(value, Expression)
def istainted(arg, taint=None):
"""
Helper to determine whether an object if tainted.
:param arg: a value or Expression
:param taint: a regular expression matching a taint value (eg. 'IMPORTANT.*'). If None, this function checks for any taint value.
"""
if not issymbolic(arg):
return False
if taint is None:
return len(arg.taint) != 0
for arg_taint in arg.taint:
m = re.match(taint, arg_taint, re.DOTALL | re.IGNORECASE)
if m:
return True
return False
def get_taints(arg, taint=None):
"""
Helper to list an object taints.
:param arg: a value or Expression
:param taint: a regular expression matching a taint value (eg. 'IMPORTANT.*'). If None, this function checks for any taint value.
"""
if not issymbolic(arg):
return
for arg_taint in arg.taint:
if taint is not None:
m = re.match(taint, arg_taint, re.DOTALL | re.IGNORECASE)
if m:
yield arg_taint
else:
yield arg_taint
return
def taint_with(arg, *taints, value_bits=256, index_bits=256):
"""
Helper to taint a value.
:param arg: a value or Expression
:param taint: a regular expression matching a taint value (eg. 'IMPORTANT.*'). If None, this function checks for any taint value.
"""
tainted_fset = frozenset(tuple(taints))
if not issymbolic(arg):
if isinstance(arg, int):
arg = BitVecConstant(value_bits, arg)
arg._taint = tainted_fset
else:
raise ValueError("type not supported")
else:
if isinstance(arg, BitVecVariable):
arg = arg + BitVecConstant(value_bits, 0, taint=tainted_fset)
else:
arg = copy.copy(arg)
arg._taint |= tainted_fset
return arg
class Variable(Expression):
def __init__(self, name, *args, **kwargs):
if self.__class__ is Variable:
raise TypeError
assert isinstance(name, str) and " " not in name
super().__init__(*args, **kwargs)
self._name = name
@property
def declaration(self):
pass
@property
def name(self):
return self._name
def __copy__(self, memo):
raise Exception("Copying of Variables is not allowed.")
def __deepcopy__(self, memo):
raise Exception("Copying of Variables is not allowed.")
def __repr__(self):
return "<{:s}({:s}) at {:x}>".format(type(self).__name__, self.name, id(self))
class Constant(Expression):
def __init__(self, value, *args, **kwargs):
if self.__class__ is Constant:
raise TypeError
assert isinstance(value, (bool, int))
super().__init__(*args, **kwargs)
self._value = value
@property
def value(self):
return self._value
class Operation(Expression):
def __init__(self, *operands, **kwargs):
if self.__class__ is Operation:
raise TypeError
# assert len(operands) > 0
# assert all(isinstance(x, Expression) for x in operands)
self._operands = operands
# If taint was not forced by a keyword argument, calculate default
if "taint" not in kwargs:
kwargs["taint"] = reduce(lambda x, y: x.union(y.taint), operands, frozenset())
super().__init__(**kwargs)
@property
def operands(self):
return self._operands
###############################################################################
# Booleans
class Bool(Expression):
def __init__(self, *operands, **kwargs):
super().__init__(*operands, **kwargs)
def cast(self, value, **kwargs):
if isinstance(value, Bool):
return value
assert isinstance(value, (int, bool))
return BoolConstant(bool(value), **kwargs)
def __cmp__(self, *args):
raise NotImplementedError("CMP for Bool")
def __invert__(self):
return BoolNot(self)
def __eq__(self, other):
return BoolEq(self, self.cast(other))
def __hash__(self):
return object.__hash__(self)
def __ne__(self, other):
return BoolNot(self == self.cast(other))
def __and__(self, other):
return BoolAnd(self, self.cast(other))
def __or__(self, other):
return BoolOr(self, self.cast(other))
def __xor__(self, other):
return BoolXor(self, self.cast(other))
def __rand__(self, other):
return BoolAnd(self.cast(other), self)
def __ror__(self, other):
return BoolOr(self.cast(other), self)
def __rxor__(self, other):
return BoolXor(self.cast(other), self)
def __bool__(self):
raise NotImplementedError("__bool__ for Bool")
class BoolVariable(Bool, Variable):
def __init__(self, name, *args, **kwargs):
super().__init__(name, *args, **kwargs)
@property
def declaration(self):
return f"(declare-fun {self.name} () Bool)"
class BoolConstant(Bool, Constant):
def __init__(self, value, *args, **kwargs):
assert isinstance(value, bool)
super().__init__(value, *args, **kwargs)
def __bool__(self):
return self.value
class BoolOperation(Operation, Bool):
def __init__(self, *operands, **kwargs):
super().__init__(*operands, **kwargs)
class BoolNot(BoolOperation):
def __init__(self, value, **kwargs):
super().__init__(value, **kwargs)
class BoolEq(BoolOperation):
def __init__(self, a, b, **kwargs):
super().__init__(a, b, **kwargs)
class BoolAnd(BoolOperation):
def __init__(self, a, b, **kwargs):
super().__init__(a, b, **kwargs)
class BoolOr(BoolOperation):
def __init__(self, a, b, **kwargs):
assert isinstance(a, Bool)
assert isinstance(b, Bool)
super().__init__(a, b, **kwargs)
class BoolXor(BoolOperation):
def __init__(self, a, b, **kwargs):
super().__init__(a, b, **kwargs)
class BoolITE(BoolOperation):
def __init__(self, cond, true, false, **kwargs):
assert isinstance(true, Bool)
assert isinstance(false, Bool)
assert isinstance(cond, Bool)
super().__init__(cond, true, false, **kwargs)
class BitVec(Expression):
""" This adds a bitsize to the Expression class """
def __init__(self, size, *operands, **kwargs):
super().__init__(*operands, **kwargs)
self.size = size
@property
def mask(self):
return (1 << self.size) - 1
@property
def signmask(self):
return 1 << (self.size - 1)
def cast(self, value, **kwargs):
if isinstance(value, BitVec):
assert value.size == self.size
return value
if isinstance(value, (str, bytes)) and len(value) == 1:
value = ord(value)
# Try to support not Integral types that can be casted to int
if not isinstance(value, int):
value = int(value)
# FIXME? Assert it fits in the representation
return BitVecConstant(self.size, value, **kwargs)
def __add__(self, other):
return BitVecAdd(self, self.cast(other))
def __sub__(self, other):
return BitVecSub(self, self.cast(other))
def __mul__(self, other):
return BitVecMul(self, self.cast(other))
def __mod__(self, other):
return BitVecMod(self, self.cast(other))
# object.__divmod__(self, other)
# object.__pow__(self, other[, modulo])
def __lshift__(self, other):
return BitVecShiftLeft(self, self.cast(other))
def __rshift__(self, other):
return BitVecShiftRight(self, self.cast(other))
def __and__(self, other):
return BitVecAnd(self, self.cast(other))
def __xor__(self, other):
return BitVecXor(self, self.cast(other))
def __or__(self, other):
return BitVecOr(self, self.cast(other))
# The division operator (/) is implemented by these methods. The
# __truediv__() method is used when __future__.division is in effect,
# otherwise __div__() is used. If only one of these two methods is
# defined, the object will not support division in the alternate context;
# TypeError will be raised instead.
def __div__(self, other):
return BitVecDiv(self, self.cast(other))
def __truediv__(self, other):
return BitVecDiv(self, self.cast(other))
def __floordiv__(self, other):
return self / other
# These methods are called to implement the binary arithmetic operations
# (+, # -, *, /, %, divmod(), pow(), **, <<, >>, &, ^, |) with reflected
# (swapped) operands. These functions are only called if the left operand
# does not support the corresponding operation and the operands are of
# different types. [2] For instance, to evaluate the expression x - y,
# where y is an instance of a class that has an __rsub__() method,
# y.__rsub__(x) is called if x.__sub__(y) returns NotImplemented.
def __radd__(self, other):
return BitVecAdd(self.cast(other), self)
def __rsub__(self, other):
return BitVecSub(self.cast(other), self)
def __rmul__(self, other):
return BitVecMul(self.cast(other), self)
def __rmod__(self, other):
return BitVecMod(self.cast(other), self)
def __rtruediv__(self, other):
return BitVecDiv(self.cast(other), self)
def __rdiv__(self, other):
return BitVecDiv(self.cast(other), self)
# object.__rdivmod__(self, other)
# object.__rpow__(self, other)
def __rlshift__(self, other):
return BitVecShiftLeft(self.cast(other), self)
def __rrshift__(self, other):
return BitVecShiftRight(self.cast(other), self)
def __rand__(self, other):
return BitVecAnd(self.cast(other), self)
def __rxor__(self, other):
return BitVecXor(self.cast(other), self)
def __ror__(self, other):
return BitVecOr(self.cast(other), self)
def __invert__(self):
return BitVecXor(self, self.cast(self.mask))
# These are the so-called "rich comparison" methods, and are called
# for comparison operators in preference to __cmp__() below. The
# correspondence between operator symbols and method names is as
# follows:
# x<y calls x.__lt__(y),
# x<=y calls x.__le__(y),
# x==y calls x.__eq__(y),
# x!=y and x<>y call x.__ne__(y),
# x>y calls x.__gt__(y), and
# x>=y calls x.__ge__(y).
def __lt__(self, other):
return LessThan(self, self.cast(other))
def __le__(self, other):
return LessOrEqual(self, self.cast(other))
def __eq__(self, other):
return Equal(self, self.cast(other))
def __hash__(self):
return object.__hash__(self)
def __ne__(self, other):
return BoolNot(Equal(self, self.cast(other)))
def __gt__(self, other):
return GreaterThan(self, self.cast(other))
def __ge__(self, other):
return GreaterOrEqual(self, self.cast(other))
def __neg__(self):
return BitVecNeg(self)
# Unsigned comparisons
def ugt(self, other):
return UnsignedGreaterThan(self, self.cast(other))
def uge(self, other):
return UnsignedGreaterOrEqual(self, self.cast(other))
def ult(self, other):
return UnsignedLessThan(self, self.cast(other))
def ule(self, other):
return UnsignedLessOrEqual(self, self.cast(other))
def udiv(self, other):
return BitVecUnsignedDiv(self, self.cast(other))
def rudiv(self, other):
return BitVecUnsignedDiv(self.cast(other), self)
def srem(self, other):
return BitVecRem(self, self.cast(other))
def rsrem(self, other):
return BitVecRem(self.cast(other), self)
def urem(self, other):
return BitVecUnsignedRem(self, self.cast(other))
def rurem(self, other):
return BitVecUnsignedRem(self.cast(other), self)
def sar(self, other):
return BitVecArithmeticShiftRight(self, self.cast(other))
def sal(self, other):
return BitVecArithmeticShiftLeft(self, self.cast(other))
def Bool(self):
return self != 0
class BitVecVariable(BitVec, Variable):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@property
def declaration(self):
return f"(declare-fun {self.name} () (_ BitVec {self.size}))"
class BitVecConstant(BitVec, Constant):
def __init__(self, size, value, *args, **kwargs):
assert isinstance(value, int)
super().__init__(size, value, *args, **kwargs)
def __bool__(self):
return self.value != 0
def __eq__(self, other):
if self.taint:
return super().__eq__(other)
return self.value == other
def | |
# 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 re
import ruamel.yaml
from orquestaconvert.expressions import jinja
from orquestaconvert.expressions import yaql as yql
from orquestaconvert.workflows import base as workflows_base
from tests import base_test_case
OrderedMap = ruamel.yaml.comments.CommentedMap
base_test_case.BaseTestCase.maxDiff = None
class TestWorkflows(base_test_case.BaseTestCase):
__test__ = True
def __init__(self, *args, **kwargs):
super(TestWorkflows, self).__init__(*args, **kwargs)
self.maxDiff = None
def test_group_task_transitions(self):
converter = workflows_base.WorkflowConverter()
transitions_list = [
"simple transition string",
{"key": "expr"},
"another simple transition string",
{"key2": "expression"},
{"key3": "expr"},
]
simple, expr = converter.group_task_transitions(transitions_list)
self.assertEqual(simple, ["simple transition string",
"another simple transition string"])
expected = OrderedMap([("expr", ["key", "key3"]),
("expression", ["key2"])])
self.assertEqual(expr, expected)
def test_group_task_string_transition(self):
converter = workflows_base.WorkflowConverter()
transitions_string = 'next_task'
simple, expr = converter.group_task_transitions(transitions_string)
self.assertEqual(simple, ['next_task'])
def test_group_task_transitions_raises_bad_type(self):
converter = workflows_base.WorkflowConverter()
transitions_list = [["list is bad"]]
with self.assertRaises(TypeError):
converter.group_task_transitions(transitions_list)
def test_dict_to_list(self):
converter = workflows_base.WorkflowConverter()
d = OrderedMap([('key1', 'value1'),
('key2', 'value2'),
('key3', 'value3')])
result = converter.dict_to_list(d)
self.assertEqual(result, [{'key1': 'value1'},
{'key2': 'value2'},
{'key3': 'value3'}])
def test_extract_context_variables(self):
converter = workflows_base.WorkflowConverter()
output_block = OrderedMap([
('key1', '{{ ctx().value1_str }}'),
('direct_ctx_key', '<%% ctx(ctx_dict_key1) %>'),
# this is actually valid YAQL - dictionary keys do not have to be quoted
('ctx_dict1', '<%% ctx.get(ctx_dict_key1) %>'),
('ctx_dict1_sq', "<%% ctx.get('ctx_dict_key1_sq') %>"),
('ctx_dict1_dq', '<%% ctx.get("ctx_dict_key1_dq") %>'),
('ctx_dict1_or', "<%% ctx.get('ctx_dict_key1_or') or 'none' %>"),
('ctx_dict2', '<%% ctx.get(ctx_dict_key2).not_this_though %>'),
('ctx_dict3', "<%% ctx.get(ctx_dict_key3, with_bare_default_value) %>"),
('ctx_dict4', "<%% ctx.get(ctx_dict_key4, 'with default value [single quotes]') %>"),
('ctx_dict5', '<%% ctx.get(ctx_dict_key5, "with default value [double quotes]") %>'),
('ctx_dict6', '<%% ctx.get(ctx_dict_key6, {}).ignore_this_key %>'),
('bare_ctx_dict1', '<%% ctx().get(dict_key1) %>'),
('bare_ctx_dict2', '<%% ctx().get(dict_key2).not_this_though %>'),
('bare_ctx_dict3', "<%% ctx().get(dict_key3, with_default_value) %>"),
('bare_ctx_dict4', "<%% ctx().get(dict_key4, 'with default value [single quotes]') %>"),
('bare_ctx_dict5', '<%% ctx().get(dict_key5, "with default value [double quotes]") %>'),
('bare_ctx_dict6', '<%% ctx().get(dict_key6, {}).ignore_this_key %>'),
('list_<%% ctx().list_list_key2 %>', [
'a',
'<%% ctx().value2_list %>',
{
'inner_key_1': 'inner_value_1',
'inner_key_2': '<%% ctx().inner_value_2 %>',
'inner_<%% ctx().inner_key_3 %>': 'inner_value_3',
'inner_{{ ctx().inner_key_4 }}': '<%% ctx().list_key2 %>',
},
]),
('key3_int', 1),
('key4_bool_false', False),
('key5_bool_true', True),
('key6_null', None),
('key7_float', 1.0),
])
expected_output = set([
'inner_key_3',
'inner_key_4',
'inner_value_2',
'list_list_key2',
'list_key2',
'value1_str',
'value2_list',
'ctx_dict_key1',
'ctx_dict_key1_sq',
'ctx_dict_key1_dq',
'ctx_dict_key1_or',
'ctx_dict_key2',
'ctx_dict_key3',
'ctx_dict_key4',
'ctx_dict_key5',
'ctx_dict_key6',
'dict_key1',
'dict_key2',
'dict_key3',
'dict_key4',
'dict_key5',
'dict_key6',
])
actual_output = converter.extract_context_variables(output_block)
self.assertEqual(actual_output, expected_output)
def test_convert_task_transition_simple(self):
converter = workflows_base.WorkflowConverter()
transitions = ['a', 'b', 'c']
publish = OrderedMap([('key_plain', 'data'),
('key_expr', '{{ _.test }}')])
orquesta_expr = 'succeeded()'
expr_converter = jinja.JinjaExpressionConverter()
result = converter.convert_task_transition_simple(transitions,
publish,
orquesta_expr,
expr_converter)
expected = OrderedMap([
('when', '{{ succeeded() }}'),
('publish', [
{'key_plain': 'data'},
{'key_expr': '{{ ctx().test }}'}
]),
('do', ['a', 'b', 'c']),
])
self.assertEqual(result, expected)
def test_convert_task_transition_simple_yaql(self):
converter = workflows_base.WorkflowConverter()
transitions = ['a', 'b', 'c']
publish = OrderedMap([('key_plain', 'data'),
('key_expr', '{{ _.test }}')])
orquesta_expr = 'succeeded()'
expr_converter = yql.YaqlExpressionConverter()
result = converter.convert_task_transition_simple(transitions,
publish,
orquesta_expr,
expr_converter)
# note: only the orquesta_expr is converted using YAQL, the expressions
# in the rest are converted independently because they may each
# be a different type
expected = OrderedMap([
('when', '<% succeeded() %>'),
('publish', [
{'key_plain': 'data'},
{'key_expr': '{{ ctx().test }}'}
]),
('do', ['a', 'b', 'c']),
])
self.assertEqual(result, expected)
def test_convert_task_transition_simple_no_orquesta_expr(self):
converter = workflows_base.WorkflowConverter()
transitions = ['a', 'b', 'c']
publish = OrderedMap([('key_plain', 'data'),
('key_expr', '{{ _.test }}')])
orquesta_expr = None
expr_converter = jinja.JinjaExpressionConverter()
result = converter.convert_task_transition_simple(transitions,
publish,
orquesta_expr,
expr_converter)
expected = OrderedMap([
('publish', [
{'key_plain': 'data'},
{'key_expr': '{{ ctx().test }}'}
]),
('do', ['a', 'b', 'c']),
])
self.assertEqual(result, expected)
def test_convert_task_transition_simple_no_publish(self):
converter = workflows_base.WorkflowConverter()
transitions = ['a', 'b', 'c']
publish = None
orquesta_expr = 'succeeded()'
expr_converter = jinja.JinjaExpressionConverter()
result = converter.convert_task_transition_simple(transitions,
publish,
orquesta_expr,
expr_converter)
expected = OrderedMap([
('when', '{{ succeeded() }}'),
('do', ['a', 'b', 'c']),
])
self.assertEqual(result, expected)
def test_convert_task_transition_simple_no_transitions(self):
converter = workflows_base.WorkflowConverter()
transitions = None
publish = OrderedMap([('key_plain', 'data'),
('key_expr', '{{ _.test }}')])
orquesta_expr = 'succeeded()'
expr_converter = jinja.JinjaExpressionConverter()
result = converter.convert_task_transition_simple(transitions,
publish,
orquesta_expr,
expr_converter)
expected = OrderedMap([
('when', '{{ succeeded() }}'),
('publish', [
{'key_plain': 'data'},
{'key_expr': '{{ ctx().test }}'}
]),
])
self.assertEqual(result, expected)
def test_convert_task_transition_expr(self):
converter = workflows_base.WorkflowConverter()
expression_list = OrderedMap([('<% $.test %>', ['task1', 'task3']),
('{{ _.other }}', ['task2'])])
orquesta_expr = 'succeeded()'
result = converter.convert_task_transition_expr('task_name',
expression_list,
{},
orquesta_expr)
expected = [
OrderedMap([
('when', '<% succeeded() and (ctx().test) %>'),
('do', ['task1', 'task3']),
]),
OrderedMap([
('when', '{{ succeeded() and (ctx().other) }}'),
('do', ['task2']),
]),
]
self.assertEqual(result, expected)
def test_convert_task_transition_expr_no_orquesta_expr(self):
converter = workflows_base.WorkflowConverter()
expression_list = OrderedMap([('<% $.test %>', ['task1', 'task3']),
('{{ _.other }}', ['task2'])])
orquesta_expr = None
result = converter.convert_task_transition_expr('task_name',
expression_list,
{},
orquesta_expr)
expected = [
OrderedMap([
('when', '<% ctx().test %>'),
('do', ['task1', 'task3']),
]),
OrderedMap([
('when', '{{ ctx().other }}'),
('do', ['task2']),
]),
]
self.assertEqual(result, expected)
def test_default_task_transition_map(self):
converter = workflows_base.WorkflowConverter()
result = converter.default_task_transition_map()
self.assertEqual(result, OrderedMap([
('on-success', OrderedMap([
('publish', OrderedMap()),
('orquesta_expr', 'succeeded()'),
])),
('on-error', OrderedMap([
('publish', OrderedMap()),
('orquesta_expr', 'failed()'),
])),
('on-complete', OrderedMap([
('publish', OrderedMap()),
('orquesta_expr', None),
])),
]))
def test_convert_task_transitions(self):
converter = workflows_base.WorkflowConverter()
task_spec = OrderedMap([
('publish', OrderedMap([
('good_data', '{{ _.good }}'),
])),
('publish-on-error', OrderedMap([
('bad_data', '{{ _.bad }}'),
])),
('on-success', [
OrderedMap([('do_thing_a', '{{ _.x }}')]),
OrderedMap([('do_thing_b', '{{ _.x }}')])
]),
('on-error', [
OrderedMap([('do_thing_error', '{{ _.e }}')]),
]),
('on-complete', [
OrderedMap([('do_thing_sometimes', '{{ _.d }}')]),
'do_thing_always'
]),
])
expr_converter = jinja.JinjaExpressionConverter()
result = converter.convert_task_transitions("task_name", task_spec, expr_converter, set())
self.assertDictEqual(result, OrderedMap([
('next', [
OrderedMap([
('when', '{{ succeeded() and (ctx().x) }}'),
('publish', [
{'good_data': '{{ ctx().good }}'}
]),
('do', [
'do_thing_a',
'do_thing_b',
]),
]),
OrderedMap([
('when', '{{ failed() and (ctx().e) }}'),
('publish', [
{'bad_data': '{{ ctx().bad }}'}
]),
('do', [
'do_thing_error',
]),
]),
OrderedMap([
('publish', [
{'good_data': '{{ ctx().good }}'},
{'bad_data': '{{ ctx().bad }}'},
]),
('do', [
'do_thing_always',
]),
]),
OrderedMap([
('when', '{{ ctx().d }}'),
('publish', [
{'good_data': '{{ ctx().good }}'},
{'bad_data': '{{ ctx().bad }}'},
]),
('do', [
'do_thing_sometimes',
]),
]),
]),
]))
def test_convert_task_transitions_empty(self):
converter = workflows_base.WorkflowConverter()
task_spec = OrderedMap([])
expr_converter = jinja.JinjaExpressionConverter()
result = converter.convert_task_transitions("task_name", task_spec, expr_converter, set())
self.assertEqual(result, OrderedMap([]))
def test_convert_task_transitions_common_publish_keys_same_values(self):
converter = workflows_base.WorkflowConverter()
task_spec = OrderedMap([
('publish', OrderedMap([
('good_data', '{{ _.good }}'),
('common_data_1', '{{ _.common_1 }}'),
('common_data_2', '{{ _.common_2 }}'),
])),
('publish-on-error', OrderedMap([
('bad_data', '{{ _.bad }}'),
('common_data_1', '{{ _.common_1 }}'),
('common_data_2', '{{ _.common_2 }}'),
])),
('on-complete', [
'do_thing_always'
]),
])
expr_converter = jinja.JinjaExpressionConverter()
result = converter.convert_task_transitions("task_name", task_spec, expr_converter, set())
self.assertDictEqual(result, OrderedMap([
('next', [
OrderedMap([
('publish', [
{'good_data': '{{ ctx().good }}'},
{'common_data_1': '{{ ctx().common_1 }}'},
{'common_data_2': '{{ ctx().common_2 }}'},
{'bad_data': '{{ ctx().bad }}'},
]),
('do', [
'do_thing_always',
]),
]),
]),
]))
def test_convert_task_transitions_common_publish_keys_different_values(self):
converter = workflows_base.WorkflowConverter()
task_spec = OrderedMap([
('publish', OrderedMap([
('good_data', '{{ _.good }}'),
('common_key_1', '{{ _.common_data }}'),
('common_key_2', '{{ _.different_data_1_1 }}'),
('common_key_3', '{{ _.different_data_1_2 }}'),
])),
('publish-on-error', OrderedMap([
('bad_data', '{{ _.bad }}'),
('common_key_1', '{{ _.common_data }}'),
('common_key_2', '{{ _.different_data_2_1 }}'),
('common_key_3', '{{ _.different_data_2_2 }}'),
])),
('on-complete', [
OrderedMap([('do_thing_sometimes', '{{ _.d }}')]),
'do_thing_always'
]),
])
expr_converter = jinja.JinjaExpressionConverter()
with self.assertRaises(NotImplementedError) as ctx_m:
converter.convert_task_transitions("tsk_name", task_spec, expr_converter, set())
rgx = re.compile(r"Task 'tsk_name' contains one or more keys "
r"\((?:common_key_2, common_key_3|common_key_3, common_key_2)\) "
r"in both publish and publish-on-error dictionaries that have different "
r"values\. Please either remove the common keys, or ensure that the "
r"values of any common keys are the same\.")
self.assertRegex(str(ctx_m.exception), rgx)
def test_convert_with_items(self):
wi = {
'with-items': 'b in <% [3, 4, 5] %>',
}
converter = workflows_base.WorkflowConverter()
actual = converter.convert_with_items(wi, yql.YaqlExpressionConverter)
# This should NOT have a concurrency key
expected = {
'items': 'b in <% [3, 4, 5] %>',
}
self.assertEqual(expected, actual)
def test_convert_with_items_concurrency_integer(self):
wi = {
'with-items': 'b in <% [3, 4, 5] %>',
'concurrency': 2,
}
converter = workflows_base.WorkflowConverter()
actual = converter.convert_with_items(wi, yql.YaqlExpressionConverter)
# This must have a concurrency key
expected = {
'items': 'b in <% [3, 4, 5] %>',
'concurrency': 2,
}
self.assertEqual(expected, actual)
def test_convert_with_items_concurrency_string(self):
wi = {
'with-items': 'b in <% [3, 4, 5] %>',
'concurrency': '2',
}
converter = workflows_base.WorkflowConverter()
actual = converter.convert_with_items(wi, yql.YaqlExpressionConverter)
# This must have a concurrency key
expected = {
'items': 'b in <% [3, 4, 5] %>',
'concurrency': | |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['UserCapabilitiesManagementArgs', 'UserCapabilitiesManagement']
@pulumi.input_type
class UserCapabilitiesManagementArgs:
def __init__(__self__, *,
user_id: pulumi.Input[str],
can_use_api_keys: Optional[pulumi.Input[bool]] = None,
can_use_auth_tokens: Optional[pulumi.Input[bool]] = None,
can_use_console_password: Optional[pulumi.Input[bool]] = None,
can_use_customer_secret_keys: Optional[pulumi.Input[bool]] = None,
can_use_smtp_credentials: Optional[pulumi.Input[bool]] = None):
"""
The set of arguments for constructing a UserCapabilitiesManagement resource.
:param pulumi.Input[str] user_id: The OCID of the user.
:param pulumi.Input[bool] can_use_api_keys: (Updatable) Indicates if the user can use API keys.
:param pulumi.Input[bool] can_use_auth_tokens: (Updatable) Indicates if the user can use SWIFT passwords / auth tokens.
:param pulumi.Input[bool] can_use_console_password: (Updatable) Indicates if the user can log in to the console.
:param pulumi.Input[bool] can_use_customer_secret_keys: (Updatable) Indicates if the user can use SigV4 symmetric keys.
:param pulumi.Input[bool] can_use_smtp_credentials: (Updatable) Indicates if the user can use SMTP passwords.
"""
pulumi.set(__self__, "user_id", user_id)
if can_use_api_keys is not None:
pulumi.set(__self__, "can_use_api_keys", can_use_api_keys)
if can_use_auth_tokens is not None:
pulumi.set(__self__, "can_use_auth_tokens", can_use_auth_tokens)
if can_use_console_password is not None:
pulumi.set(__self__, "can_use_console_password", can_use_console_password)
if can_use_customer_secret_keys is not None:
pulumi.set(__self__, "can_use_customer_secret_keys", can_use_customer_secret_keys)
if can_use_smtp_credentials is not None:
pulumi.set(__self__, "can_use_smtp_credentials", can_use_smtp_credentials)
@property
@pulumi.getter(name="userId")
def user_id(self) -> pulumi.Input[str]:
"""
The OCID of the user.
"""
return pulumi.get(self, "user_id")
@user_id.setter
def user_id(self, value: pulumi.Input[str]):
pulumi.set(self, "user_id", value)
@property
@pulumi.getter(name="canUseApiKeys")
def can_use_api_keys(self) -> Optional[pulumi.Input[bool]]:
"""
(Updatable) Indicates if the user can use API keys.
"""
return pulumi.get(self, "can_use_api_keys")
@can_use_api_keys.setter
def can_use_api_keys(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "can_use_api_keys", value)
@property
@pulumi.getter(name="canUseAuthTokens")
def can_use_auth_tokens(self) -> Optional[pulumi.Input[bool]]:
"""
(Updatable) Indicates if the user can use SWIFT passwords / auth tokens.
"""
return pulumi.get(self, "can_use_auth_tokens")
@can_use_auth_tokens.setter
def can_use_auth_tokens(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "can_use_auth_tokens", value)
@property
@pulumi.getter(name="canUseConsolePassword")
def can_use_console_password(self) -> Optional[pulumi.Input[bool]]:
"""
(Updatable) Indicates if the user can log in to the console.
"""
return pulumi.get(self, "can_use_console_password")
@can_use_console_password.setter
def can_use_console_password(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "can_use_console_password", value)
@property
@pulumi.getter(name="canUseCustomerSecretKeys")
def can_use_customer_secret_keys(self) -> Optional[pulumi.Input[bool]]:
"""
(Updatable) Indicates if the user can use SigV4 symmetric keys.
"""
return pulumi.get(self, "can_use_customer_secret_keys")
@can_use_customer_secret_keys.setter
def can_use_customer_secret_keys(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "can_use_customer_secret_keys", value)
@property
@pulumi.getter(name="canUseSmtpCredentials")
def can_use_smtp_credentials(self) -> Optional[pulumi.Input[bool]]:
"""
(Updatable) Indicates if the user can use SMTP passwords.
"""
return pulumi.get(self, "can_use_smtp_credentials")
@can_use_smtp_credentials.setter
def can_use_smtp_credentials(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "can_use_smtp_credentials", value)
@pulumi.input_type
class _UserCapabilitiesManagementState:
def __init__(__self__, *,
can_use_api_keys: Optional[pulumi.Input[bool]] = None,
can_use_auth_tokens: Optional[pulumi.Input[bool]] = None,
can_use_console_password: Optional[pulumi.Input[bool]] = None,
can_use_customer_secret_keys: Optional[pulumi.Input[bool]] = None,
can_use_smtp_credentials: Optional[pulumi.Input[bool]] = None,
user_id: Optional[pulumi.Input[str]] = None):
"""
Input properties used for looking up and filtering UserCapabilitiesManagement resources.
:param pulumi.Input[bool] can_use_api_keys: (Updatable) Indicates if the user can use API keys.
:param pulumi.Input[bool] can_use_auth_tokens: (Updatable) Indicates if the user can use SWIFT passwords / auth tokens.
:param pulumi.Input[bool] can_use_console_password: (Updatable) Indicates if the user can log in to the console.
:param pulumi.Input[bool] can_use_customer_secret_keys: (Updatable) Indicates if the user can use SigV4 symmetric keys.
:param pulumi.Input[bool] can_use_smtp_credentials: (Updatable) Indicates if the user can use SMTP passwords.
:param pulumi.Input[str] user_id: The OCID of the user.
"""
if can_use_api_keys is not None:
pulumi.set(__self__, "can_use_api_keys", can_use_api_keys)
if can_use_auth_tokens is not None:
pulumi.set(__self__, "can_use_auth_tokens", can_use_auth_tokens)
if can_use_console_password is not None:
pulumi.set(__self__, "can_use_console_password", can_use_console_password)
if can_use_customer_secret_keys is not None:
pulumi.set(__self__, "can_use_customer_secret_keys", can_use_customer_secret_keys)
if can_use_smtp_credentials is not None:
pulumi.set(__self__, "can_use_smtp_credentials", can_use_smtp_credentials)
if user_id is not None:
pulumi.set(__self__, "user_id", user_id)
@property
@pulumi.getter(name="canUseApiKeys")
def can_use_api_keys(self) -> Optional[pulumi.Input[bool]]:
"""
(Updatable) Indicates if the user can use API keys.
"""
return pulumi.get(self, "can_use_api_keys")
@can_use_api_keys.setter
def can_use_api_keys(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "can_use_api_keys", value)
@property
@pulumi.getter(name="canUseAuthTokens")
def can_use_auth_tokens(self) -> Optional[pulumi.Input[bool]]:
"""
(Updatable) Indicates if the user can use SWIFT passwords / auth tokens.
"""
return pulumi.get(self, "can_use_auth_tokens")
@can_use_auth_tokens.setter
def can_use_auth_tokens(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "can_use_auth_tokens", value)
@property
@pulumi.getter(name="canUseConsolePassword")
def can_use_console_password(self) -> Optional[pulumi.Input[bool]]:
"""
(Updatable) Indicates if the user can log in to the console.
"""
return pulumi.get(self, "can_use_console_password")
@can_use_console_password.setter
def can_use_console_password(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "can_use_console_password", value)
@property
@pulumi.getter(name="canUseCustomerSecretKeys")
def can_use_customer_secret_keys(self) -> Optional[pulumi.Input[bool]]:
"""
(Updatable) Indicates if the user can use SigV4 symmetric keys.
"""
return pulumi.get(self, "can_use_customer_secret_keys")
@can_use_customer_secret_keys.setter
def can_use_customer_secret_keys(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "can_use_customer_secret_keys", value)
@property
@pulumi.getter(name="canUseSmtpCredentials")
def can_use_smtp_credentials(self) -> Optional[pulumi.Input[bool]]:
"""
(Updatable) Indicates if the user can use SMTP passwords.
"""
return pulumi.get(self, "can_use_smtp_credentials")
@can_use_smtp_credentials.setter
def can_use_smtp_credentials(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "can_use_smtp_credentials", value)
@property
@pulumi.getter(name="userId")
def user_id(self) -> Optional[pulumi.Input[str]]:
"""
The OCID of the user.
"""
return pulumi.get(self, "user_id")
@user_id.setter
def user_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "user_id", value)
class UserCapabilitiesManagement(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
can_use_api_keys: Optional[pulumi.Input[bool]] = None,
can_use_auth_tokens: Optional[pulumi.Input[bool]] = None,
can_use_console_password: Optional[pulumi.Input[bool]] = None,
can_use_customer_secret_keys: Optional[pulumi.Input[bool]] = None,
can_use_smtp_credentials: Optional[pulumi.Input[bool]] = None,
user_id: Optional[pulumi.Input[str]] = None,
__props__=None):
"""
This resource provides the User Capabilities Management resource in Oracle Cloud Infrastructure Identity service.
Manages the capabilities of the specified user.
**Important:** Deleting the User Capabilities Management leaves the User resource in its existing state (rather than returning to its defaults)
## Example Usage
```python
import pulumi
import pulumi_oci as oci
test_user_capabilities_management = oci.identity.UserCapabilitiesManagement("testUserCapabilitiesManagement",
user_id=oci_identity_user["user1"]["id"],
can_use_api_keys=True,
can_use_auth_tokens=True,
can_use_console_password=False,
can_use_customer_secret_keys=True,
can_use_smtp_credentials=True)
```
## Import
Users can be imported using the `id`, e.g.
```sh
$ pulumi import oci:identity/userCapabilitiesManagement:UserCapabilitiesManagement test_user_capabilities_management "capabilities/{userId}"
```
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[bool] can_use_api_keys: (Updatable) Indicates if the user can use API keys.
:param pulumi.Input[bool] can_use_auth_tokens: (Updatable) Indicates if the user can use SWIFT passwords / auth tokens.
:param pulumi.Input[bool] can_use_console_password: (Updatable) Indicates if the user can log in to the console.
:param pulumi.Input[bool] can_use_customer_secret_keys: (Updatable) Indicates if the user can use SigV4 symmetric keys.
:param pulumi.Input[bool] can_use_smtp_credentials: (Updatable) Indicates if the user can use SMTP passwords.
:param pulumi.Input[str] user_id: The OCID of the user.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: UserCapabilitiesManagementArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
This resource provides the User Capabilities Management resource in Oracle Cloud Infrastructure Identity service.
Manages the capabilities of the specified user.
**Important:** Deleting the User Capabilities Management leaves the User resource in its existing state (rather than returning to its defaults)
## Example Usage
```python
import pulumi
import pulumi_oci as oci
test_user_capabilities_management = oci.identity.UserCapabilitiesManagement("testUserCapabilitiesManagement",
user_id=oci_identity_user["user1"]["id"],
can_use_api_keys=True,
can_use_auth_tokens=True,
can_use_console_password=False,
can_use_customer_secret_keys=True,
can_use_smtp_credentials=True)
```
## Import
Users can be imported using the `id`, e.g.
```sh
$ pulumi import oci:identity/userCapabilitiesManagement:UserCapabilitiesManagement test_user_capabilities_management "capabilities/{userId}"
```
:param str resource_name: The name of the resource.
:param UserCapabilitiesManagementArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(UserCapabilitiesManagementArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
can_use_api_keys: Optional[pulumi.Input[bool]] = None,
can_use_auth_tokens: Optional[pulumi.Input[bool]] = None,
can_use_console_password: Optional[pulumi.Input[bool]] = None,
can_use_customer_secret_keys: Optional[pulumi.Input[bool]] = None,
can_use_smtp_credentials: Optional[pulumi.Input[bool]] = None,
user_id: Optional[pulumi.Input[str]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = UserCapabilitiesManagementArgs.__new__(UserCapabilitiesManagementArgs)
__props__.__dict__["can_use_api_keys"] = can_use_api_keys
__props__.__dict__["can_use_auth_tokens"] = can_use_auth_tokens
__props__.__dict__["can_use_console_password"] = can_use_console_password
__props__.__dict__["can_use_customer_secret_keys"] = can_use_customer_secret_keys
__props__.__dict__["can_use_smtp_credentials"] = can_use_smtp_credentials
if user_id is None and not opts.urn:
raise TypeError("Missing required property 'user_id'")
__props__.__dict__["user_id"] = user_id
super(UserCapabilitiesManagement, __self__).__init__(
'oci:identity/userCapabilitiesManagement:UserCapabilitiesManagement',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
can_use_api_keys: Optional[pulumi.Input[bool]] = None,
can_use_auth_tokens: Optional[pulumi.Input[bool]] = None,
can_use_console_password: Optional[pulumi.Input[bool]] = None,
can_use_customer_secret_keys: Optional[pulumi.Input[bool]] = None,
can_use_smtp_credentials: Optional[pulumi.Input[bool]] = None,
user_id: Optional[pulumi.Input[str]] = None) -> 'UserCapabilitiesManagement':
"""
Get an existing UserCapabilitiesManagement resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[bool] can_use_api_keys: (Updatable) Indicates if the user can use API keys.
| |
# Copyright 2014-2019 The ODL contributors
#
# This file is part of ODL.
#
# 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 https://mozilla.org/MPL/2.0/.
"""Default operators defined on any `ProductSpace`."""
from __future__ import print_function, division, absolute_import
from numbers import Integral
import numpy as np
from odl.operator.operator import Operator
from odl.operator.default_ops import ZeroOperator
from odl.space import ProductSpace
__all__ = ('ProductSpaceOperator',
'ComponentProjection', 'ComponentProjectionAdjoint',
'BroadcastOperator', 'ReductionOperator', 'DiagonalOperator')
class ProductSpaceOperator(Operator):
r"""A "matrix of operators" on product spaces.
For example a matrix of operators can act on a vector by
``ProductSpaceOperator([[A, B], [C, D]])([x, y]) =
[A(x) + B(y), C(x) + D(y)]``
Notes
-----
This is intended for the case where an operator can be decomposed
as a linear combination of "sub-operators", e.g.
.. math::
\left(
\begin{array}{ccc}
A & B & 0 \\
0 & C & 0 \\
0 & 0 & D
\end{array}\right)
\left(
\begin{array}{c}
x \\
y \\
z
\end{array}\right)
=
\left(
\begin{array}{c}
A(x) + B(y) \\
C(y) \\
D(z)
\end{array}\right)
Mathematically, a `ProductSpaceOperator` is an operator
.. math::
\mathcal{A}: \mathcal{X} \to \mathcal{Y}
between product spaces
:math:`\mathcal{X}=\mathcal{X}_1 \times\dots\times \mathcal{X}_m`
and
:math:`\mathcal{Y}=\mathcal{Y}_1 \times\dots\times \mathcal{Y}_n`
which can be written in the form
.. math::
\mathcal{A} = (\mathcal{A}_{ij})_{i,j}, \quad
i = 1, \dots, n, \ j = 1, \dots, m
with *component operators*
:math:`\mathcal{A}_{ij}: \mathcal{X}_j \to \mathcal{Y}_i`.
Its action on a vector :math:`x = (x_1, \dots, x_m)` is defined as
the matrix multiplication
.. math::
[\mathcal{A}(x)]_i = \sum_{j=1}^m \mathcal{A}_{ij}(x_j).
See Also
--------
BroadcastOperator : Case when a single argument is used by several ops.
ReductionOperator : Calculates sum of operator results.
DiagonalOperator : Case where the 'matrix' is diagonal.
"""
def __init__(self, operators, domain=None, range=None):
"""Initialize a new instance.
Parameters
----------
operators : `array-like`
An array of `Operator`'s, must be 2-dimensional.
domain : `ProductSpace`, optional
Domain of the operator. If not provided, it is tried to be
inferred from the operators. This requires each **column**
to contain at least one operator.
range : `ProductSpace`, optional
Range of the operator. If not provided, it is tried to be
inferred from the operators. This requires each **row**
to contain at least one operator.
Examples
--------
>>> r3 = odl.rn(3)
>>> pspace = odl.ProductSpace(r3, r3)
>>> I = odl.IdentityOperator(r3)
>>> x = pspace.element([[1, 2, 3],
... [4, 5, 6]])
Create an operator that sums two inputs:
>>> prod_op = odl.ProductSpaceOperator([[I, I]])
>>> prod_op(x)
ProductSpace(rn(3), 1).element([
[ 5., 7., 9.]
])
Diagonal operator -- 0 or ``None`` means ignore, or the implicit
zero operator:
>>> prod_op = odl.ProductSpaceOperator([[I, 0],
... [0, I]])
>>> prod_op(x)
ProductSpace(rn(3), 2).element([
[ 1., 2., 3.],
[ 4., 5., 6.]
])
If a column is empty, the operator domain must be specified. The
same holds for an empty row and the range of the operator:
>>> prod_op = odl.ProductSpaceOperator([[I, 0],
... [I, 0]], domain=r3 ** 2)
>>> prod_op(x)
ProductSpace(rn(3), 2).element([
[ 1., 2., 3.],
[ 1., 2., 3.]
])
>>> prod_op = odl.ProductSpaceOperator([[I, I],
... [0, 0]], range=r3 ** 2)
>>> prod_op(x)
ProductSpace(rn(3), 2).element([
[ 5., 7., 9.],
[ 0., 0., 0.]
])
"""
# Lazy import to improve `import odl` time
import scipy.sparse
# Validate input data
if domain is not None:
if not isinstance(domain, ProductSpace):
raise TypeError('`domain` {!r} not a ProductSpace instance'
''.format(domain))
if domain.is_weighted:
raise NotImplementedError('weighted spaces not supported')
if range is not None:
if not isinstance(range, ProductSpace):
raise TypeError('`range` {!r} not a ProductSpace instance'
''.format(range))
if range.is_weighted:
raise NotImplementedError('weighted spaces not supported')
if isinstance(operators, scipy.sparse.spmatrix):
if not all(isinstance(op, Operator) for op in operators.data):
raise ValueError('sparse matrix `operator` contains non-'
'`Operator` entries')
self.__ops = operators
else:
self.__ops = self._convert_to_spmatrix(operators)
# Set domain and range (or verify if given)
if domain is None:
domains = [None] * self.__ops.shape[1]
else:
domains = domain
if range is None:
ranges = [None] * self.__ops.shape[0]
else:
ranges = range
for row, col, op in zip(self.__ops.row, self.__ops.col,
self.__ops.data):
if domains[col] is None:
domains[col] = op.domain
elif domains[col] != op.domain:
raise ValueError('column {}, has inconsistent domains, '
'got {} and {}'
''.format(col, domains[col], op.domain))
if ranges[row] is None:
ranges[row] = op.range
elif ranges[row] != op.range:
raise ValueError('row {}, has inconsistent ranges, '
'got {} and {}'
''.format(row, ranges[row], op.range))
if domain is None:
for col, sub_domain in enumerate(domains):
if sub_domain is None:
raise ValueError('col {} empty, unable to determine '
'domain, please use `domain` parameter'
''.format(col))
domain = ProductSpace(*domains)
if range is None:
for row, sub_range in enumerate(ranges):
if sub_range is None:
raise ValueError('row {} empty, unable to determine '
'range, please use `range` parameter'
''.format(row))
range = ProductSpace(*ranges)
# Set linearity
linear = all(op.is_linear for op in self.__ops.data)
super(ProductSpaceOperator, self).__init__(
domain=domain, range=range, linear=linear)
@staticmethod
def _convert_to_spmatrix(operators):
"""Convert an array-like object of operators to a sparse matrix."""
# Lazy import to improve `import odl` time
import scipy.sparse
# Convert ops to sparse representation. This is not trivial because
# operators can be indexable themselves and give the wrong impression
# of an extra dimension. So we have to infer the shape manually
# first and extract the indices of nonzero positions.
nrows = len(operators)
ncols = None
irow, icol, data = [], [], []
for i, row in enumerate(operators):
try:
iter(row)
except TypeError:
raise ValueError(
'`operators` must be a matrix of `Operator` objects, `0` '
'or `None`, got {!r} (row {} = {!r} is not iterable)'
''.format(operators, i, row))
if isinstance(row, Operator):
raise ValueError(
'`operators` must be a matrix of `Operator` objects, `0` '
'or `None`, but row {} is an `Operator` {!r}'
''.format(i, row))
if ncols is None:
ncols = len(row)
elif len(row) != ncols:
raise ValueError(
'all rows in `operators` must have the same length, but '
'length {} of row {} differs from previous common length '
'{}'.format(len(row), i, ncols))
for j, col in enumerate(row):
if col is None or col is 0:
pass
elif isinstance(col, Operator):
irow.append(i)
icol.append(j)
data.append(col)
else:
raise ValueError(
'`operators` must be a matrix of `Operator` objects, '
'`0` or `None`, got entry {!r} at ({}, {})'
''.format(col, i, j))
# Create object array explicitly, threby avoiding erroneous conversion
# in `coo_matrix.__init__`
data_arr = np.empty(len(data), dtype=object)
data_arr[:] = data
return scipy.sparse.coo_matrix((data_arr, (irow, icol)),
shape=(nrows, ncols))
@property
def ops(self):
"""The sparse operator matrix representing this operator."""
return self.__ops
def _call(self, x, out=None):
"""Call the operators on the parts of ``x``."""
# TODO: add optimization in case an operator appears repeatedly in a
# row
if out is None:
out = self.range.zero()
for i, j, op in zip(self.ops.row, self.ops.col, self.ops.data):
out[i] += op(x[j])
else:
has_evaluated_row = np.zeros(len(self.range), dtype=bool)
for i, j, op in zip(self.ops.row, self.ops.col, self.ops.data):
if not has_evaluated_row[i]:
op(x[j], out=out[i])
else:
# TODO: optimize
out[i] += op(x[j])
has_evaluated_row[i] = True
for i, evaluated in enumerate(has_evaluated_row):
if not evaluated:
out[i].set_zero()
return out
def derivative(self, x):
"""Derivative of the product space operator.
Parameters
----------
x : `domain` element
The point to take the derivative in
Returns
-------
adjoint : linear`ProductSpaceOperator`
The derivative
Examples
--------
>>> r3 = odl.rn(3)
>>> pspace = odl.ProductSpace(r3, r3)
>>> I = odl.IdentityOperator(r3)
>>> x = pspace.element([[1, 2, 3], [4, 5, 6]])
Example with linear operator (derivative is itself)
>>> prod_op = ProductSpaceOperator([[0, I], [0, 0]],
... domain=pspace, range=pspace)
>>> prod_op(x)
ProductSpace(rn(3), 2).element([
[ 4., 5., 6.],
[ 0., 0., 0.]
])
>>> prod_op.derivative(x)(x)
ProductSpace(rn(3), 2).element([
[ 4., 5., 6.],
[ 0., 0., 0.]
])
Example with affine operator
>>> residual_op = I - r3.element([1, 1, 1])
>>> op = ProductSpaceOperator([[0, residual_op], [0, 0]],
... domain=pspace, range=pspace)
Calling operator gives offset by [1, 1, 1]
>>> op(x)
ProductSpace(rn(3), 2).element([
[ 3., 4., 5.],
[ 0., 0., 0.]
])
Derivative of affine operator does not have this offset
>>> op.derivative(x)(x)
ProductSpace(rn(3), 2).element([
[ 4., 5., 6.],
[ 0., 0., 0.]
])
"""
# Lazy import to improve `import odl` | |
<reponame>ivanbgd/Self-Balancing-Binary-Search-Trees
"""
This is an application of Binary Search Trees.
It's used for storing an array in a tree (or two trees), and it was invented to speed things up.
Uses 1-based indexing.
By using AVL trees like here (self balancing trees in general), we keep the maximum height of a tree at O(log n), so all operations on the array take at most O(log n) time.
Non-balancing BST has O(n) time complexity in the worst case, like a regular array (list).
"""
import AVL_Rec as AVL
class ArrayNode(AVL.AVLNode):
def __init__(self, key, height, color):
assert key and height and (color == 'b' or color == 'w'), "Node must be added with key and height and color ('b' or 'w')!"
self.color = color
return super(ArrayNode, self).__init__(key)
def setColor(self, color):
assert color == 'b' or color == 'w', "Color can be either 'b' or 'w'!"
self.color = color
def getColor(self):
return self.color
def printNode(self):
print("Key: {}, Parent: {}, Left child: {}, Right child: {}, Size: {}, Height: {}, Color: {}".format(self.key, self.parent, self.left, self.right, self.size, self.height, repr(self.color)))
def __str__(self):
return str((self.key, self.color))
def __repr__(self):
"""This can be used as:
print(repr(tree.find(key, root)))
But, it's also very useful for debugging, because debugger will show us the key of the node without the need for expanding the node.
Of course, we can add some other pieces of information, too.
We can return "str(self.key)" and concatenate other string to it, or we can use the form below. Anyhow, we must return a string.
"""
return "Key: {}, Size: {}, Height: {}, Color: {}".format(self.key, self.size, self.height, repr(self.color))
class ArrayAVL(AVL.AVLTree):
def __init__(self, root):
"""Expects a root node object as input."""
return super(ArrayAVL, self).__init__(root)
def __str__(self):
return str(self.inOrder(self.root))
def inOrderRec(self, current):
if current.getLeftChild():
self.inOrderRec(current.getLeftChild())
self.result.append((current.getKey(), current.getColor()))
if current.getRightChild():
self.inOrderRec(current.getRightChild())
def insert(self, key, color, root):
"""Inputs: key is a numerical value; color is 'b' or 'w'; root is the root node object.
Adds ArrayNode with key key and color color to the ArrayAVL tree.
Returns nothing.
Node is always inserted as a leaf, so its size and height are 1.
I had to override method insert() from BinarySearchTree() class because it creates a Node object which doesn't contain the color field.
"""
parent = self.find(key, root)
node = ArrayNode(key, 1, color)
node.setParent(parent)
if key < parent.getKey():
parent.setLeftChild(node)
else:
parent.setRightChild(node)
while parent:
parent.incrementSize()
parent = parent.getParent()
def AVLInsert(self, key, color, root):
"""Inputs: key is a numerical value; color is 'b' or 'w'; root is the root node object.
Adds AVL node with key key and color color to the tree. Returns nothing.
"""
self.insert(key, color, root)
node = self.find(key, root)
self.rebalance(node)
class Array(object):
"""
Array object of elements with color 'b' or 'w'.
At the time of creation, all elements have color 'w'.
"""
def __init__(self, n):
"""
Creates an Array object of n elements with color 'w'.
"""
self.size = n
self.T1, self.T2 = self.newArray(self.size)
def __str__(self):
return str(self.T1)
def getSize(self):
return self.size
def decrementSize(self):
assert self.size > 1, "Size must be at least 1!"
self.size -= 1
def incrementSize(self):
self.size += 1
def oppositeColor(self, color):
assert color == 'b' or color == 'w', "Color can be either 'b' or 'w'!"
if color == 'b':
return 'w'
else:
return 'b'
def push(self, color):
"""
Pushes a new element with color 'color' to the end of the array.
Returns nothing.
"""
self.incrementSize()
self.T1.AVLInsert(self.size, color, self.T1.getRoot())
self.T2.AVLInsert(self.size, self.oppositeColor(color), self.T2.getRoot())
def pop(self):
"""
Pops an element from the end of the array and returns it.
"""
el1 = self.T1.find(self.size, self.T1.getRoot())
self.T1.AVLDelete(el1)
el2 = self.T2.find(self.size, self.T2.getRoot())
self.T2.AVLDelete(el2)
self.decrementSize()
return el1
def newArray(self, n):
"""
Creates two ArrayBST trees, T1 and T2, with keys [1, n].
All nodes in T1 have color 'w' (white), and all nodes in T2 have color 'b' (black).
Returns T1, T2.
"""
T1 = ArrayAVL(ArrayNode(1, 1, 'w'))
for i in range(2, n + 1):
T1.AVLInsert(i, 'w', T1.getRoot())
T2 = ArrayAVL(ArrayNode(1, 1, 'b'))
for i in range(2, n + 1):
T2.AVLInsert(i, 'b', T2.getRoot())
return T1, T2
def getElement(self, m):
"""
Returns color ('b' or 'w') of the m-th element in T1 (the Array).
m has to be >= 1 and <= size.
"""
assert 1 <= m <= self.size, "m has to be >= 1 and <= size!"
el = self.T1.find(m, self.T1.getRoot())
return el
def setColor(self, m, color):
"""
Sets color ('b' or 'w') of the m-th element in T1 (the Array), and the opposite color of the m-th element in T2.
m has to be >= 1 and <= size.
Returns nothing.
"""
assert 1 <= m <= self.size, "m has to be >= 1 and <= size!"
el1 = self.T1.find(m, self.T1.getRoot())
el2 = self.T2.find(m, self.T2.getRoot())
el1.setColor(color)
el2.setColor(self.oppositeColor(color))
def getColor(self, m):
"""
Returns color ('b' or 'w') of the m-th element in T1 (the Array).
m has to be >= 1 and <= size.
"""
assert 1 <= m <= self.size, "m has to be >= 1 and <= size!"
el = self.T1.find(m, self.T1.getRoot())
return repr(el.getColor())
def toggle(self, x):
"""
Toggles color of the element with index x.
x has to be >= 1 and <= size.
Returns nothing.
"""
assert 1 <= x <= self.size, "x has to be >= 1 and <= size!"
el1 = self.T1.find(x, self.T1.getRoot())
el2 = self.T2.find(x, self.T2.getRoot())
color = el1.getColor()
el1.setColor(self.oppositeColor(color))
el2.setColor(color)
def flip(self, x):
"""
Flips color of all elements with index >= x.
x has to be >= 1 and <= size.
Returns nothing.
"""
assert 1 <= x <= self.size, "x has to be >= 1 and <= size!"
x -= 1
L1, R1 = ArrayAVLSplit(self.T1, self.T1.getRoot(), x)
L2, R2 = ArrayAVLSplit(self.T2, self.T2.getRoot(), x)
L1Tree = ArrayAVL(L1)
L2Tree = ArrayAVL(L2)
R1Tree = ArrayAVL(R1)
R2Tree = ArrayAVL(R2)
self.T1 = ArrayAVL(ArrayAVLMerge(L1Tree, L1, R2Tree, R2))
self.T2 = ArrayAVL(ArrayAVLMerge(L2Tree, L2, R1Tree, R1))
del L1Tree, L2Tree, R1Tree, R2Tree
def ArrayAVLMerge(tree1, R1, tree2, R2):
"""Merges two ArrayAVL trees, tree1 and tree2, with roots R1 and R2, using the largest element in R1's tree as the node for merging, into a new ArrayAVL tree.
CONSTRAINTS: All keys in R1's tree must be smaller than all keys in tree rooted at R2.
INPUTS are two trees (tree1 and tree2) and their roots (R1 and R2): tree1, R1, tree2, R2.
OUTPUT (the return value of this function) is root of the new tree, with all the elements of both trees.
USAGE: Since this function actually returns a node, and not a tree, we should create an ArrayAVL tree rooted at the return value of this function. Then, we can delete tree1 and tree2 to free memory up.
"""
if not R1:
return R2
if not R2:
return R1
T = tree1.find(float("inf"), R1)
T.setHeight(1)
R1 = tree1.AVLDelete(T) # we have to update R1, in case it was the largest key in tree1 when it got deleted - in case we are deleting the root
if T == R1: # this means that T is the only node in tree1, i.e., tree1 has only that one node, which we don't delete, but we're not going to duplicate it now, either
tree2.AVLInsert(R1.getKey(), R1.getColor(), R2)
return R2
root = AVL.AVLMergeWithRoot(tree1, R1, tree2, R2, T)
return root
def _AVLSplitRec(tree, R, x):
"""
Splits AVL tree into two trees.
Input: An AVL tree; its root R; key x.
Output: Roots of two AVL trees, one with elements <= x, the other with elements > x.
Usage: User should set parents of both trees' roots to None after creating the two trees rooted at those two roots, and this should be done in two separate try-except blocks,
because a tree might be empty. Usage example: "try: tree1/2.getRoot().setParent(None) except: pass". Of course, this can alternatively be achieved by using two "if" clauses.
Also, user can delete node with key x from the left tree (tree1) after creating the trees, and AFTER fixing the parents, in case they want to remove x from | |
>>> thread = api.stop_run_with_http_info(owner, entity, uuid, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str owner: Owner of the namespace (required)
:param str entity: Entity: project name, hub name, registry name, ... (required)
:param str uuid: Uuid identifier of the sub-entity (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'owner',
'entity',
'uuid'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method stop_run" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'owner' is set
if self.api_client.client_side_validation and ('owner' not in local_var_params or # noqa: E501
local_var_params['owner'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `owner` when calling `stop_run`") # noqa: E501
# verify the required parameter 'entity' is set
if self.api_client.client_side_validation and ('entity' not in local_var_params or # noqa: E501
local_var_params['entity'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `entity` when calling `stop_run`") # noqa: E501
# verify the required parameter 'uuid' is set
if self.api_client.client_side_validation and ('uuid' not in local_var_params or # noqa: E501
local_var_params['uuid'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `uuid` when calling `stop_run`") # noqa: E501
collection_formats = {}
path_params = {}
if 'owner' in local_var_params:
path_params['owner'] = local_var_params['owner'] # noqa: E501
if 'entity' in local_var_params:
path_params['entity'] = local_var_params['entity'] # noqa: E501
if 'uuid' in local_var_params:
path_params['uuid'] = local_var_params['uuid'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['ApiKey'] # noqa: E501
return self.api_client.call_api(
'/api/v1/{owner}/{entity}/runs/{uuid}/stop', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def stop_run_tensorboard(self, owner, entity, uuid, **kwargs): # noqa: E501
"""Stop run tensorboard # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.stop_run_tensorboard(owner, entity, uuid, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str owner: Owner of the namespace (required)
:param str entity: Entity: project name, hub name, registry name, ... (required)
:param str uuid: Uuid identifier of the sub-entity (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.stop_run_tensorboard_with_http_info(owner, entity, uuid, **kwargs) # noqa: E501
def stop_run_tensorboard_with_http_info(self, owner, entity, uuid, **kwargs): # noqa: E501
"""Stop run tensorboard # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.stop_run_tensorboard_with_http_info(owner, entity, uuid, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str owner: Owner of the namespace (required)
:param str entity: Entity: project name, hub name, registry name, ... (required)
:param str uuid: Uuid identifier of the sub-entity (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'owner',
'entity',
'uuid'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method stop_run_tensorboard" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'owner' is set
if self.api_client.client_side_validation and ('owner' not in local_var_params or # noqa: E501
local_var_params['owner'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `owner` when calling `stop_run_tensorboard`") # noqa: E501
# verify the required parameter 'entity' is set
if self.api_client.client_side_validation and ('entity' not in local_var_params or # noqa: E501
local_var_params['entity'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `entity` when calling `stop_run_tensorboard`") # noqa: E501
# verify the required parameter 'uuid' is set
if self.api_client.client_side_validation and ('uuid' not in local_var_params or # noqa: E501
local_var_params['uuid'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `uuid` when calling `stop_run_tensorboard`") # noqa: E501
collection_formats = {}
path_params = {}
if 'owner' in local_var_params:
path_params['owner'] = local_var_params['owner'] # noqa: E501
if 'entity' in local_var_params:
path_params['entity'] = local_var_params['entity'] # noqa: E501
if 'uuid' in local_var_params:
path_params['uuid'] = local_var_params['uuid'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['ApiKey'] # noqa: E501
return self.api_client.call_api(
'/api/v1/{owner}/{entity}/runs/{uuid}/tensorboard/stop', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def stop_runs(self, owner, project, body, **kwargs): # noqa: E501
"""Stop runs # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.stop_runs(owner, project, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str owner: Owner of the namespace (required)
:param str project: Project under namesapce (required)
:param V1Uuids body: Uuids of the entities (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.stop_runs_with_http_info(owner, project, body, **kwargs) # noqa: E501
def stop_runs_with_http_info(self, owner, project, body, **kwargs): # noqa: E501
"""Stop runs # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.stop_runs_with_http_info(owner, project, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str owner: Owner of the namespace (required)
:param str project: Project under namesapce (required)
:param V1Uuids body: Uuids of the entities (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'owner',
'project',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method stop_runs" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'owner' is set
if self.api_client.client_side_validation and ('owner' not in local_var_params or # noqa: E501
local_var_params['owner'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `owner` when calling `stop_runs`") | |
tariff
level is based on tariff rings (A, B, ...).
- COUNTY tariff level is
based on counties (SE, WL, ...).
- GH tariff level is
based on Großbereich Hamburg/Hamburg AB.
- NET tariff level is
valid in complete tariff net.
- ZG tariff level is
based on payment borders (Zahlgrenzen).
- STADTVERKEHR tariff level is
based on limits for city tickets.
"""
TariffRegionType = In(
["ZONE", "GH_ZONE", "RING", "COUNTY", "GH", "NET", "ZG", "STADTVERKEHR"]
)
"""RequiredRegionType
Contains information about the needed information regarding the region type
type: TariffRegionType holds information about the type that is required (None - None)
count: int holds information about how many regions of the type are required (None - None)
"""
RequiredRegionType = Schema({"type": TariffRegionType, "count": int})
"""TariffLevel
Contains information about a tariff level
id: int Unique identifier for this tariff level (None - None)
label: str label of the tariff level (None - None)
requiredRegionType: RequiredRegionType Describes what additional region information is needed to buy the ticket. (e.g. 2 Zones or 1 County) (None - None)
"""
TariffLevel = Schema(
{"id": int, "label": str, "requiredRegionType": RequiredRegionType}
)
"""TariffMetaDataResponse
Contains tariff related meta data
tariffKinds: TariffKind Contains the different tariff kinds (0 - unbounded)
tariffLevels: TariffLevel Contains the different tariff levels information (0 - unbounded)
tariffCounties: TariffCounty Contains the different tariff counties information (0 - unbounded)
tariffZones: TariffZone Contains the different tariff zones (0 - unbounded)
tariffRings: str Contains the different tariff rings (0 - unbounded)
"""
TariffMetaDataResponse = Schema.extend(
BaseResponseType,
{
"tariffKinds": [TariffKind],
"tariffLevels": [TariffLevel],
"tariffCounties": [TariffCounty],
"tariffZones": [TariffZone],
"tariffRings": [str],
},
)
"""TicketListTicketInfos
Contains infos of a ticket.
tariffKindID: int id of the tariff kind (Kartenart). (None - None)
tariffKindLabel: str name of the tariff kind (e.g. Einzelkarte). (None - None)
tariffLevelID: int id of the tariff level (Tarifstufe). (None - None)
tariffLevelLabel: str name of the tariff level (e.g. Kurzstrecke). (None - None)
tariffGroupID: int id of the tariff group. (0 - None)
tariffGroupLabel: str name of the tariff group (e.g. Allgemeine Zeitkarten). (0 - None)
regionType: TariffRegionType if this is not null, the specified TicketInfo needs this type of additional TariffRegionInfos.
* since version 14 (0 - None)
selectableRegions: int The number of selectable regions with this ticket. (for example with "2 Tarifzonen" this would be 2) Default: 0 (0 - None)
requiredStartStation: bool Holds information if the ticket needs start station information to verify validity. Default: false (None - None)
personInfos: PersonInfo Contains list of information for how many people of a specific type of person the card is for. (0 - unbounded)
validityPeriods: ValidityPeriod Contains information about the validity of this ticket. (0 - unbounded)
variants: TicketListTicketVariant Contains information about one variant of this ticket. (for example 2nd class and 1st class) (0 - unbounded)
"""
TicketListTicketInfos = Schema(
{
"tariffKindID": int,
"tariffKindLabel": str,
"tariffLevelID": int,
"tariffLevelLabel": str,
"tariffGroupID": int,
"tariffGroupLabel": str,
"regionType": TariffRegionType,
"selectableRegions": int,
"requiredStartStation": bool,
"personInfos": [PersonInfo],
"validityPeriods": [ValidityPeriod],
"variants": [TicketListTicketVariant],
}
)
"""TicketListResponse
Response of the TicketListRequest, which contains all HVV Tickets.
ticketInfos: TicketListTicketInfos List of all tickets. (None - unbounded)
"""
TicketListResponse = Schema.extend(
BaseResponseType, {"ticketInfos": [TicketListTicketInfos]}
)
"""TariffRegionInfo
Holds informations about a tariff region (e.g. tariff-zones, tariff-rings).
regionType: TariffRegionType Type of tariff region (e.g. tariff-zone, tariff-ring).
(could be null if there is no TicketInfo of type GH_ZONE). (None - None)
alternatives: TariffRegionList altanatives of crossed tariff regions. Because stations could belong to more than one tariff region, there
could be different possible list of crossed regions for the same route. (0 - unbounded)
"""
TariffRegionInfo = Schema(
{"regionType": TariffRegionType, "alternatives": [TariffRegionList]}
)
"""TicketInfo
Holds detail ticket informations.
tariffKindID: int id of the tariff kind (Kartenart). (None - None)
tariffKindLabel: str name of the tariff kind (e.g. Einzelkarte). (None - None)
tariffLevelID: int id of the tariff level (Tarifstufe). (None - None)
tariffLevelLabel: str name of the tariff level (e.g. Kurzstrecke). (None - None)
tariffGroupID: int id of the tariff group. (0 - None)
tariffGroupLabel: str name of the tariff group (e.g. Allgemeine Zeitkarten). (0 - None)
basePrice: float base ticket price (without extra fare). (None - None)
extraFarePrice: float additional extra fare ticket price. (0 - None)
reducedBasePrice: float reduced base ticket price (without extra fare).
* since version 16 (0 - None)
reducedExtraFarePrice: float reduced additional extra fare ticket price.
* since version 16 (0 - None)
currency: str The currency of the price. Default is Euro. Default: EUR (0 - None)
regionType: TariffRegionType if this is not null, the specified TicketInfo needs this type of additional TariffRegionInfos.
* since version 14 (0 - None)
notRecommended: bool If set to true, this ticket is valid but not recommended.
* since version 32 Default: false (0 - None)
shopLinkRegular: str The link to the shop, where you could buy this ticket as a regular ticket.
* since version 32 (0 - None)
shopLinkExtraFare: str The link to the shop, where you could buy this ticket as an extra fare ticket.
* since version 32 (0 - None)
"""
TicketInfo = Schema(
{
"tariffKindID": int,
"tariffKindLabel": str,
"tariffLevelID": int,
"tariffLevelLabel": str,
"tariffGroupID": int,
"tariffGroupLabel": str,
"basePrice": float,
"extraFarePrice": float,
"reducedBasePrice": float,
"reducedExtraFarePrice": float,
"currency": str,
"regionType": TariffRegionType,
"notRecommended": bool,
"shopLinkRegular": str,
"shopLinkExtraFare": str,
}
)
"""ShopType
- AST: Anruf-Sammel-Taxi
"""
ShopType = In(["AST"])
"""ShopInfo
Information about the shop, where a ticket could be bought.
shopType: ShopType Type of Shop (for example Anruf-Sammel-Taxi) (1 - 1)
url: str URL of the responsible ticket shop. (1 - 1)
"""
ShopInfo = Schema({Required("shopType"): ShopType, Required("url"): str})
"""RealtimeType
Configures the consideration of realtime informations during route calculation.
-PLANDATA: only return a result based on plandata.
-REALTIME: only return a result based on realtime data.
-AUTO: The plandata result (schedules) will allways be returned. Realtime result
(realtimeSchedules) will be returned if it is different from plandata result.
* since version 19
"""
RealtimeType = In(["PLANDATA", "REALTIME", "AUTO"])
"""IndividualProfileType
Configures requests for routes by different profiles.
* since version 25
"""
IndividualProfileType = In(
[
"BICYCLE_NORMAL",
"BICYCLE_RACING",
"BICYCLE_QUIET_ROADS",
"BICYCLE_MAIN_ROADS",
"BICYCLE_BAD_WEATHER",
"FOOT_NORMAL",
]
)
"""SimpleServiceType
Enumeration with all simple types of services
* BICYCLE since API version 17
"""
SimpleServiceType = In(
[
"BUS",
"TRAIN",
"SHIP",
"FOOTPATH",
"BICYCLE",
"AIRPLANE",
"CHANGE",
"CHANGE_SAME_PLATFORM",
]
)
"""ServiceType
The complex type of a Service. Includes the simple type and additional information.
simpleType: SimpleServiceType The simple type of a Service, like BUS or TRAIN. (None - None)
shortInfo: str A short information about the vehicle (e.g. Schnellbus). More information see properties in geofox. (0 - None)
longInfo: str More detailled information about the vehicle (e.g. Niederflur-Schnellbus). More information
see properties in geofox. (0 - None)
model: str The specific model of the vehicle if applicable and available. * since API version 24 (0 - None)
"""
ServiceType = Schema(
{"simpleType": SimpleServiceType, "shortInfo": str, "longInfo": str, "model": str}
)
"""LineListEntry
One entry of the line list
id: str The unique id of an entry (None - None)
name: str Name of the entry. Is null if the line was
deleted. (0 - None)
carrierNameShort: str Short name of the carrier. Is null if the line
was deleted. (0 - None)
carrierNameLong: str Long name of the carrier. Is null if the line
was deleted. (0 - None)
sublines: SublineListEntry List of sublines. Is null if no sublines were
requested or if the line
was deleted. (0 - unbounded)
exists: bool This field is false if the line is deleted. Default: true (0 - None)
type: ServiceType The type of the service. For Example: BUS, TRAIN
with optional additional information. (None - None)
"""
LineListEntry = Schema(
{
"id": str,
"name": str,
"carrierNameShort": str,
"carrierNameLong": str,
"sublines": [SublineListEntry],
"exists": bool,
"type": ServiceType,
}
)
"""LLResponse
The response for LLRequest with a list of lines.
dataReleaseID: str result was created on this data release. (0 - None)
lines: LineListEntry List of lines. This list could be empty if
there is no line fitting
to the given filter settings. (0 - unbounded)
"""
LLResponse = Schema.extend(
BaseResponseType, {"dataReleaseID": str, "lines": [LineListEntry]}
)
"""Service
The service with type and a name.
name: str The name of the service. For Example: S1, U3, 101, etc. (None - None)
direction: str The direction where the service is headed. (0 - None)
directionId: int The id of the direction. Forward (1), backward (6). (0 - None)
origin: str The origin where the service comes from (opposite of direction).
* since version 19 (0 - None)
type: ServiceType The type of the service. For Example: BUS, TRAIN with optional additional information. (None - None)
id: str The id of a service. Is neccessary for TariffRequest. This is NOT the service-id, but the line key
* since version 4 (0 - None)
"""
Service = Schema(
{
"name": str,
"direction": str,
"directionId": int,
"origin": str,
"type": ServiceType,
"id": str,
| |
import numpy as np
import pickle
import os
from copy import deepcopy
from scipy.special import digamma
from pynverse import inversefunc
from utils import bql_f_inv, \
normal_gamma, \
solve_tabular_continuing_PI
# ============================================================================
# General Tabular agent class
# ============================================================================
class TabularAgent:
def __init__(self, gamma):
# Discount factor
self.gamma = gamma
def add_observations(self, s, a, r, s_):
""" Add observations to log. """
s, a, r, s_ = [np.array([data]) for data in [s, a, r, s_]]
if hasattr(self, 'train_s'):
self.train_s = np.concatenate([self.train_s, s], axis=0)
self.train_a = np.concatenate([self.train_a, a], axis=0)
self.train_s_ = np.concatenate([self.train_s_, s_], axis=0)
self.train_r = np.concatenate([self.train_r, r], axis=0)
else:
self.train_s = s
self.train_a = a
self.train_s_ = s_
self.train_r = r
def take_action(self, s, t, policy_params):
raise NotImplementedError
def update_after_step(self, t):
pass
def observe(self, transition):
pass
def save_copy(self, location, name):
""" Save a copy of the agent. """
fhandle = open(location + '/' + name, 'wb')
pickle.dump(self, fhandle)
fhandle.close()
# ============================================================================
# QLearningAgent class
# ============================================================================
class QLearningAgent(TabularAgent):
def __init__(self, params):
# Set QLearning agent parameters
self.gamma = params['gamma']
self.lr = params['lr']
self.sa_list = params['sa_list']
self.Q0 = params['Q0']
self.dither_mode = params['dither_mode']
self.dither_param = params['dither_param']
self.anneal_timescale = params['anneal_timescale']
# Array for storing previous Q posterior
self.Qlog = []
super(QLearningAgent, self).__init__(self.gamma)
# Set initial Q values to Q0, and create set of valid actions
self.Q = {}
self.valid_actions = {}
# List of valid state-actions
for (s, a) in self.sa_list:
if s not in self.Q:
self.Q[s] = {a : self.Q0}
else:
self.Q[s][a] = self.Q0
if s not in self.valid_actions:
self.valid_actions[s] = set([a])
else:
self.valid_actions[s].add(a)
def take_action(self, s, t):
""" Take epsilon-greedy or boltzmann action. """
# Compute annealing factor for epsilon or T
anneal_factor = np.exp(- t / self.anneal_timescale)
if self.dither_mode == 'epsilon-greedy':
# Get action corresponding to highest Q
a = self.get_max_a_Q(s, argmax=True)
if np.random.rand() < anneal_factor * self.dither_param:
# Return random pick from valid actions
return np.random.choice(list(self.valid_actions[s]))
else:
return a
elif self.dither_mode == 'boltzmann':
# Get list of valid actions from state s
valid_actions = list(self.valid_actions[s])
# Get Q values coorespodning to actions from state s
Q_ = np.array([self.Q[s][a] for a in valid_actions])
# Calculate Boltzmann probabilities and normalise
probs = np.exp(Q_ / (self.dither_param * anneal_factor))
probs = probs / probs.sum()
return np.random.choice(valid_actions, p=probs)
def update_Q(self, s, a, r, s_):
""" Update Q-estimates using Temporal Differences update. """
# Get maximum Q corresponding to next state s_
max_a_Q = self.get_max_a_Q(s_)
# Apply Q-Learning update rule
self.Q[s][a] += self.lr * (r + self.gamma * max_a_Q - self.Q[s][a])
def get_max_a_Q(self, s, argmax=False):
""" Returns the maximum of Q[s] across all valid actions. """
# Get list of valid actions
valid_actions = list(self.valid_actions[s])
# Get Q values coorespodning to actions from state s
Q_ = np.array([self.Q[s][a] for a in valid_actions])
if argmax:
# Break ties at random
a_idx = np.random.choice(np.argwhere(Q_ == np.amax(Q_))[:, 0])
return valid_actions[a_idx]
else:
return np.max(Q_)
def observe(self, transition):
t, s, a, r, s_ = transition
self.add_observations(s, a, r, s_)
self.last_transition = transition
def update_after_step(self, max_buffer_length, log):
# Log Q values
if log: self.Qlog.append(deepcopy(self.Q))
# Update Q values
t, s, a, r, s_ = self.last_transition
self.update_Q(s, a, r, s_)
self.last_transition = None
def get_name(self):
name = 'QLearningAgent_{}_param-{}_gamma-{}_lr-{}_Q0-{}-tscale-{}'
name = name.format(self.dither_mode,
self.dither_param,
self.gamma,
self.lr,
self.Q0,
self.anneal_timescale)
return name
# ============================================================================
# BayesianQAgent class
# ============================================================================
class BayesianQAgent(TabularAgent):
def __init__(self, params):
# Bayesian Q-Learning agent parameters
self.gamma = params['gamma']
self.mu0 = params['mu0']
self.lamda = params['lamda']
self.alpha = params['alpha']
self.beta = params['beta']
self.sa_list = params['sa_list']
self.num_mixture_samples = params['num_mixture_samples']
# List for storing Q posterior hyperparameters
self.Qpost_log = []
super(BayesianQAgent, self).__init__(params['gamma'])
# Dict for holding posterior phyperparameters
self.Qpost = {}
# Set normal-gamma prior parameters for each state-action
for s, a in self.sa_list:
if s not in self.Qpost: self.Qpost[s] = {}
self.Qpost[s][a] = (self.mu0, self.lamda, self.alpha, self.beta)
def take_action(self, s, t, reduce_max=True):
# Sample q values for each action from current state
qs, acts = self.sample_q(s)
if reduce_max:
# Return action corresponding to maximum q
return acts[np.argmax(qs)]
else:
return qs, acts
def sample_q(self, s):
# Arrays for holding q samples and corresponding actions
qs, acts = [], []
for a, hyp in self.Qpost[s].items():
# Sample from student-t distribution
st = np.random.standard_t(2 * hyp[2])
# q sample from t: m0 + t * (beta / (lamda * alpha))**0.5
qs.append(hyp[0] + st * (hyp[3] / (hyp[1] * hyp[2]))**0.5)
acts.append(a)
return np.array(qs), np.array(acts)
def kl_matched_hyps(self, s, a, r, s_):
num_samples = self.num_mixture_samples
# Find the action from s_ with the largest mean
a_ = self.max_mu0_action(s_)
# Parameters for next state-action NG and posterior predictive
mu0_, lamda_, alpha_, beta_ = self.Qpost[s_][a_]
coeff = (beta_ * (lamda_ + 1) / (alpha_ * lamda_))**0.5
# Sample from student-t, rescale and add mean
st = np.random.standard_t(2 * alpha_, size=(num_samples,))
z_samp = mu0_ + st * coeff
# Dicount and add reward
z_samp = r + self.gamma * z_samp
# z_sa posterior hyperparameters
mu0_sa, lamda_sa, alpha_sa, beta_sa = self.Qpost[s][a]
# z_sa posterior hyperparameters updated for each sample
mu0_ = (lamda_sa * mu0_sa + z_samp) / (lamda_sa + 1)
lamda_ = np.array([lamda_sa + 1] * mu0_.shape[0])
alpha_ = np.array([alpha_sa + 0.5] * mu0_.shape[0])
beta_ = beta_sa + lamda_sa * (z_samp - mu0_sa)**2 / (2 * lamda_sa + 2)
# Sample mu and tau for each set of updated hyperparameters
mus, taus = normal_gamma(mu0_, lamda_, alpha_, beta_)
# MC estimates of moments
E_tau = np.mean(taus)
E_mu_tau = np.mean(mus * taus)
E_mu2_tau = np.mean(mus**2 * taus)
E_log_tau = np.mean(np.log(taus))
# f^-1(x) where f(x) = log(x) - digamma(x)
f_inv_term = bql_f_inv(np.log(E_tau) - E_log_tau)
# Calculate hyperparameters of KL-matched normal gamma
mu0 = E_mu_tau / E_tau
lamda = 1 / (1e-12 + E_mu2_tau - E_tau * mu0**2)
alpha = max(1 + 1e-6, f_inv_term)
beta = alpha / E_tau
return mu0, lamda, alpha, beta
def max_mu0_action(self, s):
# Get actions and corresponding hyperparameters of R_sa distribution
a_mu0 = [(a, hyp[0]) for (a, hyp) in self.Qpost[s].items()]
a, mu0 = [np.array(arr) for arr in zip(*a_mu0)]
return a[np.argmax(mu0)]
def observe(self, transition):
t, s, a, r, s_ = transition
self.add_observations(s, a, r, s_)
self.last_transition = transition
def update_after_step(self, max_buffer_length, log):
# Log Q posterior hyperparameters
if log: self.Qpost_log.append(deepcopy(self.Qpost))
# Update hyperparameters
t, s, a, r, s_ = self.last_transition
hyps = self.kl_matched_hyps(s, a, r, s_)
self.Qpost[s][a] = hyps
self.last_transition = None
def get_name(self):
name = 'BayesianQAgent_gamma-{}_mu0-{}_lamda-{}_alpha-{}_beta-{}'
name = name.format(self.gamma,
self.mu0,
self.lamda,
self.alpha,
self.beta)
return name
# ============================================================================
# PSRLAgent agent definition
# ============================================================================
class PSRLAgent(TabularAgent):
def __init__(self, params):
# PSRL agent parameters
self.gamma = params['gamma']
self.kappa = params['kappa']
self.mu0 = params['mu0']
self.lamda = params['lamda']
self.alpha = params['alpha']
self.beta = params['beta']
self.sa_list = params['sa_list']
self.max_iter = params['max_iter']
self.Ppost = {}
self.Rpost = {}
self.buffer = []
self.num_s = len(set([s for (s, a) in self.sa_list]))
self.num_a = len(set([a for (s, a) in self.sa_list]))
# Lists for storing P and R posteriors
self.Ppost_log = []
self.Rpost_log = []
super(PSRLAgent, self).__init__(params['gamma'])
# Dynamics posterior
self.Ppost = self.kappa * np.ones((self.num_s, self.num_a, self.num_s))
# Rewards posterior parameters for non-allowed actions
Rparam = [-1e12, 1e9, 1e12, 1e9]
Rparam = [[[Rparam] * self.num_s] * self.num_a] * self.num_s
self.Rpost = np.array(Rparam)
# Rewards posterior parameters for allowed actions
Rparam = [self.mu0, self.lamda, self.alpha, self.beta]
Rparam = np.array([Rparam] * self.num_s)
for (s, a) in self.sa_list:
self.Rpost[s, a, ...] = Rparam
self.sample_posterior_and_update_continuing_policy()
def sample_posterior(self):
# Initialise posterior arrays (dynamics 0, reward large negative)
P = np.zeros((self.num_s, self.num_a, self.num_s))
R = np.zeros((self.num_s, self.num_a, self.num_s))
for s in range(self.num_s):
for a in range(self.num_a):
P[s, a, :] = np.random.dirichlet(self.Ppost[s, a])
for s in range(self.num_s):
for a in range(self.num_a):
for s_ in range(self.num_s):
mu0, lamda, alpha, beta = self.Rpost[s, a, s_]
R[s, a, s_] = normal_gamma(mu0, lamda, alpha, beta)[0]
return P, R
def update_posterior(self):
# Transition counts | |
<reponame>NeilJ-Thomson/pensa<gh_stars>10-100
import numpy as np
from tqdm import tqdm
from pensa.features import *
from pensa.statesinfo import *
# -- Functions to calculate SSI statistics across paired ensembles --
def ssi_ensemble_analysis(features_a, features_b, all_data_a, all_data_b, torsions=None, pocket_occupancy=None, pbc=True,
verbose=True, write_plots=None, override_name_check=False):
"""
Calculates State Specific Information statistic for a feature across two ensembles.
Parameters
----------
features_a : list of str
Feature names of the first ensemble.
features_b : list of str
Feature names of the first ensemble.
Must be the same as features_a. Provided as a sanity check.
all_data_a : float array
Trajectory data from the first ensemble. Format: [frames,frame_data].
all_data_b : float array
Trajectory data from the second ensemble. Format: [frames,frame_data].
torsions : str
Torsion angles to use for SSI, including backbone - 'bb', and sidechain - 'sc'.
Default is None.
pocket_occupancy : bool, optional
Set to 'True' if the data input is pocket occupancy distribution.
The default is None.
pbc : bool, optional
If true, the apply periodic bounary corrections on angular distribution inputs.
The input for periodic correction must be radians. The default is True.
verbose : bool, default=True
Print intermediate results.
write_plots : bool, optional
If true, visualise the states over the raw distribution. The default is None.
override_name_check : bool, default=False
Only check number of features, not their names.
Returns
-------
data_names : list of str
Feature names.
data_ssi : float array
State Specific Information statistics for each feature.
"""
# Get the multivariate timeseries data
if torsions is None:
mv_res_feat_a, mv_res_data_a = features_a,all_data_a
mv_res_feat_b, mv_res_data_b = features_b,all_data_b
else:
mv_res_feat_a, mv_res_data_a = get_multivar_res_timeseries(features_a,all_data_a,torsions+'-torsions',write=False,out_name='')
mv_res_feat_b, mv_res_data_b = get_multivar_res_timeseries(features_b,all_data_b,torsions+'-torsions',write=False,out_name='')
mv_res_feat_a, mv_res_data_a = mv_res_feat_a[torsions+'-torsions'], mv_res_data_a[torsions+'-torsions']
mv_res_feat_b, mv_res_data_b = mv_res_feat_b[torsions+'-torsions'], mv_res_data_b[torsions+'-torsions']
# Assert that the features are the same and data sets have same number of features
if override_name_check:
assert len(mv_res_feat_a) == len(mv_res_feat_b)
else:
assert mv_res_feat_a == mv_res_feat_b
assert mv_res_data_a.shape[0] == mv_res_data_b.shape[0]
# Extract the names of the features
data_names = mv_res_feat_a
# Initialize relative entropy and average value
data_ssi = np.zeros(len(data_names))
# Loop over all features
for residue in range(len(mv_res_data_a)):
data_a = mv_res_data_a[residue]
data_b = mv_res_data_b[residue]
combined_dist=[]
for dist_no in range(len(data_a)):
# # # combine the ensembles into one distribution (condition_a + condition_b)
data_both = list(data_a[dist_no]) + list(data_b[dist_no])
combined_dist.append(data_both)
## Saving distribution length
traj1_len = len(data_a[dist_no])
if pbc is True:
feat_distr = [correct_angle_periodicity(distr) for distr in combined_dist]
else:
feat_distr = combined_dist
if pocket_occupancy is True:
## Define states for water occupancy
feat_states = [[-0.5,0.5,1.5]]
else:
feat_states=[]
for dim_num in range(len(feat_distr)):
if write_plots is True:
plot_name = data_names[residue]
else:
plot_name = None
try:
feat_states.append(determine_state_limits(feat_distr[dim_num],
traj1_len,
write_plots=write_plots,
write_name=plot_name))
except:
print('Distribution A not clustering properly.\nTry altering Gaussian parameters or input custom states.')
H_feat=calculate_entropy(feat_states,feat_distr)
if H_feat != 0:
##calculating the entropy for set_distr_b
## if no dist (None) then apply the binary dist for two simulations
ens_distr=[[0.5]*traj1_len + [1.5]*int(len(feat_distr[0])-traj1_len)]
ens_states= [[0,1,2]]
traj_1_fraction = traj1_len/len(feat_distr[0])
traj_2_fraction = 1 - traj_1_fraction
norm_factor = -1*traj_1_fraction*math.log(traj_1_fraction,2) - 1*traj_2_fraction*math.log(traj_2_fraction,2)
H_ens = norm_factor
featens_joint_states= feat_states + ens_states
featens_joint_distr= feat_distr + ens_distr
H_featens=calculate_entropy(featens_joint_states,featens_joint_distr)
SSI = ((H_feat + H_ens) - H_featens)/norm_factor
else:
SSI = 0
data_ssi[residue] = SSI
if verbose is True:
print(data_names[residue],data_ssi[residue])
return data_names, data_ssi
def ssi_feature_analysis(features_a, features_b, all_data_a, all_data_b, torsions=None, verbose=True, override_name_check=False):
"""
Calculates State Specific Information statistic between two features across two ensembles.
Parameters
----------
features_a : list of str
Feature names of the first ensemble.
features_b : list of str
Feature names of the first ensemble.
Must be the same as features_a. Provided as a sanity check.
all_data_a : float array
Trajectory data from the first ensemble. Format: [frames,frame_data].
all_data_b : float array
Trajectory data from the second ensemble. Format: [frames,frame_data].
torsions : str
Torsion angles to use for SSI, including backbone - 'bb', and sidechain - 'sc'.
Default is None.
verbose : bool, default=True
Print intermediate results.
override_name_check : bool, default=False
Only check number of features, not their names.
Returns
-------
data_names : list of str
Feature names.
data_ssi : float array
State Specific Information statistics for each feature.
"""
# Get the multivariate timeseries data
if torsions is None:
mv_res_feat_a, mv_res_data_a = features_a,all_data_a
mv_res_feat_b, mv_res_data_b = features_b,all_data_b
else:
mv_res_feat_a, mv_res_data_a = get_multivar_res_timeseries(features_a,all_data_a,torsions+'-torsions',write=False,out_name='')
mv_res_feat_b, mv_res_data_b = get_multivar_res_timeseries(features_b,all_data_b,torsions+'-torsions',write=False,out_name='')
mv_res_feat_a, mv_res_data_a = mv_res_feat_a[torsions+'-torsions'], mv_res_data_a[torsions+'-torsions']
mv_res_feat_b, mv_res_data_b = mv_res_feat_b[torsions+'-torsions'], mv_res_data_b[torsions+'-torsions']
# Assert that the features are the same and data sets have same number of features
if override_name_check:
assert len(mv_res_feat_a) == len(mv_res_feat_b)
else:
assert mv_res_feat_a == mv_res_feat_b
assert mv_res_data_a.shape[0] == mv_res_data_b.shape[0]
# Extract the names of the features
data_names = []
for feat1 in range(len(mv_res_feat_a)):
for feat2 in range(feat1, len(mv_res_feat_a)):
data_names.append(torsions + ' ' + mv_res_feat_a[feat1] + ' & ' + torsions + ' ' + mv_res_feat_a[feat2])
# Initialize SSI
data_ssi = np.zeros(len(data_names))
# Loop over all features
count=0
for res1 in range(len(mv_res_data_a)):
# print(res1)
res1_data_ens1 = mv_res_data_a[res1]
res1_data_ens2 = mv_res_data_b[res1]
res1_combined_dist=[]
for dist_no_a in range(len(res1_data_ens1)):
# # # combine the ensembles into one distribution (condition_a + condition_b)
res1_data_both = list(res1_data_ens1[dist_no_a]) + list(res1_data_ens2[dist_no_a])
res1_combined_dist.append(res1_data_both)
## Saving distribution length
traj1_len = len(res1_data_ens1[dist_no_a])
# if calculate_ssi(res1_combined_dist, traj1_len)!=0:
set_distr_a=[correct_angle_periodicity(distr_a) for distr_a in res1_combined_dist]
set_a_states=[]
for dim_num_a in range(len(set_distr_a)):
set_a_states.append(determine_state_limits(set_distr_a[dim_num_a], traj1_len))
H_a=calculate_entropy(set_a_states,set_distr_a)
if H_a != 0:
for res2 in range(res1, len(mv_res_data_a)):
# Only run SSI if entropy is non-zero
res2_data_ens1 = mv_res_data_a[res2]
res2_data_ens2 = mv_res_data_b[res2]
res2_combined_dist=[]
for dist_no_b in range(len(res2_data_ens1)):
# # # combine the ensembles into one distribution (condition_a + condition_b)
res2_data_both = list(res2_data_ens1[dist_no_b]) + list(res2_data_ens2[dist_no_b])
res2_combined_dist.append(res2_data_both)
set_distr_b=[correct_angle_periodicity(distr_b) for distr_b in res2_combined_dist]
set_b_states=[]
for dim_num_b in range(len(set_distr_b)):
set_b_states.append(determine_state_limits(set_distr_b[dim_num_b], traj1_len))
H_b=calculate_entropy(set_b_states,set_distr_b)
if H_b!=0:
ab_joint_states= set_a_states + set_b_states
ab_joint_distributions= set_distr_a + set_distr_b
H_ab=calculate_entropy(ab_joint_states,ab_joint_distributions)
traj_1_fraction = traj1_len/len(set_distr_a[0])
traj_2_fraction = 1 - traj_1_fraction
norm_factor = -1*traj_1_fraction*math.log(traj_1_fraction,2) - 1*traj_2_fraction*math.log(traj_2_fraction,2)
SSI = ((H_a + H_b) - H_ab)/norm_factor
data_ssi[count] = SSI
if verbose is True:
print(data_names[count],'\nSSI[bits]: ',data_ssi[count])
count+=1
else:
if verbose is True:
print(data_names[count],'\nSSI[bits]: ',data_ssi[count])
count+=1
else:
for res2 in range(res1+1, len(mv_res_data_a)):
if verbose is True:
print(data_names[count],'\nSSI[bits]: ',data_ssi[count])
count+=1
return data_names, data_ssi
def cossi_featens_analysis(features_a, features_b, all_data_a, all_data_b, torsions=None, verbose=True, override_name_check=False):
"""
Calculates State Specific Information Co-SSI statistic between two features and the ensembles condition.
Parameters
----------
features_a : list of str
Feature names of the first ensemble.
features_b : list of str
Feature names of the first ensemble.
Must be the same as features_a. Provided as a sanity check.
all_data_a : float array
Trajectory data from the first ensemble. Format: [frames,frame_data].
all_data_b : float array
Trajectory data from the second ensemble. Format: [frames,frame_data].
torsions : str
Torsion angles to use for SSI, including backbone - 'bb', and sidechain - 'sc'.
Default is None.
verbose : bool, default=True
Print intermediate results.
override_name_check : bool, default=False
Only check number of features, not their names.
Returns
-------
data_names : list of str
Feature names.
data_ssi : float array
State Specific Information SSI statistics for each feature.
data_cossi : float array
State Specific Information Co-SSI statistics for each feature.
"""
# Get the multivariate timeseries data
if torsions is None:
mv_res_feat_a, mv_res_data_a = features_a,all_data_a
mv_res_feat_b, mv_res_data_b = features_b,all_data_b
else:
mv_res_feat_a, mv_res_data_a = get_multivar_res_timeseries(features_a,all_data_a,torsions+'-torsions',write=False,out_name='')
mv_res_feat_b, mv_res_data_b = get_multivar_res_timeseries(features_b,all_data_b,torsions+'-torsions',write=False,out_name='')
mv_res_feat_a, mv_res_data_a = mv_res_feat_a[torsions+'-torsions'], mv_res_data_a[torsions+'-torsions']
mv_res_feat_b, mv_res_data_b = mv_res_feat_b[torsions+'-torsions'], mv_res_data_b[torsions+'-torsions']
# Assert that the features are the same and data sets have same number of features
if override_name_check:
assert len(mv_res_feat_a) == len(mv_res_feat_b)
else:
assert mv_res_feat_a == mv_res_feat_b
assert mv_res_data_a.shape[0] == mv_res_data_b.shape[0]
# Extract the names of the features
data_names = []
for feat1 in range(len(mv_res_feat_a)):
for feat2 in range(feat1, len(mv_res_feat_a)):
data_names.append(torsions + ' ' + mv_res_feat_a[feat1] + ' & ' + torsions + ' ' + mv_res_feat_a[feat2])
# Initialize SSI and | |
"""A parameter range scaling the simulated kite moments-of-inertia."""
def __init__(self, dim, scales, distribution, body, body_name=''):
"""Constructor.
Args:
dim: Dimension to apply the scaling to (one of 0, 1, 2).
scales: Scale factors to apply.
distribution: Parameter for specifying probability distribution.
body: String identifying the body in the 'sim' dictionary.
body_name: Name to be used in the score name.
"""
self.dim = dim
self.body = body
super(InertiaScaleParameterRange, self).__init__(
body_name + ' %s Inertia Scaling [#]' % ['X', 'Y', 'Z'][dim], scales,
distribution)
def GetOverrides(self, value):
return {
'sim': {
self.body: {
'mass_prop_uncertainties': {
'moment_of_inertia_scale': {
self.dim: value
}
}
}
}
}
class AeroSimOffsetParameterRange(ParameterRange):
"""A parameter range overriding the aerodynamic offsets."""
def __init__(self, field, offsets, distribution):
"""Constructor.
Args:
field: Offset to adjust.
offsets: A list of values to sweep over.
distribution: Parameter for specifying probability distribution.
"""
self.field = field
super(AeroSimOffsetParameterRange, self).__init__(
field + ' Offset', offsets, distribution)
def GetOverrides(self, value):
return {
'sim': {
'aero_sim': {
'coeff_offsets': {
self.field: value
}
}
}
}
class AeroSimMomentBFlapScalingParameterRange(ParameterRange):
"""A parameter range for scaling the moments from flap deflections."""
def __init__(self, label, moment, basis, scale_differences,
distribution):
"""Constructor.
Args:
label: Name to display.
moment: Index in (0, 1, 2) indicating which moment to scale.
basis: Array of kNumFlaps values to multiply scale_differences by.
scale_differences: Value to add to 1.0 to generate the scaling.
distribution: Parameter for specifying probability distribution.
"""
self.moment = moment
self.basis = basis
super(AeroSimMomentBFlapScalingParameterRange, self).__init__(
label, scale_differences, distribution)
def GetOverrides(self, value):
scale_factor = 1.0 + value
return {
'sim': {
'aero_sim': {
'moment_coeff_b_scale_factors': {
'flap_derivatives': {
flap: {
self.moment: scale_factor * self.basis[flap]
}
for flap in range(system_types.kNumFlaps)
if numpy.abs(self.basis[flap]) > 0.0
}
}
}
}
}
class AeroSimForceBFlapScalingParameterRange(ParameterRange):
"""A parameter range for scaling the forces from flap deflections."""
def __init__(self, label, force, basis, scale_differences,
distribution):
"""Constructor.
Args:
label: Name to display.
force: Index in (0, 1, 2) indicating which force to scale.
basis: Array of kNumFlaps values to multiply scale_differences by.
scale_differences: Value to add to 1.0 to generate the scaling.
distribution: Parameter for specifying probability distribution.
"""
self.force = force
self.basis = basis
super(AeroSimForceBFlapScalingParameterRange, self).__init__(
label, scale_differences, distribution)
def GetOverrides(self, value):
scale_factor = 1.0 + value
return {
'sim': {
'aero_sim': {
'force_coeff_w_scale_factors': {
'flap_derivatives': {
flap: {
self.force: scale_factor * self.basis[flap]
}
for flap in range(system_types.kNumFlaps)
if numpy.abs(self.basis[flap]) > 0.0
}
}
}
}
}
class AeroSimMomentBRateScalingParameterRange(ParameterRange):
"""A parameter range for scaling the body aero moments from body rates."""
moments = ['l', 'm', 'n']
def __init__(self, moment, rate, scale_differences, distribution):
"""Constructor.
Args:
moment: Index in (0, 1, 2) indicating which moment to scale.
rate: One of 'p', 'q', or 'r'.
scale_differences: Value to add to 1.0 to generate the scaling.
distribution: Parameter for specifying probability distribution.
"""
self.moment = moment
self.rate = rate
super(AeroSimMomentBRateScalingParameterRange, self).__init__(
'C%s%s Scaling Factor Offset [#]'
% (self.moments[self.moment], self.rate),
scale_differences, distribution)
def GetOverrides(self, value):
scaling = 1.0 + value
return {
'sim': {
'aero_sim': {
'moment_coeff_b_scale_factors': {
'rate_derivatives': {
self.rate: {
self.moment: scaling
}
}
}
}
}
}
class AeroSimForceBRateScalingParameterRange(ParameterRange):
"""A parameter range for scaling the wind aero forces from body rates."""
forces = ['D', 'Y', 'L']
def __init__(self, force, rate, scale_differences, distribution):
"""Constructor.
Args:
force: Index in (0, 1, 2) indicating which force to scale.
rate: One of 'p', 'q', or 'r'.
scale_differences: Value to add to 1.0 to generate the scaling.
distribution: Parameter for specifying probability distribution.
"""
self.force = force
self.rate = rate
super(AeroSimForceBRateScalingParameterRange, self).__init__(
'C%s%s Scaling Factor Offset [#]'
% (self.forces[self.force], self.rate),
scale_differences, distribution)
def GetOverrides(self, value):
scaling = 1.0 + value
return {
'sim': {
'aero_sim': {
'force_coeff_w_scale_factors': {
'rate_derivatives': {
self.rate: {
self.force: scaling
}
}
}
}
}
}
class AeroSimFlapOffsetParameterRange(ParameterRange):
"""A parameter range overriding the flap offsets."""
def __init__(self, label, basis, offsets, distribution):
"""Constructor.
Args:
label: Label for this range.
basis: Basis vector to scale (numpy.array of kNumFlaps elements).
offsets: A list of values to sweep over.
distribution: Parameter for specifying probability distribution.
"""
self.basis = basis
super(AeroSimFlapOffsetParameterRange, self).__init__(label, offsets,
distribution)
def GetOverrides(self, value):
return {
'sim': {
'aero_sim': {
'flap_offsets': {
flap: value * self.basis[flap]
for flap in range(system_types.kNumFlaps)
if numpy.abs(self.basis[flap]) > 0.0
}
}
}
}
class AirDensityParameterRange(ParameterRange):
"""A parameter range overriding the simulator's air density."""
def __init__(self, air_densities, distribution):
"""Constructor.
Args:
air_densities: A list of air densities defining this parameter range.
distribution: Parameter for specifying probability distribution.
"""
super(AirDensityParameterRange, self).__init__(
'Air Density [kg/m^3]', air_densities, distribution)
def GetOverrides(self, value):
return {
'sim': {
'phys_sim': {
'air_density': value
}
}
}
class WindSpeedParameterRange(ParameterRange):
"""A parameter range overriding the wind speed."""
def __init__(self, wind_speeds, wind_shear_ref_height_agl=None,
t_updates=None, max_wind_speed=None):
"""Constructor.
Args:
wind_speeds: A list of wind speeds defining this parameter range.
wind_shear_ref_height_agl: Above-ground-level reference height [m] for
the wind shear model.
t_updates: A list of times [s] when wind speed updates are applied.
max_wind_speed: Speed [m/s] used to saturate the mean wind speed before
the second entry and after the third entry in t_updates.
"""
if wind_shear_ref_height_agl is not None:
label = 'Wind Speed [m/s] @ %.f [m] AGL' % wind_shear_ref_height_agl
else:
label = 'Wind Speed [m/s]'
super(WindSpeedParameterRange, self).__init__(
label, wind_speeds, distribution=None)
self._wind_shear_ref_height_agl = wind_shear_ref_height_agl
self._t_updates = t_updates
self._max_wind_speed = max_wind_speed
def GetOverrides(self, value):
assert value >= 0, ('Wind speed must be positive. '
'Use WindDirectionDegParameterRange override to assign '
'appropriate direction.')
overrides = {
'sim': {
'phys_sim': {
'wind_speed': value
}
}
}
if self._wind_shear_ref_height_agl is not None:
overrides['sim']['phys_sim']['wind_shear_ref_height_agl'] = (
self._wind_shear_ref_height_agl)
if self._t_updates is not None:
num_updates = len(self._t_updates)
assert num_updates == 3, (
'The wind speed saturation logic in batch sims requires 3 updates.')
offset_value = min(0.0, self._max_wind_speed - value)
wind_speed_offsets = [{
't_update': self._t_updates[0],
'offset': offset_value,
}, {
't_update': self._t_updates[1],
'offset': 0.0,
}, {
't_update': self._t_updates[2],
'offset': offset_value,
}]
overrides['sim']['phys_sim']['wind_speed_update'] = (
overrides_util.PreprocessWindSpeedUpdates(wind_speed_offsets))
return overrides
class WindDirectionDegParameterRange(ParameterRange):
"""A parameter range overriding the wind_direction."""
def __init__(self, wind_directions, distribution):
"""Constructor.
Args:
wind_directions: A list of wind directions [deg].
distribution: Parameter for specifying probability distribution.
"""
super(WindDirectionDegParameterRange, self).__init__(
'Wind Direction [deg]', wind_directions, distribution)
def GetOverrides(self, value):
return {
'sim': {
'phys_sim': {
'wind_direction': numpy.deg2rad(value % 360.0)
}
}
}
class WindElevationDegParameterRange(ParameterRange):
"""A parameter range overriding the wind elevation."""
def __init__(self, elevations, distribution):
"""Constructor.
Args:
elevations: A list of wind elevations [deg].
distribution: Parameter for specifying probability distribution.
"""
super(WindElevationDegParameterRange, self).__init__(
'Wind Elevation [deg]', elevations, distribution)
def GetOverrides(self, value):
return {
'sim': {
'phys_sim': {
'wind_elevation': numpy.deg2rad(value)
}
}
}
class WindDatabaseInitialTimeParameterRange(ParameterRange):
"""A parameter range overriding the initial time of the wind database."""
def __init__(self, times, distribution):
"""Constructor.
Args:
times: A list of initial times [s].
distribution: Parameter for specifying probability distribution.
"""
super(WindDatabaseInitialTimeParameterRange, self).__init__(
'Wind Database Initial Time [s]', times, distribution)
def GetOverrides(self, value):
return {
'sim': {
'phys_sim': {
'wind_database_initial_time': value
}
}
}
class WindDatabaseYOffsetParameterRange(ParameterRange):
"""A parameter range overriding the y offset of the wind database."""
def __init__(self, offset_positions, distribution):
"""Constructor.
Args:
offset_positions: A list of offset positions [m].
distribution: Parameter for specifying probability distribution.
"""
super(WindDatabaseYOffsetParameterRange, self).__init__(
'Wind Database Y offset [m]', offset_positions, distribution)
def GetOverrides(self, value):
return {
'sim': {
'phys_sim': {
'wind_database_y_offset': value
}
}
}
class WindVeerDegParameterRange(ParameterRange):
"""A parameter range overriding the wind veer."""
def __init__(self, wind_directions, distribution, start_height_agl=100.0,
end_height_agl=400.0):
"""Constructor.
Args:
wind_directions: A list of changes in wind direction [deg].
distribution: Parameter for specifying probability distribution.
start_height_agl: Height [m] above-ground-level at which to start
the direction change.
end_height_agl: Height [m] above-ground-level at which to end
the direction change.
"""
label = 'Wind Veer [deg] from %.f to %.f [m] AGL' % (start_height_agl,
end_height_agl)
super(WindVeerDegParameterRange, self).__init__(label, wind_directions,
distribution)
self._start_height = start_height_agl
self._end_height = end_height_agl
def GetOverrides(self, value):
return {
'sim': {
'phys_sim': {
'wind_veer': numpy.deg2rad(value),
'wind_veer_start_height_agl': self._start_height,
'wind_veer_end_height_agl': self._end_height,
}
}
}
class WindShearExponentParameterRange(ParameterRange):
"""A parameter range overriding the wind shear exponent."""
def __init__(self, wind_shear_exponents):
"""Constructor.
Args:
wind_shear_exponents: A list of exponents defining this parameter range.
"""
super(WindShearExponentParameterRange, self).__init__(
'Wind Shear [#]', wind_shear_exponents, distribution=None)
def GetOverrides(self, value):
return {
'sim': {
'phys_sim': {
'wind_shear_exponent': value,
}
| |
832, 656, 380, 300, 300, 206, 187, 175,
142, 465, 206, 271, 468, 215, 560, 83, 215, 83, 215, 215, 83, 175,
215, 83, 83, 111, 206, 756, 559, 756, 1367, 206, 559, 1015, 559, 559,
946, 1015, 548, 559, 756, 1043, 756, 698, 159, 414, 308, 458, 997,
663, 663, 347, 39, 755, 838, 323, 755, 323, 159, 159, 717, 159, 21,
41, 128, 516, 159, 717, 71, 870, 755, 159, 740, 717, 374, 516, 740,
51, 148, 335, 148, 335, 791, 120, 364, 335, 335, 51, 120, 251, 538,
251, 971, 1395, 538, 78, 178, 538, 538, 918, 129, 918, 129, 538, 538,
656, 129, 538, 538, 129, 538, 1051, 538, 128, 838, 931, 998, 823,
1095, 334, 870, 334, 367, 550, 1061, 498, 745, 832, 498, 745, 716,
498, 498, 128, 997, 832, 716, 832, 130, 642, 616, 497, 432, 432, 432,
432, 642, 159, 432, 46, 230, 788, 160, 230, 478, 46, 693, 103, 920,
230, 589, 643, 160, 616, 432, 165, 165, 583, 592, 838, 784, 583, 710,
6, 583, 583, 6, 35, 230, 838, 592, 710, 6, 589, 230, 838, 30, 592,
583, 6, 583, 6, 6, 583, 30, 30, 6, 375, 375, 99, 36, 1158, 425, 662,
417, 681, 364, 375, 1025, 538, 822, 669, 893, 538, 538, 450, 409,
632, 527, 632, 563, 632, 527, 550, 71, 698, 550, 39, 550, 514, 537,
514, 537, 111, 41, 173, 592, 173, 648, 173, 173, 173, 1011, 514, 173,
173, 514, 166, 648, 355, 161, 166, 648, 497, 327, 327, 550, 650, 21,
425, 605, 555, 103, 425, 605, 842, 836, 1011, 636, 138, 756, 836,
756, 756, 353, 1011, 636, 636, 1158, 741, 741, 842, 756, 741, 1011,
677, 1011, 770, 366, 306, 488, 920, 920, 665, 775, 502, 500, 775,
775, 648, 364, 833, 207, 13, 93, 500, 364, 500, 665, 500, 93, 295,
183, 1293, 313, 272, 313, 279, 303, 93, 516, 93, 1013, 381, 6, 93,
93, 303, 259, 643, 168, 673, 230, 1261, 230, 230, 673, 1060, 1079,
1079, 550, 741, 741, 590, 527, 741, 741, 442, 741, 442, 848, 741,
590, 925, 219, 527, 925, 335, 442, 590, 239, 590, 590, 590, 239, 527,
239, 1033, 230, 734, 241, 741, 230, 549, 548, 1015, 1015, 32, 36,
433, 465, 724, 465, 73, 73, 73, 465, 808, 73, 592, 1430, 250, 154,
154, 250, 538, 353, 353, 353, 353, 353, 175, 194, 206, 538, 632,
1163, 960, 175, 175, 538, 452, 632, 1163, 175, 538, 960, 194, 175,
194, 632, 960, 632, 94, 632, 461, 960, 1163, 1163, 461, 632, 960,
755, 707, 105, 382, 625, 382, 382, 784, 707, 871, 559, 387, 387, 871,
784, 559, 784, 88, 36, 570, 314, 1028, 975, 335, 335, 398, 573, 573,
573, 21, 215, 562, 738, 612, 424, 21, 103, 788, 870, 912, 23, 186,
757, 73, 818, 23, 73, 563, 952, 262, 563, 137, 262, 1022, 952, 137,
1273, 442, 952, 604, 137, 308, 384, 913, 235, 325, 695, 398, 95, 668,
776, 713, 309, 691, 22, 10, 364, 682, 682, 578, 481, 1252, 1072,
1252, 825, 578, 825, 1072, 1149, 592, 273, 387, 273, 427, 155, 1204,
50, 452, 50, 1142, 50, 367, 452, 1142, 611, 367, 50, 50, 367, 50,
1675, 99, 367, 50, 1501, 1099, 830, 681, 689, 917, 1089, 453, 425,
235, 918, 538, 550, 335, 161, 387, 859, 324, 21, 838, 859, 1123, 21,
723, 21, 335, 335, 206, 21, 364, 1426, 21, 838, 838, 335, 364, 21,
21, 859, 920, 838, 838, 397, 81, 639, 397, 397, 588, 933, 933, 784,
222, 830, 36, 36, 222, 1251, 266, 36, 146, 266, 366, 581, 605, 366,
22, 966, 681, 681, 433, 730, 1013, 550, 21, 21, 938, 488, 516, 21,
21, 656, 420, 323, 323, 323, 327, 323, 918, 581, 581, 830, 361, 830,
364, 259, 364, 496, 496, 364, 691, 705, 691, 475, 427, 1145, 600,
179, 427, 527, 749, 869, 689, 335, 347, 220, 298, 689, 1426, 183,
554, 55, 832, 550, 550, 165, 770, 957, 67, 1386, 219, 683, 683, 355,
683, 355, 355, 738, 355, 842, 931, 266, 325, 349, 256, 1113, 256,
423, 960, 554, 554, 325, 554, 508, 22, 142, 22, 508, 916, 767, 55,
1529, 767, 55, 1286, 93, 972, 550, 931, 1286, 1286, 972, 93, 1286,
1392, 890, 93, 1286, 93, 1286, 972, 374, 931, 890, 808, 779, 975,
975, 175, 173, 4, 681, 383, 1367, 173, 383, 1367, 383, 173, 175, 69,
238, 146, 238, 36, 148, 888, 238, 173, 238, 148, 238, 888, 185, 925,
925, 797, 925, 815, 925, 469, 784, 289, 784, 925, 797, 925, 925,
1093, 925, 925, 925, 1163, 797, 797, 815, 925, 1093, 784, 636, 663,
925, 187, 922, 316, 1380, 709, 916, 916, 187, 355, 948, 916, 187,
916, 916, 948, 948, 916, 355, 316, 316, 334, 300, 1461, 36, 583,
1179, 699, 235, 858, 583, 699, 858, 699, 1189, 1256, 1189, 699, 797,
699, 699, 699, 699, 427, 488, 427, 488, 175, 815, 656, 656, 150, 322,
465, 322, 870, 465, 1099, 582, 665, 767, 749, 635, 749, 600, 1448,
36, 502, 235, 502, 355, 502, 355, 355, 355, 172, 355, 355, 95, 866,
425, 393, 1165, 42, 42, 42, 393, 939, 909, 909, 836, 552, 424, 1333,
852, 897, 1426, 1333, 1446, 1426, 997, 1011, 852, 1198, 55, 32, 239,
588, 681, 681, 239, 1401, 32, 588, 239, 462, 286, 1260, 984, 1160,
960, 960, 486, 828, 462, 960, 1199, 581, 850, 663, 581, 751, 581,
581, 1571, 252, 252, 1283, 264, 430, 264, 430, 430, 842, 252, 745,
21, 307, 681, 1592, 488, 857, 857, 1161, 857, 857, 857, 138, 374,
374, 1196, 374, 1903, 1782, 1626, 414, 112, 1477, 1040, 356, 775,
414, 414, 112, 356, 775, 435, 338, 1066, 689, 689, 1501, 689, 1249,
205, 689, 765, 220, 308, 917, 308, 308, 220, 327, 387, 838, 917, 917,
917, 220, 662, 308, 220, 387, 387, 220, 220, 308, 308, 308, 387,
1009, 1745, 822, 279, 554, 1129, 543, 383, 870, 1425, 241, 870, 241,
383, 716, 592, 21, 21, 592, 425, 550, 550, 550, 427, 230, 57, 483,
784, 860, 57, 308, 57, 486, 870, 447, 486, 433, 433, 870, 433, 997,
486, 443, 433, 433, 997, 486, 1292, 47, 708, 81, 895, 394, 81, 935,
81, 81, 81, 374, 986, 916, 1103, 1095, 465, 495, 916, 667, 1745, 518,
220, 1338, 220, 734, 1294, 741, 166, 828, 741, 741, 1165, 1371, 1371,
471, 1371, 647, 1142, 1878, 1878, 1371, 1371, 822, 66, 327, 158, 427,
427, 465, 465, 676, 676, 30, 30, 676, 676, 893, 1592, 93, 455, 308,
582, 695, 582, 629, 582, 85, 1179, 85, 85, 1592, 1179, 280, 1027,
681, 398, 1027, 398, 295, 784, 740, 509, 425, 968, 509, 46, 833, 842,
401, 184, 401, 464, 6, 1501, 1501, 550, 538, 883, 538, 883, 883, 883,
1129, 550, 550, 333, 689, 948, 21, 21, 241, 2557, 2094, 273, 308, 58,
863, 893, 1086, 409, 136, 1086, 592, 592, 830, 830, 883, 830, 277,
68, 689, 902, 277, 453, 507, 129, 689, 630, 664, 550, 128, 1626,
1626, 128, 902, 312, 589, 755, 755, 589, 755, 407, 1782, 589, 784,
1516, 1118, 407, 407, 1447, 589, 235, 755, 1191, 235, 235, 407, 128,
589, 1118, 21, 383, 1331, 691, 481, 383, 1129, 1129, 1261, 1104,
1378, 1129, 784, 1129, 1261, 1129, 947, 1129, 784, 784, 1129, 1129,
35, 1104, 35, 866, 1129, 1129, 64, 481, 730, 1260, 481, 970, 481,
481, 481, 481, 863, 481, 681, 699, 863, 486, 681, 481, 481, 55, 55,
235, 1364, 944, 632, 822, 401, 822, 952, 822, 822, 99, 550, 2240,
550, 70, 891, | |
#!/usr/bin/env python3.8
# Released under the MIT License. See LICENSE for details.
#
"""BallisticaCore server manager."""
from __future__ import annotations
import json
import os
import signal
import subprocess
import sys
import time
from pathlib import Path
from threading import Lock, Thread, current_thread
from typing import TYPE_CHECKING
# We make use of the bacommon and efro packages as well as site-packages
# included with our bundled Ballistica dist, so we need to add those paths
# before we import them.
sys.path += [
str(Path(Path(__file__).parent, 'dist', 'ba_data', 'python')),
str(Path(Path(__file__).parent, 'dist', 'ba_data', 'python-site-packages'))
]
from bacommon.servermanager import ServerConfig, StartServerModeCommand
from efro.dataclasses import dataclass_from_dict, dataclass_validate
from efro.error import CleanError
from efro.terminal import Clr
if TYPE_CHECKING:
from typing import Optional, List, Dict, Union, Tuple
from types import FrameType
from bacommon.servermanager import ServerCommand
VERSION_STR = '1.2'
# Version history:
# 1.2:
# Added optional --help arg
# Added --config arg for setting config path and --root for ba_root path
# Added noninteractive mode and --interactive/--noninteractive args to
# explicitly specify
# Added explicit control for auto-restart: --no-auto-restart
# Config file is now reloaded each time server binary is restarted; no more
# need to bring down server wrapper to pick up changes
# Now automatically restarts server binary when config file is modified
# (use --no-config-auto-restart to disable that behavior)
# 1.1.1:
# Switched config reading to use efro.dataclasses.dataclass_from_dict()
# 1.1.0:
# Added shutdown command
# Changed restart to default to immediate=True
# Added clean_exit_minutes, unclean_exit_minutes, and idle_exit_minutes
# 1.0.0:
# Initial release
class ServerManagerApp:
"""An app which manages BallisticaCore server execution.
Handles configuring, launching, re-launching, and otherwise
managing BallisticaCore operating in server mode.
"""
# How many seconds we wait after asking our subprocess to do an immediate
# shutdown before bringing down the hammer.
IMMEDIATE_SHUTDOWN_TIME_LIMIT = 5.0
def __init__(self) -> None:
self._config_path = 'config.yaml'
self._user_provided_config_path = False
self._config = ServerConfig()
self._ba_root_path = os.path.abspath('dist/ba_root')
self._interactive = sys.stdin.isatty()
self._wrapper_shutdown_desired = False
self._done = False
self._subprocess_commands: List[Union[str, ServerCommand]] = []
self._subprocess_commands_lock = Lock()
self._subprocess_force_kill_time: Optional[float] = None
self._auto_restart = True
self._config_auto_restart = True
self._config_mtime: Optional[float] = None
self._last_config_mtime_check_time: Optional[float] = None
self._should_report_subprocess_error = False
self._running = False
self._interpreter_start_time: Optional[float] = None
self._subprocess: Optional[subprocess.Popen[bytes]] = None
self._subprocess_launch_time: Optional[float] = None
self._subprocess_sent_config_auto_restart = False
self._subprocess_sent_clean_exit = False
self._subprocess_sent_unclean_exit = False
self._subprocess_thread: Optional[Thread] = None
self._subprocess_exited_cleanly: Optional[bool] = None
# This may override the above defaults.
self._parse_command_line_args()
# Do an initial config-load. If the config is invalid at this point
# we can cleanly die (we're more lenient later on reloads).
self.load_config(strict=True, print_confirmation=False)
@property
def config(self) -> ServerConfig:
"""The current config for the app."""
return self._config
@config.setter
def config(self, value: ServerConfig) -> None:
dataclass_validate(value)
self._config = value
def _prerun(self) -> None:
"""Common code at the start of any run."""
# Make sure we don't call run multiple times.
if self._running:
raise RuntimeError('Already running.')
self._running = True
dbgstr = 'debug' if __debug__ else 'opt'
print(
f'{Clr.CYN}{Clr.BLD}BallisticaCore server manager {VERSION_STR}'
f' starting up ({dbgstr} mode)...{Clr.RST}',
flush=True)
# Python will handle SIGINT for us (as KeyboardInterrupt) but we
# need to register a SIGTERM handler so we have a chance to clean
# up our subprocess when someone tells us to die. (and avoid
# zombie processes)
signal.signal(signal.SIGTERM, self._handle_term_signal)
# During a run, we make the assumption that cwd is the dir
# containing this script, so make that so. Up until now that may
# not be the case (we support being called from any location).
os.chdir(os.path.abspath(os.path.dirname(__file__)))
# Fire off a background thread to wrangle our server binaries.
self._subprocess_thread = Thread(target=self._bg_thread_main)
self._subprocess_thread.start()
def _postrun(self) -> None:
"""Common code at the end of any run."""
print(f'{Clr.CYN}Server manager shutting down...{Clr.RST}', flush=True)
assert self._subprocess_thread is not None
if self._subprocess_thread.is_alive():
print(f'{Clr.CYN}Waiting for subprocess exit...{Clr.RST}',
flush=True)
# Mark ourselves as shutting down and wait for the process to wrap up.
self._done = True
self._subprocess_thread.join()
# If there's a server error we should care about, exit the
# entire wrapper uncleanly.
if self._should_report_subprocess_error:
raise CleanError('Server subprocess exited uncleanly.')
def run(self) -> None:
"""Do the thing."""
if self._interactive:
self._run_interactive()
else:
self._run_noninteractive()
def _run_noninteractive(self) -> None:
"""Run the app loop to completion noninteractively."""
self._prerun()
try:
while True:
time.sleep(1.234)
except KeyboardInterrupt:
# Gracefully bow out if we kill ourself via keyboard.
pass
except SystemExit:
# We get this from the builtin quit(), our signal handler, etc.
# Need to catch this so we can clean up, otherwise we'll be
# left in limbo with our process thread still running.
pass
self._postrun()
def _run_interactive(self) -> None:
"""Run the app loop to completion interactively."""
import code
self._prerun()
# Print basic usage info for interactive mode.
print(
f"{Clr.CYN}Interactive mode enabled; use the 'mgr' object"
f' to interact with the server.\n'
f"Type 'help(mgr)' for more information.{Clr.RST}",
flush=True)
context = {'__name__': '__console__', '__doc__': None, 'mgr': self}
# Enable tab-completion if possible.
self._enable_tab_completion(context)
# Now just sit in an interpreter.
# TODO: make it possible to use IPython if the user has it available.
try:
self._interpreter_start_time = time.time()
code.interact(local=context, banner='', exitmsg='')
except SystemExit:
# We get this from the builtin quit(), our signal handler, etc.
# Need to catch this so we can clean up, otherwise we'll be
# left in limbo with our process thread still running.
pass
except BaseException as exc:
print(
f'{Clr.SRED}Unexpected interpreter exception:'
f' {exc} ({type(exc)}){Clr.RST}',
flush=True)
self._postrun()
def cmd(self, statement: str) -> None:
"""Exec a Python command on the current running server subprocess.
Note that commands are executed asynchronously and no status or
return value is accessible from this manager app.
"""
if not isinstance(statement, str):
raise TypeError(f'Expected a string arg; got {type(statement)}')
with self._subprocess_commands_lock:
self._subprocess_commands.append(statement)
self._block_for_command_completion()
def _block_for_command_completion(self) -> None:
# Ideally we'd block here until the command was run so our prompt would
# print after it's results. We currently don't get any response from
# the app so the best we can do is block until our bg thread has sent
# it. In the future we can perhaps add a proper 'command port'
# interface for proper blocking two way communication.
while True:
with self._subprocess_commands_lock:
if not self._subprocess_commands:
break
time.sleep(0.1)
# One last short delay so if we come out *just* as the command is sent
# we'll hopefully still give it enough time to process/print.
time.sleep(0.1)
def screenmessage(self,
message: str,
color: Optional[Tuple[float, float, float]] = None,
clients: Optional[List[int]] = None) -> None:
"""Display a screen-message.
This will have no name attached and not show up in chat history.
They will show up in replays, however (unless clients is passed).
"""
from bacommon.servermanager import ScreenMessageCommand
self._enqueue_server_command(
ScreenMessageCommand(message=message, color=color,
clients=clients))
def chatmessage(self,
message: str,
clients: Optional[List[int]] = None) -> None:
"""Send a chat message from the server.
This will have the server's name attached and will be logged
in client chat windows, just like other chat messages.
"""
from bacommon.servermanager import ChatMessageCommand
self._enqueue_server_command(
ChatMessageCommand(message=message, clients=clients))
def clientlist(self) -> None:
"""Print a list of connected clients."""
from bacommon.servermanager import ClientListCommand
self._enqueue_server_command(ClientListCommand())
self._block_for_command_completion()
def kick(self, client_id: int, ban_time: Optional[int] = None) -> None:
"""Kick the client with the provided id.
If ban_time is provided, the client will be banned for that
length of time in seconds. If it is None, ban duration will
be determined automatically. Pass 0 or a negative number for no
ban time.
"""
from bacommon.servermanager import KickCommand
self._enqueue_server_command(
KickCommand(client_id=client_id, ban_time=ban_time))
def restart(self, immediate: bool = True) -> None:
"""Restart the server subprocess.
By default, the current server process will exit immediately.
If 'immediate' is passed as False, however, it will instead exit at
the next clean transition point (the end of a series, etc).
"""
from bacommon.servermanager import ShutdownCommand, ShutdownReason
self._enqueue_server_command(
ShutdownCommand(reason=ShutdownReason.RESTARTING,
immediate=immediate))
# If we're asking for an immediate restart but don't get one within
# the grace period, bring down the hammer.
if immediate:
self._subprocess_force_kill_time = (
time.time() + self.IMMEDIATE_SHUTDOWN_TIME_LIMIT)
def shutdown(self, immediate: bool = True) -> None:
"""Shut down the server subprocess and exit the wrapper.
By default, the current server process will exit immediately.
If 'immediate' is passed as False, however, it will instead exit at
the next clean transition point (the end of a series, etc).
| |
data_models.Vip(subnet_id=t_constants.MOCK_SUBNET_ID,
network_id=t_constants.MOCK_NETWORK_ID)
fake_lb = data_models.LoadBalancer(id='1', vip=fake_lb_vip,
project_id='test-project')
vip = self.driver.allocate_vip(fake_lb)
exp_create_port_call = {
'port': {
'name': 'octavia-lb-1',
'network_id': t_constants.MOCK_NETWORK_ID,
'device_id': 'lb-1',
'device_owner': allowed_address_pairs.OCTAVIA_OWNER,
'admin_state_up': False,
'tenant_id': 'test-project',
'fixed_ips': [{'subnet_id': t_constants.MOCK_SUBNET_ID}]
}
}
create_port.assert_called_once_with(exp_create_port_call)
self.assertIsInstance(vip, data_models.Vip)
self.assertEqual(t_constants.MOCK_IP_ADDRESS, vip.ip_address)
self.assertEqual(t_constants.MOCK_SUBNET_ID, vip.subnet_id)
self.assertEqual(t_constants.MOCK_PORT_ID, vip.port_id)
self.assertEqual(fake_lb.id, vip.load_balancer_id)
def test_unplug_vip_errors_when_update_port_cant_find_port(self):
lb = dmh.generate_load_balancer_tree()
list_ports = self.driver.neutron_client.list_ports
show_subnet = self.driver.neutron_client.show_subnet
show_subnet.return_value = t_constants.MOCK_SUBNET
port1 = t_constants.MOCK_NEUTRON_PORT['port']
port2 = {
'id': '4', 'network_id': '3', 'fixed_ips':
[{'ip_address': '10.0.0.2'}]
}
list_ports.return_value = {'ports': [port1, port2]}
update_port = self.driver.neutron_client.update_port
update_port.side_effect = neutron_exceptions.PortNotFoundClient
self.assertRaises(network_base.UnplugVIPException,
self.driver.unplug_vip, lb, lb.vip)
def test_unplug_vip_errors_when_update_port_fails(self):
lb = dmh.generate_load_balancer_tree()
show_subnet = self.driver.neutron_client.show_subnet
show_subnet.return_value = t_constants.MOCK_SUBNET
port1 = t_constants.MOCK_NEUTRON_PORT['port']
port2 = {
'id': '4', 'network_id': '3', 'fixed_ips':
[{'ip_address': '10.0.0.2'}]
}
list_ports = self.driver.neutron_client.list_ports
list_ports.return_value = {'ports': [port1, port2]}
update_port = self.driver.neutron_client.update_port
update_port.side_effect = TypeError
self.assertRaises(network_base.UnplugVIPException,
self.driver.unplug_vip, lb, lb.vip)
def test_unplug_vip_errors_when_vip_subnet_not_found(self):
lb = dmh.generate_load_balancer_tree()
show_subnet = self.driver.neutron_client.show_subnet
show_subnet.side_effect = neutron_exceptions.NotFound
self.assertRaises(network_base.PluggedVIPNotFound,
self.driver.unplug_vip, lb, lb.vip)
def test_unplug_vip(self):
lb = dmh.generate_load_balancer_tree()
show_subnet = self.driver.neutron_client.show_subnet
show_subnet.return_value = t_constants.MOCK_SUBNET
update_port = self.driver.neutron_client.update_port
port1 = t_constants.MOCK_NEUTRON_PORT['port']
port2 = {
'id': '4', 'network_id': '3', 'fixed_ips':
[{'ip_address': '10.0.0.2'}]
}
list_ports = self.driver.neutron_client.list_ports
list_ports.return_value = {'ports': [port1, port2]}
get_port = self.driver.neutron_client.get_port
get_port.side_effect = neutron_exceptions.NotFound
self.driver.unplug_vip(lb, lb.vip)
self.assertEqual(len(lb.amphorae), update_port.call_count)
clear_aap = {'port': {'allowed_address_pairs': []}}
update_port.assert_has_calls([mock.call(port1.get('id'), clear_aap),
mock.call(port1.get('id'), clear_aap)])
def test_plug_network_when_compute_instance_cant_be_found(self):
net_id = t_constants.MOCK_NOVA_INTERFACE.net_id
network_attach = self.driver.compute.attach_network_or_port
network_attach.side_effect = nova_exceptions.NotFound(
404, message='Instance not found')
self.assertRaises(network_base.AmphoraNotFound,
self.driver.plug_network,
t_constants.MOCK_COMPUTE_ID, net_id)
def test_plug_network_when_network_cant_be_found(self):
net_id = t_constants.MOCK_NOVA_INTERFACE.net_id
network_attach = self.driver.compute.attach_network_or_port
network_attach.side_effect = nova_exceptions.NotFound(
404, message='Network not found')
self.assertRaises(network_base.NetworkException,
self.driver.plug_network,
t_constants.MOCK_COMPUTE_ID, net_id)
def test_plug_network_when_interface_attach_fails(self):
net_id = t_constants.MOCK_NOVA_INTERFACE.net_id
network_attach = self.driver.compute.attach_network_or_port
network_attach.side_effect = TypeError
self.assertRaises(network_base.PlugNetworkException,
self.driver.plug_network,
t_constants.MOCK_COMPUTE_ID, net_id)
def test_plug_network(self):
net_id = t_constants.MOCK_NOVA_INTERFACE.net_id
network_attach = self.driver.compute.attach_network_or_port
network_attach.return_value = t_constants.MOCK_NOVA_INTERFACE
oct_interface = self.driver.plug_network(
t_constants.MOCK_COMPUTE_ID, net_id)
exp_ips = [fixed_ip.get('ip_address')
for fixed_ip in t_constants.MOCK_NOVA_INTERFACE.fixed_ips]
actual_ips = [fixed_ip.ip_address
for fixed_ip in oct_interface.fixed_ips]
self.assertEqual(exp_ips, actual_ips)
self.assertEqual(t_constants.MOCK_COMPUTE_ID,
oct_interface.compute_id)
self.assertEqual(net_id, oct_interface.network_id)
def test_unplug_network_when_compute_port_cant_be_found(self):
net_id = t_constants.MOCK_NOVA_INTERFACE.net_id
list_ports = self.driver.neutron_client.list_ports
list_ports.return_value = {'ports': []}
self.assertRaises(network_base.NetworkNotFound,
self.driver.unplug_network,
t_constants.MOCK_COMPUTE_ID, net_id)
def test_unplug_network_when_list_ports_fails(self):
net_id = t_constants.MOCK_NOVA_INTERFACE.net_id
list_ports = self.driver.neutron_client.list_ports
list_ports.side_effect = Exception
self.assertRaises(network_base.NetworkException,
self.driver.unplug_network,
t_constants.MOCK_COMPUTE_ID, net_id)
def test_unplug_network(self):
list_ports = self.driver.neutron_client.list_ports
port1 = t_constants.MOCK_NEUTRON_PORT['port']
port2 = {
'id': '4', 'network_id': '3', 'fixed_ips':
[{'ip_address': '10.0.0.2'}]
}
list_ports.return_value = {'ports': [port1, port2]}
port_detach = self.driver.compute.detach_port
self.driver.unplug_network(t_constants.MOCK_COMPUTE_ID,
port2.get('network_id'))
port_detach.assert_called_once_with(
compute_id=t_constants.MOCK_COMPUTE_ID, port_id=port2.get('id'))
def test_update_vip(self):
listeners = [data_models.Listener(protocol_port=80, peer_port=1024,
protocol=constants.PROTOCOL_TCP),
data_models.Listener(protocol_port=443, peer_port=1025,
protocol=constants.PROTOCOL_TCP),
data_models.Listener(protocol_port=50, peer_port=1026,
protocol=constants.PROTOCOL_UDP)]
vip = data_models.Vip(ip_address='10.0.0.2')
lb = data_models.LoadBalancer(id='1', listeners=listeners, vip=vip)
list_sec_grps = self.driver.neutron_client.list_security_groups
list_sec_grps.return_value = {'security_groups': [{'id': 'secgrp-1'}]}
fake_rules = {
'security_group_rules': [
{'id': 'rule-80', 'port_range_max': 80, 'protocol': 'tcp'},
{'id': 'rule-22', 'port_range_max': 22, 'protocol': 'tcp'}
]
}
list_rules = self.driver.neutron_client.list_security_group_rules
list_rules.return_value = fake_rules
delete_rule = self.driver.neutron_client.delete_security_group_rule
create_rule = self.driver.neutron_client.create_security_group_rule
self.driver.update_vip(lb)
delete_rule.assert_called_once_with('rule-22')
expected_create_rule_1 = {
'security_group_rule': {
'security_group_id': 'secgrp-1',
'direction': 'ingress',
'protocol': 'tcp',
'port_range_min': 1024,
'port_range_max': 1024,
'ethertype': 'IPv4'
}
}
expected_create_rule_udp_peer = {
'security_group_rule': {
'security_group_id': 'secgrp-1',
'direction': 'ingress',
'protocol': 'tcp',
'port_range_min': 1026,
'port_range_max': 1026,
'ethertype': 'IPv4'
}
}
expected_create_rule_2 = {
'security_group_rule': {
'security_group_id': 'secgrp-1',
'direction': 'ingress',
'protocol': 'tcp',
'port_range_min': 1025,
'port_range_max': 1025,
'ethertype': 'IPv4'
}
}
expected_create_rule_3 = {
'security_group_rule': {
'security_group_id': 'secgrp-1',
'direction': 'ingress',
'protocol': 'tcp',
'port_range_min': 443,
'port_range_max': 443,
'ethertype': 'IPv4'
}
}
expected_create_rule_udp = {
'security_group_rule': {
'security_group_id': 'secgrp-1',
'direction': 'ingress',
'protocol': 'udp',
'port_range_min': 50,
'port_range_max': 50,
'ethertype': 'IPv4'
}
}
create_rule.assert_has_calls([mock.call(expected_create_rule_1),
mock.call(expected_create_rule_udp_peer),
mock.call(expected_create_rule_2),
mock.call(expected_create_rule_3),
mock.call(expected_create_rule_udp)],
any_order=True)
def test_update_vip_when_listener_deleted(self):
listeners = [data_models.Listener(protocol_port=80,
protocol=constants.PROTOCOL_TCP),
data_models.Listener(
protocol_port=443,
protocol=constants.PROTOCOL_TCP,
provisioning_status=constants.PENDING_DELETE),
data_models.Listener(
protocol_port=50, protocol=constants.PROTOCOL_UDP,
provisioning_status=constants.PENDING_DELETE)]
vip = data_models.Vip(ip_address='10.0.0.2')
lb = data_models.LoadBalancer(id='1', listeners=listeners, vip=vip)
list_sec_grps = self.driver.neutron_client.list_security_groups
list_sec_grps.return_value = {'security_groups': [{'id': 'secgrp-1'}]}
fake_rules = {
'security_group_rules': [
{'id': 'rule-80', 'port_range_max': 80, 'protocol': 'tcp'},
{'id': 'rule-22', 'port_range_max': 443, 'protocol': 'tcp'},
{'id': 'rule-udp-50', 'port_range_max': 50, 'protocol': 'tcp'}
]
}
list_rules = self.driver.neutron_client.list_security_group_rules
list_rules.return_value = fake_rules
delete_rule = self.driver.neutron_client.delete_security_group_rule
create_rule = self.driver.neutron_client.create_security_group_rule
self.driver.update_vip(lb)
delete_rule.assert_has_calls(
[mock.call('rule-22'), mock.call('rule-udp-50')])
self.assertTrue(create_rule.called)
def test_update_vip_when_no_listeners(self):
listeners = []
vip = data_models.Vip(ip_address='10.0.0.2')
lb = data_models.LoadBalancer(id='1', listeners=listeners, vip=vip)
list_sec_grps = self.driver.neutron_client.list_security_groups
list_sec_grps.return_value = {'security_groups': [{'id': 'secgrp-1'}]}
fake_rules = {
'security_group_rules': [
{'id': 'all-egress', 'protocol': None, 'direction': 'egress'},
{'id': 'ssh-rule', 'protocol': 'tcp', 'port_range_max': 22}
]
}
list_rules = self.driver.neutron_client.list_security_group_rules
list_rules.return_value = fake_rules
delete_rule = self.driver.neutron_client.delete_security_group_rule
self.driver.update_vip(lb)
delete_rule.assert_called_once_with('ssh-rule')
def test_update_vip_when_security_group_rule_deleted(self):
listeners = []
vip = data_models.Vip(ip_address='10.0.0.2')
lb = data_models.LoadBalancer(id='1', listeners=listeners, vip=vip)
list_sec_grps = self.driver.neutron_client.list_security_groups
list_sec_grps.return_value = {'security_groups': [{'id': 'secgrp-1'}]}
fake_rules = {
'security_group_rules': [
{'id': 'all-egress', 'protocol': None, 'direction': 'egress'},
{'id': 'ssh-rule', 'protocol': 'tcp', 'port_range_max': 22}
]
}
list_rules = self.driver.neutron_client.list_security_group_rules
list_rules.return_value = fake_rules
delete_rule = self.driver.neutron_client.delete_security_group_rule
delete_rule.side_effect = neutron_exceptions.NotFound
self.driver.update_vip(lb)
delete_rule.assert_called_once_with('ssh-rule')
def test_update_vip_when_security_group_missing(self):
listeners = []
vip = data_models.Vip(ip_address='10.0.0.2')
lb = data_models.LoadBalancer(id='1', listeners=listeners, vip=vip)
list_sec_grps = self.driver.neutron_client.list_security_groups
list_sec_grps.return_value = {'security_groups': []}
self.assertRaises(exceptions.MissingVIPSecurityGroup,
self.driver.update_vip,
lb)
@mock.patch('octavia.network.drivers.neutron.allowed_address_pairs.'
'AllowedAddressPairsDriver._update_security_group_rules')
def test_update_vip_for_delete_when_security_group_missing(self,
update_rules):
listeners = []
vip = data_models.Vip(ip_address='10.0.0.2')
lb = data_models.LoadBalancer(id='1', listeners=listeners, vip=vip)
list_sec_grps = self.driver.neutron_client.list_security_groups
list_sec_grps.return_value = {'security_groups': []}
self.driver.update_vip(lb, for_delete=True)
update_rules.assert_not_called()
def test_failover_preparation(self):
original_dns_integration_state = self.driver.dns_integration_enabled
self.driver.dns_integration_enabled = False
ports = {"ports": [
{"fixed_ips": [{"subnet_id": self.SUBNET_ID_1,
"ip_address": self.IP_ADDRESS_1}],
"id": self.FIXED_IP_ID_1, "network_id": self.NETWORK_ID_1},
{"fixed_ips": [{"subnet_id": self.SUBNET_ID_2,
"ip_address": self.IP_ADDRESS_2}],
"id": self.FIXED_IP_ID_2, "network_id": self.NETWORK_ID_2}]}
self.driver.neutron_client.list_ports.return_value = ports
self.driver.neutron_client.show_port = mock.Mock(
side_effect=self._failover_show_port_side_effect)
port_update = self.driver.neutron_client.update_port
amphora = data_models.Amphora(
id=self.AMPHORA_ID, load_balancer_id=self.LB_ID,
compute_id=self.COMPUTE_ID, status=self.ACTIVE,
lb_network_ip=self.LB_NET_IP, ha_port_id=self.HA_PORT_ID,
ha_ip=self.HA_IP)
self.driver.failover_preparation(amphora)
self.assertFalse(port_update.called)
self.driver.dns_integration_enabled = original_dns_integration_state
def test_failover_preparation_dns_integration(self):
ports = {"ports": [
{"fixed_ips": [{"subnet_id": self.SUBNET_ID_1,
"ip_address": self.IP_ADDRESS_1}],
"id": self.FIXED_IP_ID_1, "network_id": self.NETWORK_ID_1},
{"fixed_ips": [{"subnet_id": self.SUBNET_ID_2,
"ip_address": self.IP_ADDRESS_2}],
"id": self.FIXED_IP_ID_2, "network_id": self.NETWORK_ID_2}]}
original_dns_integration_state = self.driver.dns_integration_enabled
self.driver.dns_integration_enabled = True
self.driver.neutron_client.list_ports.return_value = ports
self.driver.neutron_client.show_port = mock.Mock(
side_effect=self._failover_show_port_side_effect)
port_update = self.driver.neutron_client.update_port
amphora = data_models.Amphora(
id=self.AMPHORA_ID, load_balancer_id=self.LB_ID,
compute_id=self.COMPUTE_ID, status=self.ACTIVE,
lb_network_ip=self.LB_NET_IP, ha_port_id=self.HA_PORT_ID,
ha_ip=self.HA_IP)
self.driver.failover_preparation(amphora)
port_update.assert_called_once_with(ports['ports'][1].get('id'),
{'port': {'dns_name': ''}})
self.driver.dns_integration_enabled = original_dns_integration_state
def _failover_show_port_side_effect(self, port_id):
if port_id == self.LB_NET_PORT_ID:
return {"fixed_ips": [{"subnet_id": self.SUBNET_ID_1,
"ip_address": self.IP_ADDRESS_1}],
"id": self.FIXED_IP_ID_1, "network_id": self.NETWORK_ID_1}
if port_id == self.HA_PORT_ID:
return {"fixed_ips": [{"subnet_id": self.SUBNET_ID_2,
"ip_address": self.IP_ADDRESS_2}],
"id": self.FIXED_IP_ID_2, "network_id": self.NETWORK_ID_2}
def test_plug_port(self):
port = mock.MagicMock()
port.id = self.PORT_ID
network_attach = self.driver.compute.attach_network_or_port
network_attach.return_value = t_constants.MOCK_NOVA_INTERFACE
amphora = data_models.Amphora(
id=self.AMPHORA_ID, load_balancer_id=self.LB_ID,
compute_id=self.COMPUTE_ID, status=self.ACTIVE,
lb_network_ip=self.LB_NET_IP, ha_port_id=self.HA_PORT_ID,
ha_ip=self.HA_IP)
self.driver.plug_port(amphora, port)
network_attach.assert_called_once_with(compute_id=amphora.compute_id,
network_id=None,
ip_address=None,
port_id=self.PORT_ID)
# NotFound cases
network_attach.side_effect = nova_exceptions.NotFound(
1, message='Instance')
self.assertRaises(network_base.AmphoraNotFound,
self.driver.plug_port,
amphora,
port)
network_attach.side_effect = nova_exceptions.NotFound(
1, message='Network')
self.assertRaises(network_base.NetworkNotFound,
self.driver.plug_port,
amphora,
port)
network_attach.side_effect = nova_exceptions.NotFound(
1, message='bogus')
self.assertRaises(network_base.PlugNetworkException,
self.driver.plug_port,
amphora,
port)
# Already plugged case should not raise an exception
network_attach.side_effect = nova_exceptions.Conflict(1)
self.driver.plug_port(amphora, port)
# Unknown error case
network_attach.side_effect = TypeError
self.assertRaises(network_base.PlugNetworkException,
self.driver.plug_port,
amphora,
port)
def test_get_network_configs(self):
amphora_mock = mock.MagicMock()
load_balancer_mock = mock.MagicMock()
vip_mock = mock.MagicMock()
amphora_mock.status = constants.DELETED
load_balancer_mock.amphorae = [amphora_mock]
show_port = self.driver.neutron_client.show_port
show_port.return_value = t_constants.MOCK_NEUTRON_PORT
fake_subnet = {'subnet': {
'id': t_constants.MOCK_SUBNET_ID,
'gateway_ip': t_constants.MOCK_IP_ADDRESS,
'cidr': t_constants.MOCK_CIDR}}
show_subnet = self.driver.neutron_client.show_subnet
show_subnet.return_value = fake_subnet
configs = self.driver.get_network_configs(load_balancer_mock)
self.assertEqual({}, configs)
vip_mock.port_id = 1
amphora_mock.id = 222
amphora_mock.status = constants.ACTIVE
amphora_mock.vrrp_port_id = 2
amphora_mock.vrrp_ip = "10.0.0.1"
amphora_mock.ha_port_id = 3
amphora_mock.ha_ip = "10.0.0.2"
load_balancer_mock.amphorae = [amphora_mock]
configs = self.driver.get_network_configs(load_balancer_mock)
self.assertEqual(1, len(configs))
config = configs[222]
# TODO(ptoohill): find a way to return different items for multiple
# calls to the same method, right now each call to show subnet
# will return the same values if a method happens to call it
# multiple times for different subnets. We should be able to verify
# different requests get different expected data.
expected_port_id = t_constants.MOCK_NEUTRON_PORT['port']['id']
self.assertEqual(expected_port_id, config.ha_port.id)
self.assertEqual(expected_port_id, config.vrrp_port.id)
expected_subnet_id = fake_subnet['subnet']['id']
self.assertEqual(expected_subnet_id, config.ha_subnet.id)
self.assertEqual(expected_subnet_id, config.vrrp_subnet.id)
@mock.patch('time.sleep')
def test_wait_for_port_detach(self, mock_sleep):
amphora = data_models.Amphora(
id=self.AMPHORA_ID, load_balancer_id=self.LB_ID,
compute_id=self.COMPUTE_ID, status=self.ACTIVE,
lb_network_ip=self.LB_NET_IP, ha_port_id=self.HA_PORT_ID,
ha_ip=self.HA_IP)
ports = {"ports": [
{"fixed_ips": [{"subnet_id": self.SUBNET_ID_1,
"ip_address": self.IP_ADDRESS_1}],
"id": self.FIXED_IP_ID_1, "network_id": self.NETWORK_ID_1},
{"fixed_ips": [{"subnet_id": self.SUBNET_ID_2,
"ip_address": self.IP_ADDRESS_2}],
"id": self.FIXED_IP_ID_2, "network_id": self.NETWORK_ID_2}]}
show_port_1_without_device_id = {"fixed_ips": [
{"subnet_id": self.SUBNET_ID_1, "ip_address": self.IP_ADDRESS_1}],
"id": self.FIXED_IP_ID_1, "network_id": self.NETWORK_ID_1,
"device_id": ''}
show_port_2_with_device_id = {"fixed_ips": [
{"subnet_id": self.SUBNET_ID_2, "ip_address": self.IP_ADDRESS_2}],
"id": self.FIXED_IP_ID_2, "network_id": self.NETWORK_ID_2,
"device_id": self.DEVICE_ID}
show_port_2_without_device_id = {"fixed_ips": [
{"subnet_id": self.SUBNET_ID_2, "ip_address": self.IP_ADDRESS_2}],
"id": self.FIXED_IP_ID_2, "network_id": self.NETWORK_ID_2,
"device_id": None}
self.driver.neutron_client.list_ports.return_value = ports
port_mock = mock.MagicMock()
port_mock.get = mock.Mock(
side_effect=[show_port_1_without_device_id,
show_port_2_with_device_id,
show_port_2_with_device_id,
show_port_2_without_device_id])
self.driver.neutron_client.show_port.return_value = port_mock
self.driver.wait_for_port_detach(amphora)
self.assertEqual(1, mock_sleep.call_count)
@mock.patch('time.time')
@mock.patch('time.sleep')
def test_wait_for_port_detach_timeout(self, mock_sleep, mock_time):
mock_time.side_effect = [1, 2, 6]
conf = oslo_fixture.Config(cfg.CONF)
conf.config(group="networking", port_detach_timeout=5)
amphora = data_models.Amphora(
id=self.AMPHORA_ID, load_balancer_id=self.LB_ID,
compute_id=self.COMPUTE_ID, status=self.ACTIVE,
lb_network_ip=self.LB_NET_IP, ha_port_id=self.HA_PORT_ID,
ha_ip=self.HA_IP)
ports = {"ports": [
{"fixed_ips": [{"subnet_id": self.SUBNET_ID_1,
"ip_address": self.IP_ADDRESS_1}],
"id": self.FIXED_IP_ID_1, "network_id": self.NETWORK_ID_1},
{"fixed_ips": [{"subnet_id": self.SUBNET_ID_2,
"ip_address": self.IP_ADDRESS_2}],
"id": self.FIXED_IP_ID_2, "network_id": self.NETWORK_ID_2}]}
show_port_1_with_device_id = {"fixed_ips": [
{"subnet_id": self.SUBNET_ID_2, "ip_address": self.IP_ADDRESS_2}],
"id": self.FIXED_IP_ID_2, "network_id": self.NETWORK_ID_2,
"device_id": self.DEVICE_ID}
self.driver.neutron_client.list_ports.return_value = ports
port_mock = mock.MagicMock()
| |
from PySide import QtGui, QtCore
from PIL import Image, ImageQt, ImageDraw
import os, json
import numpy
import svgwrite
#import PointCloud
from PointCloud import Point2, PointCloud, intersect_line
from gcode import Mach3 as Gc
import re
class Viewer(QtGui.QMainWindow):
def __init__(self, parameters, scale=Point2(1.0,1.0)):
super(Viewer, self).__init__()
#self.layout = QtGui.QBoxLayout(QtGui.QBoxLayout.TopToBottom, None)
self.layout = QtGui.QVBoxLayout()
self.setLayout(self.layout)
self.layout.setContentsMargins(0, 0, 0, 0)
self.parameters = parameters
self.multiWidget = QtGui.QScrollArea(self)
self.multiWidget.setSizePolicy(QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
self.bl = QtGui.QVBoxLayout(self.multiWidget)
#self.bn = QtGui.QPushButton(self, text="Hello")
#self.bn.setSizePolicy(QtGui.QSizePolicy.Expanding,
# QtGui.QSizePolicy.Expanding)
#self.layout.addWidget(self.bn)
self.imageLabel = QtGui.QLabel(self.multiWidget)
self.imageLabel.setSizePolicy(QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
self.imageLabel.setScaledContents(True)
self.bl.addWidget(self.imageLabel)
#self.imageLabel.setStyleSheet("border: 0px")
#self.imageLabel.setContentsMargins(0, 0, 0, 0)
#self.imageLabel.setText("nothing loaded")
self.imageLabel2 = QtGui.QLabel(self.multiWidget)
self.imageLabel2.setSizePolicy(QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Minimum)
self.imageLabel2.setScaledContents(False)
#self.imageLabel2.setStyleSheet("border: 0px")
#self.imageLabel2.setContentsMargins(0, 0, 0, 0)
self.bl.addWidget(self.imageLabel2)
self.imageLabel3 = QtGui.QLabel(self.multiWidget)
#self.imageLabel3.setSizePolicy(QtGui.QSizePolicy.Ignored,
# QtGui.QSizePolicy.Ignored)
#self.imageLabel3.setScaledContents(False)
#self.imageLabel3.setStyleSheet("border: 0px")
#self.imageLabel3.setContentsMargins(0, 0, 0, 0)
self.bl.addWidget(self.imageLabel3)
self.cutoffSlider = QtGui.QSlider(self.multiWidget, orientation=QtCore.Qt.Horizontal)
self.cutoffSlider.sliderReleased.connect(self.updateNailsImage)
self.bl.addWidget(self.cutoffSlider)
self.setCentralWidget(self.multiWidget)
#self.setCentralWidget(self.imageLabel)
self.setWindowTitle("NailedIt - analyser")
self.resize(600, 600)
self.scaleFactor = scale
self.deviation = []
self.debug_cnt = 1
self.minNailDist = 2.8 # keep this distance to the nails
self.timer = QtCore.QTimer(self)
self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.debug)
self.timer.setSingleShot(True)
#self.timer.start(0)
# menu
fileMenu = self.menuBar().addMenu("File")
fileMenu.addAction("Open", self.openFile)
fileMenu.addSeparator()
fileMenu.addAction("Export Nails SVG", self.saveNailsSVG)
fileMenu.addAction("Generate Gcode", self.generateGcode)
optionsMenu = self.menuBar().addMenu("Options")
self.showNailsAction = QtGui.QAction("show nails", optionsMenu, checkable=True, triggered=self.updateNailsImage)
optionsMenu.addAction(self.showNailsAction)
self.showOverlaps = QtGui.QAction("calculate overlaps", optionsMenu, checkable=True, triggered=self.updateNailsImage)
optionsMenu.addAction(self.showOverlaps)
self.reversePaths = QtGui.QAction("reverse path", optionsMenu, checkable=True, triggered=self.reverseTriggered)
optionsMenu.addAction(self.reversePaths)
optionsMenu.addAction("check nail distance", self.checkNails)
optionsMenu.addAction("calculate COG", self.calculateCOG)
#self.layout.addWidget(self.menu)
#self.layout.addWidget(self.scrollArea)
self.showImage(Image.new("RGB", (500,500)))
#if "image" in self.parameters:
# self.showImage(self.parameters["image"])
def reverseTriggered(self):
self.deviation = []
self.updateNailsImage()
def showImage(self, image, slot=0):
if slot == 0:
self.qim = ImageQt.ImageQt(image) # don't let python clean up the data
self.imageLabel.setPixmap(QtGui.QPixmap.fromImage(self.qim))
self.imageLabel.adjustSize()
elif slot == 1:
self.qim2 = ImageQt.ImageQt(image) # don't let python clean up the data
self.imageLabel2.setPixmap(QtGui.QPixmap.fromImage(self.qim2))
self.imageLabel2.adjustSize()
elif slot == 2:
self.qim3 = ImageQt.ImageQt(image) # don't let python clean up the data
self.imageLabel3.setPixmap(QtGui.QPixmap.fromImage(self.qim3))
self.imageLabel3.adjustSize()
def checkNails(self):
if "Nails" in self.parameters:
nails = self.parameters["Nails"]["3:nails"]
pc = PointCloud(10,10)
print "list", nails
pc.addFromList(nails)
print pc.p
img = self.parameters["image"]
draw = ImageDraw.Draw(img)
min_dist = 1000
for i,p in enumerate(pc.p):
np, d = pc.closestPoint(p.x, p.y, i)
min_dist = min(min_dist, d)
if d < self.minNailDist:
draw.rectangle((p.x-3, p.y - 3, p.x + 3, p.y + 3), outline=(255,0,0))
print "minDist:", min_dist * 1000.0 * self.parameters["Nails"]["2:parameters:"]["ppi"], "mm"
self.showImage(img)
def openFile(self):
filename = QtGui.QFileDialog.getOpenFileName(self, "Open Nailedit File", "./", "Nailedit (*.json)")[0]
if filename:
js = load_nailedit(filename)
if js:
self.parameters["Nails"] = js
print "num nails:", len(js["3:nails"]), "string length:", js['1:summary']["thread length"]
self.parameters["filename"] = filename
self.setWindowTitle("NailedIt - analyser (%s)"%os.path.basename(filename))
self.cutoffSlider.setMaximum(len(js["4:thread"]))
self.cutoffSlider.setSliderPosition(self.cutoffSlider.maximum())
self.deviation = []
self.updateNailsImage()
def updateDeviation(self):
if "Nails" in self.parameters and self.deviation:
nails = self.parameters["Nails"]
w = nails['2:parameters:']["proc_width"]
h = nails['2:parameters:']["proc_height"]
img = Image.new("RGB", (w, 100), (255,255,255))
draw = ImageDraw.Draw(img, "RGB")
for x in xrange(w):
d = int(float(x)/w * len(self.deviation))
v = float(self.deviation[d])/self.deviation[0] * 100
draw.line((x, 100, x, 100-v), fill=(255,0,0), width=1)
self.showImage(img, slot=1)
def debug(self):
#################################################################################################
if "Nails" in self.parameters:
js = self.parameters["Nails"]
nails = js["3:nails"]
path = js["4:thread"]
img = self.parameters["image"].copy()
inters = 0
up_to = self.debug_cnt
p4 = Point2(nails[path[up_to]][0], nails[path[up_to]][1])
p3 = Point2(nails[path[up_to-1]][0], nails[path[up_to-1]][1])
draw = ImageDraw.Draw(img, "RGBA")
if up_to > 1:
p1 = Point2(nails[path[0]][0], nails[path[0]][1])
for c in path[1:up_to]:
p2 = Point2(nails[c][0], nails[c][1])
s, t = intersect_line(p1, p2, p3, p4)
if 0 < s < 1 and 0 < t < 1:
inters += 1
draw.line((p1.x, p1.y, p2.x, p2.y), (0,255,0,255))
p1 = p2
draw.line((p3.x, p3.y, p4.x, p4.y), (255,0,0, 255), width=2)
self.debug_cnt += 1
self.showImage(img)
print "intersects", inters
self.timer.start(1000 if self.debug_cnt % 10 == 0 else 50)
def updateNailsImage(self):
if "Nails" in self.parameters:
nails = self.parameters["Nails"]
w = nails['2:parameters:']["proc_width"]
h = nails['2:parameters:']["proc_height"]
img = self.parameters["image"] = Image.new("RGB", (w, h))
trg = Image.open(nails['2:parameters:']["inputImagePath"])
if trg:
trg = trg.resize(img.size)
ret = draw_nails(nails, img, showNails=self.showNailsAction.isChecked(), targetImage=trg if not self.deviation else None, lastString=self.cutoffSlider.value(), reversed=self.reversePaths.isChecked())
if ret:
self.deviation = ret
self.showImage(self.parameters["image"])
self.updateDeviation()
if self.showOverlaps.isChecked():
ovl = self.parameters["overlap"] = Image.new("RGB", (w, h))
draw_overlap(nails, ovl, lastString=self.cutoffSlider.value(), reversed=self.reversePaths.isChecked())
self.showImage(ovl, slot=2)
def saveNailsSVG(self):
if "Nails" in self.parameters:
filename = QtGui.QFileDialog.getSaveFileName(self, "Export Nails", "./", "SVG (*.svg)")[0]
if filename:
save_nails_SVG(self.parameters["Nails"], filename, self.scaleFactor)
def generateGcode(self):
if not "Nails" in self.parameters:
return
filename = QtGui.QFileDialog.getSaveFileName(self, "Generate Gcode", "./", "gcode (*.tap)")[0]
if not filename:
return
js = self.parameters["Nails"]
nails = js["3:nails"]
path = js["4:thread"]
w = js["2:parameters:"]["proc_width"]
h = js["2:parameters:"]["proc_height"]
sf = Point2(1,1) * self.scaleFactor * 1000.0 * js["2:parameters:"]["ppi"] # pixels to millimeters
origin = Point2(0,0)
pc = PointCloud(1,1)
pc.addFromList(nails)
cp = pc.closestPoint(origin.x, origin.y)
print "origin", nails[cp[0]]
engine = Gc(nails, path[:self.cutoffSlider.value()], scaleFactor=sf, origin=pc.p[cp[0]])
code = engine.generateStringPath(os.path.basename(self.parameters["filename"]), startPosition=Point2(w*sf.x*.5, -5), minNailDistance=self.minNailDist)
#code = engine.generateStringPath(os.path.basename(self.parameters["filename"]), nails, path[:400], self.minNailDist, scaleFactor=sf, origin=Point2(0,0), startPosition=Point2(0.5, -0.1)*w)
spl = os.path.splitext(filename)
filename = spl[0]+"_string"+spl[1]
with open(filename, "w") as f:
f.write(code)
f.close()
print "written gcode to", filename
img = self.drawGcode(self.parameters["image"], code, Point2(1.0/sf.x,1.0/sf.y), Point2(0,0))
self.showImage(img)
code = engine.generateDrillPattern(os.path.basename(self.parameters["filename"]), -6.0)
filename = spl[0]+"_drills"+spl[1]
with open(filename, "w") as f:
f.write(code)
f.close()
print "written gcode to", filename
def calculateCOG(self):
nailWeight = 9.9 / 100 #grams per nail
threadWeightPerMeter = 40.0/1000 # g / m
canvas_weight = 838 # grams
if "Nails" in self.parameters:
js = self.parameters["Nails"]
w = js["2:parameters:"]["proc_width"]
h = js["2:parameters:"]["proc_height"]
sf = Point2(1, 1) * self.scaleFactor * 1000.0 * js["2:parameters:"]["ppi"] # pixels to millimeters
origin = Point2(0, 0)
pc = PointCloud(1,1)
pc.addFromList(js["3:nails"])
#cp = pc.closestPoint(origin.x, origin.y)
#origin = pc.p[cp[0]]
pc.translate(-origin.x, -origin.y)
pc.scale(sf.x, sf.y)
# cog nails
nails_cog = Point2(0,0)
nails_mass = nailWeight * len(pc.p)
for p in pc.p:
nails_cog += p
nails_cog = nails_cog / len(pc.p)
# cog thread
path = js["4:thread"]
cp = pc.p[path[0]]
totalThreadLen = 0
thread_cog = Point2(0,0)
for pid in path[1:]:
nxt = pc.p[pid]
l = cp.dist(nxt)
totalThreadLen += l
thread_cog += (cp+nxt)*0.5*l
cp = nxt
thread_cog /= totalThreadLen
thread_mass = totalThreadLen / 1000 * threadWeightPerMeter
# canvas cog
canvas_cog = Point2(float(js["2:parameters:"]["proc_width"])*sf.x, float(js["2:parameters:"]["proc_height"])*sf.y)*0.5
print "canvas:", canvas_weight, "g"
print "nails:", nails_mass, "g"
print "thread:", thread_mass, "g"
print "canvas cog:", canvas_cog
print "nails cog:", nails_cog
print "thread cog:", thread_cog
combined_cog = (canvas_cog*canvas_weight + nails_cog * nails_mass + thread_cog * thread_mass)
combined_cog /= canvas_weight + nails_mass + thread_mass
print "overall COG", combined_cog
def drawGcode(self, img, code, scaleFact, origin):
drw = ImageDraw.Draw(img)
mpx,mpy,mpz = 0,0,0
lines = code.split('\n')
for line in lines:
x = re.search(r"(Y)([0-9.-]+)", line)
x = float(x.group(2)) if x else mpx
y = re.search(r"(X)([0-9.-]+)", line)
y = float(y.group(2)) if y else mpy
z = re.search(r"(Z)([0-9.-]+)", line)
z = float(z.group(2)) if z else mpz
i = re.search(r"(J)([0-9.-]+)", line)
i = float(i.group(2)) if i else None
j = re.search(r"(I)([0-9.-]+)", line)
j = float(j.group(2)) if j else None
if line.startswith("G0 "):
drw.line((mpx * scaleFact.x + origin.x, mpy * scaleFact.y + origin.y,
x * scaleFact.x + origin.x, y * scaleFact.y + origin.y), (0,0,255))
mpx, mpy, mpz = x, y, z
elif line.startswith("G1 "):
drw.line((mpx * scaleFact.x + origin.x, mpy * scaleFact.y + origin.y,
x * scaleFact.x + origin.x, y * scaleFact.y + origin.y), (255,50,0))
mpx, mpy, mpz = x, y, z
elif line.startswith("G2 ") or line.startswith("G3 "):
r = Point2(Point2(i,j).length() * scaleFact.x, Point2(i,j).length() * scaleFact.y)
drw.arc(((mpx+i) * scaleFact.x + origin.x - abs(r.x), (mpy+j) * scaleFact.y + origin.y - abs(r.x),
(mpx+i) * scaleFact.x + origin.x + abs(r.x), (mpy+j) * scaleFact.y + origin.y + abs(r.x)), 0, 360, (255,0,0))
mpx, mpy, mpz = x, y, z
return img
def load_nailedit(filepath):
print 'loading "%s"'%filepath
with open(filepath, 'r') as f:
js = json.load(f)
f.close()
print 'done'
return js
def save_nails_SVG(nails, filename, scale):
svg = svgwrite.Drawing(filename, profile='tiny')
pnts = nails["3:nails"]
r = 1
ptmm = nails["2:parameters:"]["ppi"] * 1000
if "nailDiameter" in nails["2:parameters:"]:
r = nails["2:parameters:"]["nailDiameter"] * ptmm
for p in pnts:
svg.add(svg.circle((p[0]*ptmm*scale.x*svgwrite.mm, p[1]*ptmm*scale.y*svgwrite.mm), r*svgwrite.mm))
svg.save()
print "saved as ", filename
print "sc:", scale, "dim:", nails["2:parameters:"]["proc_width"]*ptmm*scale, "x", nails["2:parameters:"]["proc_height"]*ptmm*scale
def draw_nails(nails, img, showNails=True, lastString=10 ** 7, targetImage=None, reversed=False):
pnts = nails["3:nails"]
path = nails["4:thread"] if not reversed else nails["4:thread"][::-1]
params = nails["2:parameters:"]
backgroundCol = params["backgroundColor"]
if not isinstance(backgroundCol, list):
backgroundCol = (backgroundCol, backgroundCol, backgroundCol)
else:
backgroundCol = tuple(backgroundCol)
stringCol = params["threadColor"]
if len(stringCol) == 2:
stringCol = [stringCol[0], stringCol[0], stringCol[0], stringCol[1]]
print stringCol
# over sampling
mmpp = params["ppi"]/0.001 #mm per pixel
threadThickness = 0.3 # mm
oversampling = 3
w = params["proc_width"] * mmpp
h = params["proc_height"] * mmpp
iw = int(w / threadThickness * oversampling)
ih = int(h / threadThickness * oversampling)
img_hi = Image.new("RGB", (int(iw), | |
<reponame>vanreusVU/Procedural-Map-Generation
# Default Modules
from typing import List
from random import randrange
import copy
# Custom Modules
from color_constants import Color
from dungeon_tiles import Tile, Tiles
from utilities import Coordinate, checkAlignedBlocks, debugTile, globalToRelative, isWithinBounds
from path_finding import aStar
class DungeonPart():
'''
Parent dungeon part class.
Contains the neccesary variables needed to draw the DungeonParts in
<dungeon_defaults.py>.RogueLikeDefaults.__drawDungeonParts()
'''
def __init__(self, x : int, y : int) -> None:
'''Just crates the template variables
:param x: world position of the object in X axis
:type x: int
:param y: world position of the object in Y axis
:type y: int
'''
# Location of the pivot point (upper left corner)
# This will be used to align the parts location on the grid
self.pivot_loc = Coordinate(x,y)
# Tiles of the dungeon part. Mark the empty parts as Tiles.Ignore
self.tiles : List[List[Tile]] = []
return
def afterInit(self, dungeon_tiles: List[List[Tiles]]):
'''
Call this after creating the dungen_parts if you want to make any changes after the main init
Example in @Room Class with <experiment_one.py>
'''
return
class Door():
'''A simple door object'''
def __init__(self, x: int, y: int):
'''
:param x: relative location of the pivot (top left corner) of the room
:type x: int
:param y: relative location of the pivot (top left corner) of the room
:type y: int
'''
self.location = Coordinate(x,y)
class Room(DungeonPart):
'''
Creates a room from the given @height, @width, @color.
Pivot point is top left corner.
'''
# Max amount of tries to place a door
MAX_DOOR_PLACEMENT_TRIES = 500
def __init__(self, x: int, y: int, height: int, width: int, wall_color: Color = None):
'''
:param x: world position of the object in X axis
:type x: int
:param y: world position of the object in Y axis
:type y: int
:param height: heightof the room in tiles
:type height: int
:param width: width of the room in tiles
:type width: int
:param wall_color: overrides the Tiles.Wall's default color., defaults to None
:type wall_color: Color, optional
'''
DungeonPart.__init__(self, x, y)
# Size info
self.height = height
self.width = width
# Color
self.color = wall_color
# Create the room tiles
# Where the corner pieces are Tiles.WALL and inner pieces are Tiles.PATH
self.tiles = [[Tiles.WALL] * self.width for _ in range(self.height)]
for y in range(1,self.height - 1):
self.tiles[y][1: self.width - 1] = [Tiles.PATH] * (self.width - 2)
# Quick access for the doors.
self.doors : List[Door] = []
return
def afterInit(self, dungeon_tiles: List[List[Tiles]]):
'''
Part of DungeonPart
Load dungeon tiles
:param dungeon_tiles: Global dungeon tiles
:type dungeon_tiles: List[List[Tiles]]
'''
# Assign dungeon tiles
self.dungeon_tiles = dungeon_tiles
def addDoor(self, location : Coordinate):
''' Adds a door to the given relative loation at the room
:param location: relative location to place a door at
:type location: Coordinate
'''
# Check if the same door exists
for door in self.doors:
if door.location == location:
# Door already exists
return
# Add the door
self.doors.append(Door(location.X, location.Y))
self.tiles[location.Y][location.X] = Tiles.DOOR
def getCenter(self) -> Coordinate:
''' Get the world center of the room
:return: Center of the room
:rtype: Coordinate
'''
x = int(self.width/2) + self.pivot_loc.X
y = int(self.height/2) + self.pivot_loc.Y
return Coordinate(x,y)
def __loadDoors(self):
'''
Goes through the @self.tiles and crates Door object for each of the doors.
Appends to self.doors
'''
for y in range(len(self.tiles)):
for x in range(len(self.tiles[y])):
if self.tiles[y][x] == Tiles.DOOR:
self.doors.append(Door(x,y))
def canPlaceDoor(self, x : int, y : int) -> bool:
'''
Checks if the door is placeable at the given location.
Avoids placing doors on corner pieces, next to each other and places where the door will be blocked
To wall piece to not be a corner. It should have continuing pieces either along the x or y axis
C = piece to check
o = empty/none blocking tile
x = wall tile
Not corner cases:
case 1: case 2:
o x o o o o
o C o x C x
o x o o o o
Corner case:
case 1:
o x o
o C x
o o o
:param x: relative location to check
:type x: int
:param y: relative location to check
:type y: int
:return: if the door is placeable at the given location.
:rtype: bool
'''
# Check if the door is being blocked by another dungeon tile and also for corner pieces
world_aligned = checkAlignedBlocks(Coordinate(x + self.pivot_loc.X, y + self.pivot_loc.Y), self.dungeon_tiles, Tiles.BLOCKING_TILES, True)
world_check = (world_aligned.X == 2 and world_aligned.Y == 0) or (world_aligned.Y == 2 and world_aligned.X == 0)
# Check if the door is next to another door
door_aligned = checkAlignedBlocks(Coordinate(x, y), self.tiles, [Tiles.DOOR], False)
door_check = door_aligned.X + door_aligned.Y == 0
return world_check and door_check
def getWallTileLocations(self, room) -> List[Coordinate]:
'''
Returns an array of all the room locations of the given room
:param room: Room to get the walls locations of
:type room: Room
:return: List of wall locations
:rtype: List[Coordinate]
'''
wall_locations : List[Coordinate] = []
# Type casting
room : Room = room
for y in range(len(room.tiles)):
for x in range(len(room.tiles[y])):
if room.tiles[y][x] == Tiles.WALL:
wall_locations.append(Coordinate(x,y))
return wall_locations
def createRandomDoor(self) -> Door:
'''
Creates doors on random locations around the walls based on the @self.num_rooms
'''
# Number of tries
tries = 0
# Created door
door : Door = None
# Get all the wall locations and index them by adding them to an array
wall_locations : List[Coordinate] = self.getWallTileLocations(self)
# Select random door locations
while (tries < self.MAX_DOOR_PLACEMENT_TRIES):
random_loc = randrange(0, len(wall_locations))
check_loc = wall_locations[random_loc]
# Don't add door if the door is not placable or a door is already added to that location
if (self.canPlaceDoor(check_loc.X,check_loc.Y) == False or self.tiles[check_loc.Y][check_loc.X] == Tiles.DOOR):
tries += 1
continue
# Add door
door = Door(check_loc.X,check_loc.Y)
self.doors.append(door)
self.tiles[check_loc.Y][check_loc.X] = Tiles.DOOR
# Door placed, exit the loop
break
# Load doors from the self.tiles
self.__loadDoors()
return door
class CustomRoom(Room):
'''
A room where you create your custom room by giving the room scheme as input
'''
def __init__(self, x: int, y: int, room_layout : str):
'''
x = wall
o = walkable area
D = Door
:param x: world position of the object in X axis
:type x: int
:param y: world position of the object in Y axis
:type y: int
:param room_layout: room's layout in string. See the example below
:type room_layout: str
'''
example_room_layout = '''\
x x x x
x o o x
x o o D
x x x x
'''
DungeonPart.__init__(self, x, y)
# Seperates the string into 2d array and crates a new array based on the values
self.tiles = [[self.__layoutToTile(i) for i in line.split()] for line in room_layout.splitlines()]
# Quick access for the doors.
self.doors = []
# Load doors from the self.tiles
self.__loadDoors()
return
def __layoutToTile(self, layout_str : str) -> Tile:
'''
Converts the string layout elements to Tiles
x = wall
o = walkable area
D = Door
:param layout_str: multi line string
:type layout_str: str
:return: Tile equivalent of the string
:rtype: Tile
'''
if layout_str == "x":
return Tiles.WALL
elif layout_str == "o":
return Tiles.PATH
elif layout_str == "D":
return Tiles.DOOR
else:
return Tiles.IGNORE
class Corridor(DungeonPart):
'''
Base class to create corridors from the given @start_room to @end_room by using the A* pathfinding algorithm.
'''
def __init__(self, start_room : Room, end_room : Room, dungeon_tiles: List[List[Tiles]], color: Color = None):
'''
:param start: First room
:type start: Room
:param end: Connected room
:type end: Room
:param start: should avoid walls or not, default to True
:type start: Bool, optional
:param color: overrides the Tiles default color., defaults to None
:type color: Color, optional
'''
DungeonPart.__init__(self, 0, 0)
# Location info
# Start position
self.start_room : Room = start_room
# End position
self.end_room | |
# -*- coding: utf-8 -*-
from linepy import *
import json, time, random
from datetime import datetime, timedelta
from humanfriendly import format_timespan, format_size, format_number, format_length
import json, time, random, sys, json, codecs, threading, glob, re, string, os, requests, six, ast, urllib, urllib3, urllib.parse, traceback, atexit
from bs4 import BeautifulSoup
from googletrans import Translator
import youtube_dl
# KAPTEN =================
cl = LineClient()
#cl = LineClient(authToken='ENvLEuuZSEPB5jcXBrN4.wOkmirNWe41AVCDdjgw/za.OxD5+rSwCmyNiIBCkkcz2kXIrhNniUxjhq3Aama6SlI=')
cl = LineClient(id=' @gmail.com',passwd=' ')
ki = LineClient()
#ki = LineClient(authToken='<KEY>
#ki = LineClient(id=' @gmail.com',passwd='<PASSWORD>')
kk = LineClient()
#kk = LineClient(authToken='<KEY>
#kk = LineClient(id=' @gmail.com',passwd='<PASSWORD>')
kc = LineClient()
#kc = LineClient(authToken='<KEY>
#kc = LineClient(id=' @gmail.com',passwd='<PASSWORD>')
kd = LineClient()
#kd = LineClient(authToken='<KEY>
#kd = LineClient(id=' @<EMAIL>',passwd='<PASSWORD>')
ke = LineClient()
#ke = LineClient(authToken='<KEY>
#ke = LineClient(id=' @<EMAIL>',passwd='<PASSWORD>')
s1 = LineClient()
#s1 = LineClient(authToken='EN7ytt6EH97u00PNspA1.U4Mzj8TUJ1y+fkFO73MYiq.RDKAkypr+aSAfmB1a9Wt5ZrW7TUaO4VYMg/TrWUFlhc=')
s1 = LineClient(id=' @gmail.com',passwd=' ')
s2 = LineClient()
#s2 = LineClient(authToken='ENK5pwMHkOnOFoPbQla1.Z2jkQwGakxweNIuIsU0aCq.SoODfdUBbigpvdSgZK7sz9oSmkHd0v7MdAHeXTHNv8o=')
s2 = LineClient(id=' @<EMAIL>',passwd=' ')
s3 = LineClient()
#s3 = LineClient(authToken='ENGKBK4If8XdftknMIrb.Tj3/RJgOGm3n0NS61mh+wW.AFv5tsd3QIKga8RlZ4itMIjudvImax1I+88h5bLt+d8=')
s3 = LineClient(id=' @<EMAIL>',passwd=' ')
ehun = LineClient()
#ehun = LineClient(authToken='ENhO0vrJXOLTqtQx8dF6.+8gbl9AnS8wIpUhMeO50vG.E9Z2cfu/tIrPeNAnHYdbe/csdng20DtHaWEDPgeA2pM=')
#ehun = LineClient(id=' <EMAIL>',passwd='<PASSWORD>')
print("success=====Ketik Bottoken di Group nu untuk ambil token nya.")
msg_dict = {}
msg_dict1 = {}
poll = LinePoll(cl)
poll = LinePoll(ki)
poll = LinePoll(kk)
poll = LinePoll(kc)
poll = LinePoll(kd)
poll = LinePoll(ke)
poll = LinePoll(s1)
poll = LinePoll(s2)
poll = LinePoll(s3)
poll = LinePoll(ehun)
call = LineCall(cl)
call = LineCall(ki)
call = LineCall(kk)
call = LineCall(kc)
call = LineCall(kd)
call = LineCall(ke)
call = LineCall(s1)
call = LineCall(s2)
call = LineCall(s3)
call = LineCall(ehun)
mid = cl.profile.mid
Amid = ki.profile.mid
Bmid = kk.profile.mid
Cmid = kc.profile.mid
Dmid = kd.profile.mid
Emid = ke.profile.mid
Fmid = s1.profile.mid
Gmid = s2.profile.mid
Hmid = s3.profile.mid
Imid = ehun.profile.mid
ABC = [cl,ki,kk,kc,kd,ke,s1,s2,s3]
Bots = [mid,Amid,Bmid,Cmid,Dmid,Emid,Fmid,Gmid,Hmid,Imid]
bot = {
"u6d58abee35bdbc56834a366ef9498704":True,
"ua7fcb2b219a379609b7fb3474a3cf931":True,
"u3f25c990113b5bfd488986235481e7ee":True,
"u5a828c2119f0138d5abdc7432465be64":True,
"uae7cb431de479869810857b54de698c1":True,
"u067b4768dd8cf37b83c20d3efb9c969d":True,
"u5474dd4f5cf2ef3b97319093341dd9b6":True,
"ubb899927cb6e8f563f14a7e8ef79b221":True,
"ucf624aa968002975849e25224aed0071":True,
"uffc1812fd68db3c5a23ee1e6128e7456":True
}
Creator = {
"ub<PASSWORD>6<PASSWORD>f<PASSWORD>0a":True
}
admin = {
"u38150a898fd1b1de5472f898ead38050":True,
"ufa9d4904d35904fcbfc9b8830a87c9d6":True,
"u3690df5c29cff67fc3251aa22ad97a64":True,
"u7fd8cbb3aca386f044ef5d845e4398bd":True,
"uf0d11974793b860c3d1ef4e593841581":True,
"ub3808de9f7df35f57fb366d157f9790a":True
}
contact = cl.getProfile()
contact = ki.getProfile()
contact = kk.getProfile()
contact = kc.getProfile()
contact = kd.getProfile()
contact = ke.getProfile()
contact = s1.getProfile()
contact = s2.getProfile()
contact = s3.getProfile()
contact = ehun.getProfile()
responsename = cl.getProfile().displayName
responsename1 = ki.getProfile().displayName
responsename2 = kk.getProfile().displayName
responsename3 = kc.getProfile().displayName
responsename4 = ehun.getProfile().displayName
help ="""=================
By Ehun bot
==================
╔═══════════════
╠➩〘 Help 〙
╠➩〘 Help admin 〙
╠➩〘 Help Creator 〙
╠➩〘 Me 〙
╠➩〘 Invite 〙
╠➩〘 invit: mid 〙
╠➩〘 Jemput tag 〙
╠➩〘 Mid 〙
╠➩〘 Mid @ 〙
╠➩〘 Ofsider 〙
╠➩〘 Lihat 〙
╠➩〘 Id (id line) 〙
╠➩〘 Pic 〙
╠➩〘 Cover 〙
╠➩〘 Rtime 〙
╠➩〘 Kalender 〙
╠➩〘 Speed 〙
╠➩〘 Ginfo 〙
╠➩〘 Memlist 〙
╠➩〘 Glist 〙
╠➩〘 Creator 〙
╠➩〘 Adminlist 〙
╠➩〘 Banlist 〙
╚═══════════════
"""
help2 ="""=================
☄Help admin☄
==================
╔═══════════════
╠➩〘 Lihat 〙
╠➩〘 Check 〙
╠➩〘 Botadd @ 〙
╠➩〘 Botdel @ 〙
╠➩〘 K (on/off)(utk cek contact)
╠➩〘 J (on/off〙
╠➩〘 Join (capten harus di dlam 〙
╠➩〘 Bye 〙
╠➩〘 Left (Indukusir capten)〙
╠➩〘 Halo (induk undang bot〙
╠➩〘 * (Induk invite bot)〙
╠➩〘 Jemput @ (asisnen invite tag) 〙
╠➩〘 Hai @ (induk nvite tag) 〙
╠➩〘 Kick @ (kick tag semua member) 〙
╠➩〘 ? @ (kicktag)〙
╠➩〘 Sampah(iduk kcansel pendingan 〙
╠➩〘 Micdel(tag)〙
╠➩〘 Micdd (tag)〙
╠➩〘 Miclist 〙
╠➩〘 Mimic (on/off 〙
╠➩〘 Gn: 〙
╠➩〘 Sider 〙
╠➩〘 Ofsider 〙
╠➩〘 Tagall 〙
╠➩〘 On (protect on) 〙
╠➩〘 Off (protect off) 〙
╠➩〘 Namelock (on/off) 〙
╠➩〘 Qr (on/off) 〙
╠➩〘 Jcancel (on/off) 〙
╠➩〘 Cancel (on/off) 〙
╠➩〘 Iprotect (on/off) 〙
╠➩〘 pkick(on/of) 〙
╠➩〘 pcancel (on/off) 〙
╠➩〘 Pjoin(on/off) 〙
╠➩〘 Ban @〙
╠➩〘 Banall 〙
╠➩〘 Unban @ 〙
╠➩〘 Clear(Bebas kn banlist dan off smua protect)
╠➩〘 Kill 〙
╠➩〘 Kill ban 〙
╠➩〘 Clear invites 〙
╠➩〘 Clean invites 〙
╠➩〘 Respon on/off 〙
╠➩〘 Restart 〙
╚═══════════════
"""
help3 ="""=================
👉HELP CREATOR👈
==================
╔═══════════════
╠➩〘 Rom 〙
╠➩〘 Spam 〙
╠➩〘 Spm 〙
╠➩〘 Code 〙
╠➩〘 Addall(semua assis add member) 〙
╠➩〘 Add bot(kapten add bot) 〙
╠➩〘 Kill 〙
╠➩〘 Admin add @ 〙
╠➩〘 Admindel @ 〙
╠➩〘 Cancelgroup 〙
╠➩〘 Leave 〙
╠➩〘 Bangroup: 〙
╠➩〘 Delban: 〙
╠➩〘 Listban 〙
╠➩〘 My (on/kff) 〙
╠➩〘 Block @ (block tag) 〙
╠➩〘 Vm 〙
╠➩〘 Jemput @ (asisnen invite tag) 〙
╠➩〘 Hai @ (induk nvite tag) 〙
╠➩〘 Kick @ (kick tag semua member) 〙
╠➩〘 ? @ (kicktag)〙
╠➩〘 /bubar (solo induk kickall)〙
╠➩〘 Rx (:5 asiskickall)〙
╠➩〘 Sayang (kickall) 〙
╠➩〘 Sampah (Kancel)〙
╚═══════════════
"""
wait={
"mention":"║┝──────────────\n║│Yuk kak chat sini 🙋\n║╰❉ Jangan ngelamun😁\n╰━━━━━━━━━━━━━━━━\n ━━━━┅═❉ইई❉═┅━━━━",
"Respontag":"Hoi Jgn ngtag semm",
"comment":"Bot Auto Like ©By : Ehun Bots\nContact Me : 👉 line.me/ti/p/~sarehun",
"message":"Trimakasih kakak sudah add aku",
"message1":"Jangan add bot boss\nMaaf anda di blockir",
"Bot":True,
"autoAdd":True,
"AutoJoin":False,
"AutoJoinQr":True,
"LeaveRoom":True,
"autoBlock":False,
"AutoJoinCancel":False,
"memberscancel":7,
"members":1,
'invite':{},
'steal':{},
'gift':{},
'copy':{},
'likeOn':True,
'detectMention':True,
'detectMention1':True,
'kickMention':False,
"Timeline":True,
"commentOn":True,
"alwaysRead":True,
'sticker':False,
"wblack":False,
"dblack":{},
"blacklist":{},
"wblacklist":False,
"autoJoinTicket":True,
"qr":False,
"myqr":True,
"Sider":False,
"Contact":False,
"Sambutan":False,
"AutoKick":False,
"inviteprotect":False,
"protectcancel":False,
"protectjoin":False,
"pname":{},
"pro_name":{},
"lang":"JP",
"BlGroup":{}
}
cctv={
"cyduk":{},
"point":{},
"sidermem":{}
}
wait2={
"readPoint":{},
"readMember":{},
"setTime":{},
"ROM":{}
}
mimic={
"copy":False,
"copy2":False,
"status":False,
"target":{}
}
bl = {
'blacklist':{}
}
with open('bl.json', 'r') as fp:
bl = json.load(fp)
setTime = {}
setTime = wait2['setTime']
mulai = time.time()
def waktu(secs):
mins, secs = divmod(secs,60)
hours, mins = divmod(mins,60)
days, hours = divmod(hours,24)
month, day = divmod(days,30)
years, mpuponth = divmod(month,12)
return '\n╠ %02d Tahun\n╠ %02d Bulan\n╠ %02d Hari\n╠ %02d Jam\n╠ %02d Menit\n╠ %02d Detik」' %(years, month, days ,hours, mins,secs)
def sendMessage(to, text, contentMetadata={}, contentType=0):
mes = Message()
mes.to, mes._from = to, profile.mid
mes.text = text
mes.contentType, mes.contentMetadata = contentType, contentMetadata
if to not in messageReq:
messageReq[to] = -1
messageReq[to] += 1
def command(text):
pesan = text.lower()
if pesan.startswith():
cmd = pesan.replace()
else:
cmd = "command"
return cmd
def sendMessageWithMention(to, mid):
try:
aa = '{"S":"0","E":"3","M":'+json.dumps(mid)+'}'
text_ = '@x '
ehun.sendMessage(to, text_, contentMetadata={'MENTION':'{"MENTIONEES":['+aa+']}'}, contentType=0)
except Exception as error:
logError(error)
def siderMembers(to, mid):
try:
arrData = ""
textx = "╭━━━┅═❉ইई❉═┅━━━━\n║ Haii ".format(str(len(mid)))
arr = []
no = 1
num = 2
for i in mid:
mention = "@x\n"
slen = str(len(textx))
elen = str(len(textx) + len(mention) - 1)
arrData = {'S':slen, 'E':elen, 'M':i}
arr.append(arrData)
textx += mention+wait["mention"]
if no < len(mid):
no += 1
textx += "%i. " % (num)
num=(num+1)
else:
try:
no = "\n╚══[ {} ]".str(ehun.getGroup(to).name)
except:
no = "\n╚══[ Success ]"
ehun.sendMessage(to, textx, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
except:
ehun.sendMessage(to, "[ INFO ] Error :\n" + str(error))
def sendMention(to, mid, firstmessage, lastmessage):
try:
arrData = ""
text = "%s " %(str(firstmessage))
arr = []
mention = "@x "
slen = str(len(text))
elen = str(len(text) + len(mention) - 1)
arrData = {'S':slen, 'E':elen, 'M':mid}
arr.append(arrData)
text += mention + str(lastmessage)
ehun.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
except:
ehun.sendMessage(to, "[ INFO ] Error :\n" + str(error))
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
def ehunBot(op):
try:
if op.type == 55:
try:
group_id = op.param1
user_id = op.param2
subprocess.Popen('echo "'+ user_id+'|'+str(op.createdTime)+'" >> dataSeen/%s.txt' % group_id, shell=True, stdout=subprocess.PIPE, )
except:
pass
if op.type == 17:
if op.param2 in bl["blacklist"]:
for jj in bl["blacklist]:
try:
s3.kickoutFromGroup(op.param1,[jj])
except:
s2.kickoutFromGroup(op.param1,[jj])
except:
try:
s1.kickoutFromGroup(op.param1,[jj])
except:
try:
ke.kickoutFromGroup(op.param1,[jj])
except:
try:
kd.kickoutFromGroup(op.param1,[jj])
except:
try:
kc.kickoutFromGroup(op.param1,[jj])
except:
try:
kk.kickoutFromGroup(op.param1,[jj])
except:
try:
ki.kickoutFromGroup(op.param1,[jj])
except:
try:
cl.kickoutFromGroup(op.param1,[jj])
except:
pass
if op.type == 13:
if op.param3 in bl["blacklist"] and op.param2 in bl["blacklist"] and op.param2 not in Bots and op.param2 not in Creator and op.param2 not in admin:
group = ehun.getGroup(op.param1)
gMembMids = [contact.mid for contact in group.members]
matched_list = []
for tag in bl["blacklist"]:
matched_list+=filter(lambda str: str == tag, gMembMids)
if matched_list == []:
sendMention(op.param1, op.param2, "")
pass
for jj in matched_list:
try:
s3.cancelGroupInvitation(op.param1,[jj])
s3.kickoutFromGroup(op.param1,[op.param2])
except:
try:
s2.cancelGroupInvitation(op.param1,[jj])
s2.kickoutFromGroup(op.param1,[op.param2])
except:
try:
s1.cancelGroupInvitation(op.param1,[jj])
s1.kickoutFromGroup(op.param1,[op.param2])
except:
try:
ke.cancelGroupInvitation(op.param1,[jj])
ke.kickoutFromGroup(op.param1,[op.param2])
except:
try:
kd.cancelGroupInvitation(op.param1,[jj])
kd.kickoutFromGroup(op.param1,[op.param2])
except:
try:
kc.cancelGroupInvitation(op.param1,[jj])
kc.kickoutFromGroup(op.param1,[op.param2])
except:
try:
kk.cancelGroupInvitation(op.param1,[jj])
kk.kickoutFromGroup(op.param1,[op.param2])
except:
try:
ki.cancelGroupInvitation(op.param1,[jj])
ki.kickoutFromGroup(op.param1,[op.param2])
except:
try:
cl.cancelGroupInvitation(op.param1,[jj])
cl.kickoutFromGroup(op.param1,[op.param2])
except:
pass
#========================================
if op.type == 5:
if wait["autoAdd"] == True:
ehun.findAndAddContactsByMid(op.param1)
if(wait["message"]in[""," ","\n",None]):
pass
else:
ehun.sendText(op.param1,str(wait["message"]))
ehun.sendContact(op.param1,"ub3808de9f7df35f57fb366d157f9790a")
if op.type == 5:
if wait["autoBlock"] == True:
ehun.blockContact(op.param1)
if op.type == 13:
if op.param3 in Imid:
if op.param2 in Creator:
ehun.acceptGroupInvitation(op.param1)
if op.param3 in Imid:
if op.param2 in admin:
ehun.acceptGroupInvitation(op.param1)
if op.param3 in Imid:
if op.param2 in Bots:
ehun.acceptGroupInvitation(op.param1)
if op.type == 13:
if Imid in op.param3:
if wait["AutoJoinCancel"] == True:
G = ehun.getGroup(op.param1)
if len (G.members) <= wait["memberscancel"]:
ehun.acceptGroupInvitation(op.param1)
sendMention(op.param1, op.param2, "","\nTrimaksih Kak Invit aku\nDiGroup" + str(G.name) + "\nMaaf Member Kurang Dari 7 Orang")
ehun.sendMessage(op.param1, None, contentMetadata={'mid': 'ub3808de9f7df35f57fb366d157f9790a'})
ehun.leaveGroup(op.param1)
else:
ehun.acceptGroupInvitation(op.param1)
G = ehun.getGroup(op.param1)
G.preventJoinByTicket = False
ehun.updateGroup(G)
Ti = ehun.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
ke.acceptGroupInvitationByTicket(op.param1,Ti)
s1.acceptGroupInvitationByTicket(op.param1,Ti)
s2.acceptGroupInvitationByTicket(op.param1,Ti)
s3.acceptGroupInvitationByTicket(op.param1,Ti)
G.preventJoinByTicket = True
ehun.updateGroup(G)
sendMention(op.param1, op.param2, "","\nTrimaksih Kak Invit aku\nDiGroup" + str(G.name) + "\nSilah kn Ketik ☞Help☜ Untuk Bantuan☆\n☆Harap Gunakan Dengan Bijak ^_^ ☆")
pass
if op.type == 13:
if Imid in op.param3:
if wait["AutoJoin"] == True:
G = ehun.getGroup(op.param1)
if len(G.members) <= wait["members"]:
ehun.rejectGroupInvitation(op.param1)
else:
ehun.acceptGroupInvitation(op.param1)
list = [mid,Amid,Bmid,Cmid,Dmid,Emid,Fmid,Gmid,Hmid]
ehun.inviteIntoGroup(op.param1, list) #[mid,Amid,Bmid,Cmid,Dmid,Emid,Fmid,Gmid,Hmid])
cl.acceptGroupInvitation(op.param1)
ki.acceptGroupInvitation(op.param1)
kk.acceptGroupInvitation(op.param1)
kc.acceptGroupInvitation(op.param1)
kd.acceptGroupInvitation(op.param1)
ke.acceptGroupInvitation(op.param1)
s1.acceptGroupInvitation(op.param1)
s2.acceptGroupInvitation(op.param1)
s3.acceptGroupInvitation(op.param1)
pass
if Imid in op.param3:
if wait["AutoJoinQr"] == True:
G = ehun.getGroup(op.param1)
if len(G.members) <= wait["members"]:
ehun.rejectGroupInvitation(op.param1)
else:
ehun.acceptGroupInvitation(op.param1)
G = ehun.getGroup(op.param1)
G.preventJoinByTicket = False
ehun.updateGroup(G)
Ti = ehun.reissueGroupTicket(op.param1)
ehun.acceptGroupInvitationByTicket(op.param1,Ti)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
ke.acceptGroupInvitationByTicket(op.param1,Ti)
s1.acceptGroupInvitationByTicket(op.param1,Ti)
| |
:param str display_name: A filter to return only resources that match the entire display name given.
:param str lifecycle_details: A message describing the current state in more detail. For example, can be used to provide actionable information for a resource in Failed state.
:param Sequence[str] managed_list_types: List of cloudguard managed list types related to this rule
:param str recommendation: Recommendation for TargetDetectorRecipeDetectorRule
:param str resource_type: resource type of the configuration to which the rule is applied
:param str service_type: service type of the configuration to which the rule is applied
:param str state: The field life cycle state. Only one state can be provided. Default value for state is active. If no value is specified state is active.
:param str time_created: The date and time the target was created. Format defined by RFC3339.
:param str time_updated: The date and time the target was updated. Format defined by RFC3339.
"""
pulumi.set(__self__, "description", description)
pulumi.set(__self__, "details", details)
pulumi.set(__self__, "detector", detector)
pulumi.set(__self__, "detector_rule_id", detector_rule_id)
pulumi.set(__self__, "display_name", display_name)
pulumi.set(__self__, "lifecycle_details", lifecycle_details)
pulumi.set(__self__, "managed_list_types", managed_list_types)
pulumi.set(__self__, "recommendation", recommendation)
pulumi.set(__self__, "resource_type", resource_type)
pulumi.set(__self__, "service_type", service_type)
pulumi.set(__self__, "state", state)
pulumi.set(__self__, "time_created", time_created)
pulumi.set(__self__, "time_updated", time_updated)
@property
@pulumi.getter
def description(self) -> str:
"""
ResponderRule Description
"""
return pulumi.get(self, "description")
@property
@pulumi.getter
def details(self) -> 'outputs.GetTargetsTargetCollectionItemTargetDetectorRecipeEffectiveDetectorRuleDetailsResult':
"""
Details of ResponderRule.
"""
return pulumi.get(self, "details")
@property
@pulumi.getter
def detector(self) -> str:
"""
detector for the rule
"""
return pulumi.get(self, "detector")
@property
@pulumi.getter(name="detectorRuleId")
def detector_rule_id(self) -> str:
"""
The unique identifier of the detector rule
"""
return pulumi.get(self, "detector_rule_id")
@property
@pulumi.getter(name="displayName")
def display_name(self) -> str:
"""
A filter to return only resources that match the entire display name given.
"""
return pulumi.get(self, "display_name")
@property
@pulumi.getter(name="lifecycleDetails")
def lifecycle_details(self) -> str:
"""
A message describing the current state in more detail. For example, can be used to provide actionable information for a resource in Failed state.
"""
return pulumi.get(self, "lifecycle_details")
@property
@pulumi.getter(name="managedListTypes")
def managed_list_types(self) -> Sequence[str]:
"""
List of cloudguard managed list types related to this rule
"""
return pulumi.get(self, "managed_list_types")
@property
@pulumi.getter
def recommendation(self) -> str:
"""
Recommendation for TargetDetectorRecipeDetectorRule
"""
return pulumi.get(self, "recommendation")
@property
@pulumi.getter(name="resourceType")
def resource_type(self) -> str:
"""
resource type of the configuration to which the rule is applied
"""
return pulumi.get(self, "resource_type")
@property
@pulumi.getter(name="serviceType")
def service_type(self) -> str:
"""
service type of the configuration to which the rule is applied
"""
return pulumi.get(self, "service_type")
@property
@pulumi.getter
def state(self) -> str:
"""
The field life cycle state. Only one state can be provided. Default value for state is active. If no value is specified state is active.
"""
return pulumi.get(self, "state")
@property
@pulumi.getter(name="timeCreated")
def time_created(self) -> str:
"""
The date and time the target was created. Format defined by RFC3339.
"""
return pulumi.get(self, "time_created")
@property
@pulumi.getter(name="timeUpdated")
def time_updated(self) -> str:
"""
The date and time the target was updated. Format defined by RFC3339.
"""
return pulumi.get(self, "time_updated")
@pulumi.output_type
class GetTargetsTargetCollectionItemTargetDetectorRecipeEffectiveDetectorRuleDetailsResult(dict):
def __init__(__self__, *,
condition_groups: Sequence['outputs.GetTargetsTargetCollectionItemTargetDetectorRecipeEffectiveDetectorRuleDetailsConditionGroupResult'],
configurations: Sequence['outputs.GetTargetsTargetCollectionItemTargetDetectorRecipeEffectiveDetectorRuleDetailsConfigurationResult'],
is_configuration_allowed: bool,
is_enabled: bool,
labels: Sequence[str],
risk_level: str):
"""
:param Sequence['GetTargetsTargetCollectionItemTargetDetectorRecipeEffectiveDetectorRuleDetailsConditionGroupArgs'] condition_groups: Condition group corresponding to each compartment
:param Sequence['GetTargetsTargetCollectionItemTargetDetectorRecipeEffectiveDetectorRuleDetailsConfigurationArgs'] configurations: ResponderRule configurations
:param bool is_configuration_allowed: configuration allowed or not
:param bool is_enabled: Identifies state for ResponderRule
:param Sequence[str] labels: user defined labels for a detector rule
:param str risk_level: The Risk Level
"""
pulumi.set(__self__, "condition_groups", condition_groups)
pulumi.set(__self__, "configurations", configurations)
pulumi.set(__self__, "is_configuration_allowed", is_configuration_allowed)
pulumi.set(__self__, "is_enabled", is_enabled)
pulumi.set(__self__, "labels", labels)
pulumi.set(__self__, "risk_level", risk_level)
@property
@pulumi.getter(name="conditionGroups")
def condition_groups(self) -> Sequence['outputs.GetTargetsTargetCollectionItemTargetDetectorRecipeEffectiveDetectorRuleDetailsConditionGroupResult']:
"""
Condition group corresponding to each compartment
"""
return pulumi.get(self, "condition_groups")
@property
@pulumi.getter
def configurations(self) -> Sequence['outputs.GetTargetsTargetCollectionItemTargetDetectorRecipeEffectiveDetectorRuleDetailsConfigurationResult']:
"""
ResponderRule configurations
"""
return pulumi.get(self, "configurations")
@property
@pulumi.getter(name="isConfigurationAllowed")
def is_configuration_allowed(self) -> bool:
"""
configuration allowed or not
"""
return pulumi.get(self, "is_configuration_allowed")
@property
@pulumi.getter(name="isEnabled")
def is_enabled(self) -> bool:
"""
Identifies state for ResponderRule
"""
return pulumi.get(self, "is_enabled")
@property
@pulumi.getter
def labels(self) -> Sequence[str]:
"""
user defined labels for a detector rule
"""
return pulumi.get(self, "labels")
@property
@pulumi.getter(name="riskLevel")
def risk_level(self) -> str:
"""
The Risk Level
"""
return pulumi.get(self, "risk_level")
@pulumi.output_type
class GetTargetsTargetCollectionItemTargetDetectorRecipeEffectiveDetectorRuleDetailsConditionGroupResult(dict):
def __init__(__self__, *,
compartment_id: str,
condition: str):
"""
:param str compartment_id: The ID of the compartment in which to list resources.
"""
pulumi.set(__self__, "compartment_id", compartment_id)
pulumi.set(__self__, "condition", condition)
@property
@pulumi.getter(name="compartmentId")
def compartment_id(self) -> str:
"""
The ID of the compartment in which to list resources.
"""
return pulumi.get(self, "compartment_id")
@property
@pulumi.getter
def condition(self) -> str:
return pulumi.get(self, "condition")
@pulumi.output_type
class GetTargetsTargetCollectionItemTargetDetectorRecipeEffectiveDetectorRuleDetailsConfigurationResult(dict):
def __init__(__self__, *,
config_key: str,
data_type: str,
name: str,
value: str,
values: Sequence['outputs.GetTargetsTargetCollectionItemTargetDetectorRecipeEffectiveDetectorRuleDetailsConfigurationValueResult']):
"""
:param str config_key: Unique name of the configuration
:param str data_type: configuration data type
:param str name: configuration name
:param str value: configuration value
:param Sequence['GetTargetsTargetCollectionItemTargetDetectorRecipeEffectiveDetectorRuleDetailsConfigurationValueArgs'] values: List of configuration values
"""
pulumi.set(__self__, "config_key", config_key)
pulumi.set(__self__, "data_type", data_type)
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "value", value)
pulumi.set(__self__, "values", values)
@property
@pulumi.getter(name="configKey")
def config_key(self) -> str:
"""
Unique name of the configuration
"""
return pulumi.get(self, "config_key")
@property
@pulumi.getter(name="dataType")
def data_type(self) -> str:
"""
configuration data type
"""
return pulumi.get(self, "data_type")
@property
@pulumi.getter
def name(self) -> str:
"""
configuration name
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def value(self) -> str:
"""
configuration value
"""
return pulumi.get(self, "value")
@property
@pulumi.getter
def values(self) -> Sequence['outputs.GetTargetsTargetCollectionItemTargetDetectorRecipeEffectiveDetectorRuleDetailsConfigurationValueResult']:
"""
List of configuration values
"""
return pulumi.get(self, "values")
@pulumi.output_type
class GetTargetsTargetCollectionItemTargetDetectorRecipeEffectiveDetectorRuleDetailsConfigurationValueResult(dict):
def __init__(__self__, *,
list_type: str,
managed_list_type: str,
value: str):
"""
:param str list_type: configuration list item type, either CUSTOM or MANAGED
:param str managed_list_type: type of the managed list
:param str value: configuration value
"""
pulumi.set(__self__, "list_type", list_type)
pulumi.set(__self__, "managed_list_type", managed_list_type)
pulumi.set(__self__, "value", value)
@property
@pulumi.getter(name="listType")
def list_type(self) -> str:
"""
configuration list item type, either CUSTOM or MANAGED
"""
return pulumi.get(self, "list_type")
@property
@pulumi.getter(name="managedListType")
def managed_list_type(self) -> str:
"""
type of the managed list
"""
return pulumi.get(self, "managed_list_type")
@property
@pulumi.getter
def value(self) -> str:
"""
configuration value
"""
return pulumi.get(self, "value")
@pulumi.output_type
class GetTargetsTargetCollectionItemTargetResponderRecipeResult(dict):
def __init__(__self__, *,
compartment_id: str,
description: str,
display_name: str,
effective_responder_rules: Sequence['outputs.GetTargetsTargetCollectionItemTargetResponderRecipeEffectiveResponderRuleResult'],
id: str,
owner: str,
responder_recipe_id: str,
responder_rules: Sequence['outputs.GetTargetsTargetCollectionItemTargetResponderRecipeResponderRuleResult'],
time_created: str,
time_updated: str):
"""
:param str compartment_id: The ID of the compartment in which to list resources.
:param str description: ResponderRule Description
:param str display_name: A filter to return only resources that match the entire display name given.
:param Sequence['GetTargetsTargetCollectionItemTargetResponderRecipeEffectiveResponderRuleArgs'] effective_responder_rules: List of responder rules associated with the recipe after applying all defaults
:param str id: Unique identifier of TargetResponderRecipe that is immutable on creation
:param str owner: Owner of ResponderRecipe
:param str responder_recipe_id: Unique identifier for Responder Recipe of which this is an extension
:param Sequence['GetTargetsTargetCollectionItemTargetResponderRecipeResponderRuleArgs'] responder_rules: List of responder rules associated with the recipe - user input
:param str time_created: The date and time the target was created. Format defined by RFC3339.
:param str time_updated: The date and time the target was updated. Format defined by RFC3339.
"""
pulumi.set(__self__, "compartment_id", compartment_id)
pulumi.set(__self__, "description", description)
pulumi.set(__self__, "display_name", display_name)
pulumi.set(__self__, "effective_responder_rules", effective_responder_rules)
pulumi.set(__self__, "id", id)
pulumi.set(__self__, "owner", owner)
pulumi.set(__self__, "responder_recipe_id", responder_recipe_id)
pulumi.set(__self__, "responder_rules", responder_rules)
pulumi.set(__self__, "time_created", time_created)
pulumi.set(__self__, "time_updated", time_updated)
@property
@pulumi.getter(name="compartmentId")
def compartment_id(self) -> str:
"""
The ID of the compartment in which to list resources.
"""
return pulumi.get(self, "compartment_id")
@property
@pulumi.getter
def description(self) -> str:
"""
ResponderRule Description
"""
return pulumi.get(self, "description")
@property
@pulumi.getter(name="displayName")
def display_name(self) -> str:
"""
A filter to return only resources that match the entire display name given.
"""
return pulumi.get(self, "display_name")
@property
@pulumi.getter(name="effectiveResponderRules")
def effective_responder_rules(self) -> Sequence['outputs.GetTargetsTargetCollectionItemTargetResponderRecipeEffectiveResponderRuleResult']:
"""
List of responder rules associated with the recipe after applying all defaults
"""
return pulumi.get(self, "effective_responder_rules")
@property
@pulumi.getter
def id(self) -> str:
"""
Unique identifier of TargetResponderRecipe that is immutable on creation
"""
return pulumi.get(self, "id")
@property
@pulumi.getter
def owner(self) -> str:
"""
Owner of ResponderRecipe
"""
return pulumi.get(self, "owner")
@property
@pulumi.getter(name="responderRecipeId")
def responder_recipe_id(self) -> str:
"""
Unique identifier for Responder Recipe of which this is an extension
"""
return pulumi.get(self, "responder_recipe_id")
@property
@pulumi.getter(name="responderRules")
def responder_rules(self) -> Sequence['outputs.GetTargetsTargetCollectionItemTargetResponderRecipeResponderRuleResult']:
"""
List of responder rules associated with the recipe - user input
"""
return pulumi.get(self, "responder_rules")
@property
@pulumi.getter(name="timeCreated")
def time_created(self) -> str:
"""
The date and time the target was created. | |
= get_beamline().detector
plot_y = get_beamline().PLOT_Y
#plot_y = pilatus2M.stats4.total
#print("plot_y is {}".format(plot_y))
else:
plot_y = '{}{}'.format(detectors[0].name, detector_suffix)
# Get axes for plotting
title = 'fit_scan: {} vs. {}'.format(detectors[0].name, motor.name)
#if len(plt.get_fignums())>0:
# Try to use existing figure
#fig = plt.gcf() # Most recent figure
fig = None
for i in plt.get_fignums():
title_cur = plt.figure(i).canvas.manager.window.windowTitle()
if title_cur==title:
fig = plt.figure(i)
break
if fig is None:
# New figure
#fig, ax = plt.subplots()
fig = plt.figure(figsize=(11,7), facecolor='white')
fig.canvas.manager.toolbar.pan()
fig.canvas.set_window_title(title)
ax = fig.gca()
subs = []
livetable = LiveTable([motor] + list(detectors))
#subs.append(livetable)
#liveplot = LivePlot_Custom(plot_y, motor.name, ax=ax)
liveplot = LivePlot(plot_y, motor.name, ax=ax)
subs.append(liveplot)
if wait_time is not None:
subs.append(MotorWait(motor, wait_time))
if fit in ['max', 'min', 'COM', 'HM', 'HMi'] or type(fit) is list:
livefit = LiveStat(fit, plot_y, motor.name)
livefitplot = LiveStatPlot(livefit, ax=ax, scan_range=[start, stop])
subs.append(livefitplot)
elif fit is not None:
# Perform a fit
#livefit = LiveFit(lm_model, plot_y, {'x': motor.name}, init_guess)
livefit = LiveFit_Custom(fit, plot_y, {'x': motor.name}, scan_range=[start, stop], background=background)
#livefitplot = LiveFitPlot(livefit, color='k')
livefitplot = LiveFitPlot_Custom(livefit, ax=ax, scan_range=[start, stop])
subs.append(livefitplot)
md['plan_header_override'] = 'fit_scan'
md['scan'] = 'fit_scan'
md['measure_type'] = 'fit_scan_{}'.format(motor.name)
md['fit_function'] = fit
md['fit_background'] = background
#cms.SAXS.detector.setExposureTime(exposure_time)
RE(cms.SAXS.detector.setExposureTime(exposure_time))
#exposure_time_last = md['exposure_time']
#md['exposure_time'] = exposure_time
# Perform the scan
bec.disable_plots()
RE(scan(list(detectors), motor, start, stop, num, per_step=per_step, md=md), subs )
bec.enable_plots()
#RE(scan(list(detectors), motor, start, stop, num, per_step=per_step, md=md), [liveplot, livefit, livefitplot])
#RE(scan(list(detectors), motor, start, stop, num, per_step=per_step, md=md), [livefit])
#md['exposure_time'] = exposure_time_last
#if plot_y=='pilatus300_stats4_total' or plot_y=='pilatus300_stats3_total':
if plot_y=='pilatus2M_stats4_total' or plot_y=='pilatus2M_stats3_total':
remove_last_Pilatus_series()
#check save_flg and save the scan data thru databroker
if save_flg == 1:
header = db[-1]
dtable = header.table()
filename = '{}/{}'.format(RE.md['experiment_alias_directory'],header.start['scan_id'])
dtable.to_csv(filename)
if toggle_beam:
beam.off()
if fit is None:
# Return to start position
#motor.user_setpoint.set(initial_position)
#mov(motor, initial_position)
motor.move(initial_position)
else:
print( livefit.result.values )
x0 = livefit.result.values['x0']
#mov(motor, x0)
motor.move(x0)
return livefit.result
def fit_edge(motor, span, num=11, detectors=None, detector_suffix='', plot=True, toggle_beam=True, wait_time=None, md={}):
"""
Optimized fit_scan for finding a (decreasing) step-edge.
Parameters
----------
motor : motor
The axis/stage/motor that you want to move.
span : float
The total size of the scan range (centered about the current position).
If a two-element list is instead specified, this is interpreted as the
distances relative to the current position for the start and end.
num : int
The number of scan points.
md : dict, optional
metadata
"""
if toggle_beam:
beam.on()
if not beam.is_on():
print('WARNING: Experimental shutter is not open.')
cms.setMonitor(monitor=['stats1', 'stats2', 'stats3', 'stats4'])
initial_position = motor.user_readback.value
if type(span) is list:
start = initial_position+span[0]
stop = initial_position+span[1]
else:
start = initial_position-span/2.
stop = initial_position+span/2.
span = abs(stop-start)
if detectors is None:
detectors = get_beamline().detector
plot_y = get_beamline().PLOT_Y
else:
plot_y = '{}{}'.format(detectors[0].name, detector_suffix)
subs = []
livetable = LiveTable_Custom([motor] + list(detectors), plot_y, motor.name)
#scallback = SavingCallback()
#subs.append(scallback)
# access data with scallback.data['keyname']
# (gives a list)
subs.append(livetable)
if plot:
# Get axes for plotting
title = 'fit_scan: {} vs. {}'.format(detectors[0].name, motor.name)
fig = None
for i in plt.get_fignums():
title_cur = plt.figure(i).canvas.manager.window.windowTitle()
if title_cur==title:
fig = plt.figure(i)
break
if fig is None:
# New figure
#fig, ax = plt.subplots()
fig = plt.figure(figsize=(11,7), facecolor='white')
fig.canvas.manager.toolbar.pan()
fig.canvas.set_window_title(title)
ax = fig.gca()
liveplot = LivePlot_Custom(plot_y, motor.name, ax=ax)
#liveplot = LivePlot(plot_y, motor.name, ax=ax)
subs.append(liveplot)
if wait_time is not None:
subs.append(MotorWait(motor, wait_time))
md['plan_header_override'] = 'fit_edge'
md['scan'] = 'fit_edge'
# Perform the scan
bec.disable_table()
bec.disable_plots()
RE(scan(list(detectors), motor, start, stop, num, md=md), subs)
#RE(scan(list(detectors), motor, start, stop, num, md=md), [liveplot, livetable] )
bec.enable_plots()
bec.enable_table()
#if plot_y=='pilatus300_stats4_total' or plot_y=='pilatus300_stats3_total':
if plot_y=='pilatus2M_stats4_total' or plot_y=='pilatus2M_stats3_total':
remove_last_Pilatus_series()
x0_guess = np.average(livetable.xdata)
# Determine x0 from half-max (HM) analysis
if True:
# TODO: Handle case where more than one pair of points cross the HM
if len(livetable.xdata)>3:
y_max = np.max(livetable.ydata)
HM = (y_max-np.min(livetable.ydata))/2.0
for ip, (x2, y2) in enumerate(zip(livetable.xdata, livetable.ydata)):
if ip>0:
x1 = livetable.xdata[ip-1]
yx1 = livetable.ydata[ip-1]
if x1>HM and x2<HM:
# This pair of points crosses the HM
m = (y2-y1)/(x2-x1)
b = y2-m*x2
xHM = (HM-b)/m
x0_guess = xHM
# Fit to sigmoid_r
if True:
y_max = np.max(livetable.ydata)
x_span = abs(np.max(livetable.xdata)-np.min(livetable.xdata))
def model(v, x):
return v['prefactor']/( 1 + np.exp( +(x-v['x0'])/v['sigma'] ) )
def func2minimize(params, x, data):
v = params.valuesdict()
m = model(v, x)
return m - data
params = lmfit.Parameters()
if y_max>0:
params.add('prefactor', value=y_max*0.95, min=y_max*0.90, max=y_max*1.02)
else:
params.add('prefactor', value=y_max*0.95, min=0, max=1)
params.add('x0', value=x0_guess, min=np.min(livetable.xdata)+x_span*0.05, max=np.max(livetable.xdata)-x_span*0.05 )
params.add('sigma', value=0.014, min=x_span*1e-4, max=x_span*0.08)
# 1st fit: only vary x0
params['prefactor'].set(vary=False)
params['sigma'].set(vary=False)
lm_result = lmfit.minimize(func2minimize, params, args=(livetable.xdata, livetable.ydata))
#lmfit.report_fit(lm_result.params)
# 2nd fit: vary everything
params['prefactor'].set(vary=True)
params['sigma'].set(vary=True)
lm_result = lmfit.minimize(func2minimize, params, args=(livetable.xdata, livetable.ydata))
#lmfit.report_fit(lm_result.params)
if plot:
xe = 0.25
fit_x = np.linspace(np.min(livetable.xdata)-xe*x_span, np.max(livetable.xdata)+xe*x_span, num=500)
fit_y = model(lm_result.params.valuesdict(), fit_x)
#liveplot.add_line(fit_x, fit_y, color='b', linewidth=2.5)
# Detect bad fits
avg_deviation = np.sum(np.abs(lm_result.residual/y_max))/len(livetable.ydata)
print(' avg deviation {:.1f}%'.format(avg_deviation*100))
#avg_deviation of <1% is good.
#avg_deviation of 1-4% is normal.
#avg_deviation of 8% is not good (fit okay, but HM slightly off).
#avg_deviation of 10% is bad fit.
# TODO: Change the plotting if the fit is bad. (I.e. since we're using HM instead of fit, show that.)
if avg_deviation>0.06:
x0 = x0_guess
else:
x0 = lm_result.params['x0'].value
print('Moving to x = {:.3f}'.format(x0))
motor.move(x0)
if toggle_beam:
beam.off()
lm_result_values = { k : v.value for k, v in lm_result.params.items() }
return lm_result_values
def _test_fit_scan(motor, span, num=11, detectors=None, detector_suffix='', fit='HMi', background=None, per_step=None, wait_time=None, md={}):
"""
Scans the specified motor, and attempts to fit the data as requested.
Parameters
----------
motor : motor
The axis/stage/motor that you want to move.
span : float
The total size of the scan range (centered about the current position).
If a two-element list is instead specified, this is interpreted as the
distances relative to the current position for the start and end.
num : int
The number of scan points.
fit : None or string
If None, then fitting is not done. Otherwise, the model specified by the
supplied string is used.
peaks: gauss, lorentz, doublesigmoid, square
edges: sigmoid, step
stats: max, min, COM (center-of-mass), HM (half-max)
background : None or string
A baseline/background underlying the fit function can be specified.
(In fact, a sequence of summed background functions can be supplied.)
constant, linear
md : dict, optional
metadata
"""
# TODO: Normalize per ROI pixel and per count_time?
if not beam.is_on():
print('WARNING: Experimental shutter is not open.')
initial_position = motor.user_readback.value
if type(span) is list:
start = initial_position+span[0]
stop = initial_position+span[1]
else:
start = initial_position-span/2.
stop = initial_position+span/2.
span = abs(stop-start)
#positions, dp = np.linspace(start, stop, num, endpoint=True, retstep=True)
if detectors is None:
detectors = get_beamline().detector
plot_y = get_beamline().PLOT_Y
else:
plot_y = '{}{}'.format(detectors[0].name, detector_suffix)
# Get axes for plotting
title = 'fit_scan: {} vs. {}'.format(detectors[0].name, motor.name)
#if len(plt.get_fignums())>0:
# Try to use existing figure
#fig = plt.gcf() # Most recent figure
fig = None
for i in plt.get_fignums():
title_cur = plt.figure(i).canvas.manager.window.windowTitle()
if title_cur==title:
fig = plt.figure(i)
break
if fig is None:
# New figure
#fig, ax = plt.subplots()
fig = plt.figure(figsize=(11,7), facecolor='white')
fig.canvas.manager.toolbar.pan()
fig.canvas.set_window_title(title)
ax = fig.gca()
subs = []
livetable = LiveTable([motor] + list(detectors))
#livetable = LiveTable([motor] + list(detectors))
subs.append(livetable)
liveplot = LivePlot_Custom(plot_y, motor.name, ax=ax)
subs.append(liveplot)
if wait_time is not None:
subs.append(MotorWait(motor, wait_time))
if fit in ['max', 'min', 'COM', 'HM', 'HMi'] or type(fit) is list:
livefit = LiveStat(fit, plot_y, motor.name)
livefitplot = LiveStatPlot(livefit, ax=ax, scan_range=[start, stop])
subs.append(livefitplot)
elif fit is not None:
# Perform a fit
#livefit = LiveFit(lm_model, plot_y, {'x': motor.name}, init_guess)
livefit = LiveFit_Custom(fit, plot_y, {'x': motor.name}, scan_range=[start, stop], background=background)
#livefitplot = LiveFitPlot(livefit, color='k')
livefitplot = LiveFitPlot_Custom(livefit, ax=ax, scan_range=[start, stop])
subs.append(livefitplot)
md['plan_header_override'] = 'fit_scan'
| |
# use ld_long macro
instruction_name = 'ld_long'
# cannot wrap the address value with square brackets
operand_values.pop()
operand_values.append(hex_word(value))
elif operand == '[$ff00+a8]' or operand == '[a8]' or operand == '[$ffa8]':
length += 1
value = rom.data[pc + 1]
full_value = 0xff00 + value
label = self.get_label_for_instruction_operand(full_value)
if label is not None:
# when referencing a label, we need to explicitely tell rgbds to use the short load opcode
instruction_name = 'ldh'
operand_values.append('[{}]'.format(label))
elif full_value in hardware_labels:
operand_values.append('[{}]'.format(hardware_labels[full_value]))
else:
# use one of the ldh_a8_formatters formatters
operand_values.append(ldh_a8_formatters[self.style['ldh_a8']](value))
elif operand == 'd8':
length += 1
value = rom.data[pc + 1]
operand_values.append(hex_byte(value))
elif operand == 'd16':
length += 2
value = rom.data[pc + 1] + rom.data[pc + 2] * 256
label = self.get_label_for_instruction_operand(value)
if label is not None:
operand_values.append(label)
else:
operand_values.append(hex_word(value))
elif operand == 'r8':
length += 1
value = to_signed(rom.data[pc + 1])
if value < 0:
operand_values.append('-' + hex_byte(abs(value)))
else:
operand_values.append(hex_byte(value))
elif operand == 'pc+r8':
length += 1
value = to_signed(rom.data[pc + 1])
# calculate the absolute address for the jump
value = pc + 2 + value
relative_value = value - pc
if relative_value >= 0:
operand_values.append('@+' + hex_byte(relative_value))
else:
operand_values.append('@-' + hex_byte(relative_value * -1))
target_bank = value // 0x4000
# convert to banked value so it can be used as a label
value = rom_address_to_mem_address(value)
if self.bank_number != target_bank:
# don't use labels for relative jumps across banks
value = None
if target_bank < self.bank_number:
# output as data, otherwise RGBDS will complain
instruction_name = self.style['db']
operand_values = [hex_byte(opcode), hex_byte(rom.data[pc + 1])]
# exit the loop to avoid processing the operands any further
break
elif operand == 'sp+r8':
length += 1
value = to_signed(rom.data[pc + 1])
if value < 0:
operand_values.append('sp-' + hex_byte(abs(value)))
else:
operand_values.append('sp+' + hex_byte(value))
elif operand == '[$ff00+c]':
operand_values.append('[{0}+c]'.format(hex_word(0xff00)))
elif type(operand) is str:
operand_values.append(operand)
else:
operand_values.append(hex_byte(operand))
if instruction_name in ['jr', 'jp', 'call'] and value is not None and value < 0x8000:
mem_address = rom_address_to_mem_address(value)
if self.first_pass:
# dont allow switched banks to create labels in bank 0
is_address_in_current_bank = (mem_address < 0x4000 and self.bank_number == 0) or (mem_address >= 0x4000 and self.bank_number > 0)
if is_address_in_current_bank:
# add the label
self.add_target_address(instruction_name, mem_address)
else:
# fetch the label name
label = self.get_label_for_jump_target(instruction_name, mem_address)
if label is not None:
# remove the address from operand values and use the label instead
operand_values.pop()
operand_values.append(label)
# check the instruction is not spanning 2 banks
if pc + length - 1 >= end_address:
# must handle it as data
length = 1
instruction_name = self.style['db']
operand_values = [hex_byte(opcode)]
self.pc += length
if self.first_pass:
self.disassembled_addresses.add(pc_mem_address)
else:
labels = self.get_labels_for_address(pc_mem_address)
if len(labels):
self.append_labels_to_output(labels)
if comment is not None:
self.append_output(comment)
instruction_bytes = rom.data[pc:pc + length]
self.append_output(self.format_instruction(instruction_name, operand_values, pc_mem_address, instruction_bytes))
# add some empty lines after returns and jumps to break up the code blocks
if instruction_name in ['ret', 'reti', 'jr', 'jp']:
if (
instruction_name == 'jr' or
(instruction_name == 'jp' and len(operand_values) > 1) or
(instruction_name == 'ret' and len(operand_values) > 0)
):
# conditional or jr
self.append_output('')
else:
# always executes
self.append_output('')
self.append_output('')
def process_data_in_range(self, rom, start_address, end_address, arguments = None):
if not self.first_pass and debug:
print('Outputting data in range: {} - {}'.format(hex_word(start_address), hex_word(end_address)))
values = list()
for address in range(start_address, end_address):
mem_address = rom_address_to_mem_address(address)
labels = self.get_labels_for_non_code_address(mem_address)
if len(labels):
# add any existing values to the output and reset the list
if len(values) > 0:
self.append_output(self.format_data(values))
values = list()
self.append_labels_to_output(labels)
values.append(hex_byte(rom.data[address]))
# output max of 16 bytes per line, and ensure any remaining values are output
if len(values) == 16 or (address == end_address - 1 and len(values)):
self.append_output(self.format_data(values))
values = list()
def process_text_in_range(self, rom, start_address, end_address, arguments = None):
if not self.first_pass and debug:
print('Outputting text in range: {} - {}'.format(hex_word(start_address), hex_word(end_address)))
values = list()
text = ''
for address in range(start_address, end_address):
mem_address = rom_address_to_mem_address(address)
labels = self.get_labels_for_non_code_address(mem_address)
if len(labels):
# add any existing values to the output and reset the list
if len(text):
values.append('"{}"'.format(text))
text = ''
if len(values):
self.append_output(self.format_data(values))
values = list()
self.append_labels_to_output(labels)
byte = rom.data[address]
if byte >= 0x20 and byte < 0x7F:
text += chr(byte)
else:
if len(text):
values.append('"{}"'.format(text))
text = ''
values.append(hex_byte(byte))
if len(text):
values.append('"{}"'.format(text))
if len(values):
self.append_output(self.format_data(values))
def process_image_in_range(self, rom, start_address, end_address, arguments = None):
if not self.first_pass and debug:
print('Outputting image in range: {} - {}'.format(hex_word(start_address), hex_word(end_address)))
if self.first_pass:
return
mem_address = rom_address_to_mem_address(start_address)
labels = self.get_labels_for_non_code_address(mem_address)
if len(labels):
self.append_labels_to_output(labels)
basename = labels[0].rstrip(':')
else:
basename = self.format_image_label(mem_address)
full_filename = rom.write_image(basename, arguments, '2bpp', rom.data[start_address:end_address])
self.append_output(self.format_instruction('INCBIN', ['\"' + full_filename + '\"']))
class Symbols:
def __init__(self):
self.symbols = dict()
self.blocks = dict()
def load_sym_file(self, symbols_path):
f = open(symbols_path, 'r')
for line in f:
# ignore comments and empty lines
if line[0] != ';' and len(line.strip()):
self.add_symbol_definition(line)
f.close()
def add_symbol_definition(self, symbol_def):
try:
location, label = symbol_def.split()
bank, address = location.split(':')
bank = int(bank, 16)
address = int(address, 16)
except:
print("Ignored invalid symbol definition: {}\n".format(symbol_def))
else:
label_parts = label.split(':')
is_block_definition = label[0] == '.' and len(label_parts) >= 2
if is_block_definition:
# add a block
block_type = label_parts[0].lower()
data_length = int(label_parts[1], 16)
if block_type in ['.byt', '.data']:
block_type = 'data'
elif block_type in ['.asc', '.text']:
block_type = 'text'
elif block_type in ['.code']:
block_type = 'code'
elif block_type in ['.image']:
block_type = 'image'
else:
return
if len(label_parts) == 3:
arguments = label_parts[2]
else:
arguments = None
self.add_block(bank, address, block_type, data_length, arguments)
else:
# add the label
self.add_label(bank, address, label)
def add_block(self, bank, address, block_type, length, arguments = None):
memory_base_address = 0x0000 if bank == 0 else 0x4000
if address >= memory_base_address:
blocks = self.get_blocks(bank)
blocks[address] = {
'type': block_type,
'length': length,
'arguments': arguments
}
def add_label(self, bank, address, label):
if bank not in self.symbols:
self.symbols[bank] = dict()
is_symbol_banked = 0x4000 <= address < 0x8000
if is_symbol_banked:
self.symbols[bank][address] = label
else:
self.symbols[0][address] = label
def get_label(self, bank, address):
# attempt to find a banked symbol
is_symbol_banked = 0x4000 <= address < 0x8000
if is_symbol_banked and bank in self.symbols and address in self.symbols[bank]:
return self.symbols[bank][address]
# attempt to find a symbol in non-banked space (stored as bank 0)
if 0 in self.symbols and address in self.symbols[0]:
return self.symbols[0][address]
return None
def get_blocks(self, bank):
memory_base_address = 0x0000 if bank == 0 else 0x4000
if bank not in self.blocks:
self.blocks[bank] = dict()
# each bank defaults to having a single code block
self.add_block(bank, memory_base_address, 'code', 0x4000)
return self.blocks[bank]
class ROM:
def __init__(self, rom_path, style):
self.style = style
self.script_dir = os.path.dirname(os.path.realpath(__file__))
self.rom_path = rom_path
self.load()
self.split_instructions()
self.has_ld_long = False
self.image_output_directory = 'gfx'
self.image_dependencies = []
print('ROM MD5 hash:', hashlib.md5(self.data).hexdigest())
self.symbols = self.load_symbols()
# add some bytes to avoid an index out of range error
# when processing last few instructions in the rom
self.data += b'\x00\x00'
self.banks = dict()
for bank in range(0, self.num_banks):
self.banks[bank] = Bank(bank, self.symbols, style)
def load(self):
if os.path.isfile(self.rom_path):
print('Loading "{}"...'.format(self.rom_path))
self.data = open(self.rom_path, 'rb').read()
self.rom_size = len(self.data)
self.num_banks = self.rom_size // 0x4000
else:
abort('"{}" not found'.format(self.rom_path))
def split_instructions(self):
# split the instructions and operands
self.instruction_names = dict()
self.instruction_operands = dict()
self.cb_instruction_name = dict()
self.cb_instruction_operands = dict()
for opcode in instructions:
instruction_parts = instructions[opcode].split()
self.instruction_names[opcode] = instruction_parts[0]
if len(instruction_parts) > 1:
self.instruction_operands[opcode] = instruction_parts[1].split(',')
else:
self.instruction_operands[opcode] = list()
for cb_opcode in cb_instructions:
instruction_parts = cb_instructions[cb_opcode].split()
self.cb_instruction_name[cb_opcode] = instruction_parts[0]
if len(instruction_parts) > 1:
self.cb_instruction_operands[cb_opcode] = instruction_parts[1].split(',')
else:
self.cb_instruction_operands[cb_opcode] = list()
def load_symbols(self):
symbols = Symbols()
for symbol_def in default_symbols:
symbols.add_symbol_definition(symbol_def)
if self.supports_gbc():
for symbol_def in gbc_symbols:
symbols.add_symbol_definition(symbol_def)
symbols_path = os.path.splitext(self.rom_path)[0] + '.sym'
if os.path.isfile(symbols_path):
print('Processing symbol file "{}"...'.format(symbols_path))
symbols.load_sym_file(symbols_path)
return symbols
def supports_gbc(self):
return ((self.data[0x143] & 0x80) == 0x80)
def disassemble(self, output_dir):
self.output_directory = os.path.abspath(output_dir.rstrip(os.sep))
if os.path.exists(self.output_directory):
if not args.overwrite:
abort('Output directory "{}" already exists!'.format(self.output_directory))
if not os.path.isdir(self.output_directory):
abort('Output path "{}" already exists and is not a directory!'.format(self.output_directory))
else:
os.makedirs(self.output_directory)
print('Generating labels...')
self.generate_labels()
self.image_dependencies = []
print('Generating disassembly', end='')
if debug:
print('')
for bank in range(0, self.num_banks):
self.write_bank_asm(bank)
self.copy_hardware_inc()
| |
<filename>nanoraw/nanoraw_helper.py
import sys, os
import re
import h5py
import numpy as np
from collections import defaultdict, namedtuple
NANORAW_VERSION = '0.5'
SMALLEST_PVAL = 1e-20
readData = namedtuple('readData', (
'start', 'end', 'segs', 'read_start_rel_to_raw',
'strand', 'fn', 'corr_group'))
channelInfo = namedtuple(
'channelInfo',
('offset', 'range', 'digitisation', 'number', 'sampling_rate'))
scaleValues = namedtuple(
'scaleValues',
('shift', 'scale', 'lower_lim', 'upper_lim'))
NORM_TYPES = ('none', 'pA', 'pA_raw', 'median', 'robust_median')
# single base conversion for motifs
SINGLE_LETTER_CODE = {
'A':'A', 'C':'C', 'G':'G', 'T':'T', 'B':'[CGT]',
'D':'[AGT]', 'H':'[ACT]', 'K':'[GT]', 'M':'[AC]',
'N':'[ACGT]', 'R':'[AG]', 'S':'[CG]', 'V':'[ACG]',
'W':'[AT]', 'Y':'[CT]'}
VERBOSE = False
# got quantiles from analysis of stability after shift-only normalization
robust_quantiles = (46.5, 53.5)
COMP_BASES = {'A':'T', 'C':'G', 'G':'C', 'T':'A', '-':'-', 'N':'N'}
def comp_base(base):
# replace non-ACGT bases with dash
try:
return COMP_BASES[base]
except KeyError:
return 'N'
def rev_comp(seq):
return ''.join(comp_base(b) for b in seq[::-1])
def get_files_list(basedirs):
return [os.path.join(base_dir, fn)
for base_dir in basedirs
for fn in os.listdir(base_dir)]
def get_files_lists(basedirs1, basedirs2):
files1 = get_files_list(basedirs1)
files2 = get_files_list(basedirs2) if basedirs2 else None
return files1, files2
def parse_motif(motif):
invalid_chars = re.findall('[^ACGTBDHKMNRSVWY]', motif)
if len(invalid_chars) > 0:
sys.stderr.write(
'********* ERROR ********* Invalid characters in motif: ' +
', '.join(invalid_chars) + ' *********\n')
sys.exit()
return re.compile(''.join(
SINGLE_LETTER_CODE[letter] for letter in motif))
def parse_obs_filter(obs_filter):
if obs_filter is None:
return None
# parse obs_filter
try:
obs_filter = [
(float(pctl_nobs.split(':')[0]),
int(pctl_nobs.split(':')[1]))
for pctl_nobs in obs_filter]
except:
raise RuntimeError('Invalid format for observation filter')
return obs_filter
def filter_reads(raw_read_coverage, obs_filter):
if obs_filter is None:
return raw_read_coverage
num_reads = len([None for chrm_reads in list(raw_read_coverage.values())
for _ in chrm_reads])
filt_raw_read_cov = {}
for chrm, chrm_reads in list(raw_read_coverage.items()):
chrm_filt_reads = [
r_data for r_data in chrm_reads if not any(
np.percentile(np.diff(r_data.segs), pctl) > thresh
for pctl, thresh in obs_filter)]
if len(chrm_filt_reads) > 0:
filt_raw_read_cov[chrm] = chrm_filt_reads
num_filt_reads = len([
None for chrm_reads in list(filt_raw_read_cov.values())
for _ in chrm_reads])
if num_filt_reads < num_reads:
sys.stderr.write(
'Filtered ' + str(num_reads - num_filt_reads) +
' reads due to observations per base filter from a ' +
'total of ' + str(num_reads) + ' reads.\n')
return filt_raw_read_cov
def parse_fast5s(files, corrected_group, basecall_subgroups):
raw_read_coverage = defaultdict(list)
for read_fn, basecall_subgroup in [
(fn, bc_grp)for fn in files
for bc_grp in basecall_subgroups]:
try:
read_data = h5py.File(read_fn, 'r')
except IOError:
# probably truncated file
continue
corr_slot = '/'.join((
'/Analyses', corrected_group, basecall_subgroup))
if corr_slot not in read_data:
continue
corr_data = read_data[corr_slot]
try:
align_data = dict(list(corr_data['Alignment'].attrs.items()))
read_start_rel_to_raw = corr_data['Events'].attrs[
'read_start_rel_to_raw']
event_data = corr_data['Events'].value
events_end = event_data[-1]['start'] + event_data[-1][
'length']
segs = np.concatenate([event_data['start'], [events_end,]])
except:
sys.stderr.write(
'********** WARNING: Corrupted corrected events in ' +
read_fn + '. ********\n')
continue
raw_read_coverage[(
align_data['mapped_chrom'],
align_data['mapped_strand'])].append(
readData(
align_data['mapped_start'],
align_data['mapped_start'] + len(segs) - 1,
segs, read_start_rel_to_raw,
align_data['mapped_strand'], read_fn,
corrected_group + '/' + basecall_subgroup))
read_data.close()
return raw_read_coverage
def get_channel_info(fast5_data):
try:
fast5_info = fast5_data['UniqueGlobalKey/channel_id'].attrs
except:
raise RuntimeError("No channel_id group in HDF5 file. " +
"Probably mux scan HDF5 file.")
channel_info = channelInfo(
fast5_info['offset'], fast5_info['range'],
fast5_info['digitisation'], fast5_info['channel_number'],
fast5_info['sampling_rate'].astype('int_'))
return channel_info
def parse_pore_model(pore_model_fn):
pore_model = {'mean':{}, 'inv_var':{}}
with open(pore_model_fn) as fp:
for line in fp:
if line.startswith('#'): continue
try:
kmer, lev_mean, lev_stdev = line.split()[:3]
lev_mean, lev_stdev = list(map(float, (lev_mean, lev_stdev)))
except ValueError:
# header or other non-kmer field
continue
pore_model['mean'][kmer] = lev_mean
pore_model['inv_var'][kmer] = 1 / (lev_stdev * lev_stdev)
return pore_model
def calc_kmer_fitted_shift_scale(pore_model, events_means, events_kmers):
r_model_means = np.array([pore_model['mean'][kmer]
for kmer in events_kmers])
r_model_inv_vars = np.array([pore_model['inv_var'][kmer]
for kmer in events_kmers])
model_mean_var = r_model_means * r_model_inv_vars
# prep kmer model coefficient matrix for the k-mers from this read
model_mean_var_sum = model_mean_var.sum()
coef_mat = np.array((
(r_model_inv_vars.sum(), model_mean_var_sum),
(model_mean_var_sum, (model_mean_var * r_model_means).sum())))
# prep dependent values from this reads true events
r_event_var = events_means * r_model_inv_vars
r_event_var_mean = r_event_var * r_model_means
dep_vect = np.array((r_event_var.sum(), r_event_var_mean.sum()))
shift, scale = np.linalg.solve(coef_mat, dep_vect)
return shift, scale
def normalize_raw_signal(
all_raw_signal, read_start_rel_to_raw, read_obs_len,
norm_type=None, channel_info=None, outlier_thresh=None,
shift=None, scale=None, lower_lim=None, upper_lim=None,
pore_model=None, event_means=None, event_kmers=None):
if norm_type not in NORM_TYPES and (shift is None or scale is None):
raise NotImplementedError(
'Normalization type ' + norm_type + ' is not a valid ' +
'option and shift or scale parameters were not provided.')
raw_signal = np.array(all_raw_signal[
read_start_rel_to_raw:
read_start_rel_to_raw + read_obs_len])
if shift is None or scale is None:
if norm_type == 'none':
shift, scale = 0, 1
elif norm_type in ('pA_raw', 'pA'):
# correct raw signal as described here:
# https://community.nanoporetech.com
# /posts/squiggle-plot-for-raw-data
shift, scale = (
-1 * channel_info.offset,
channel_info.digitisation / channel_info.range)
if norm_type == 'pA':
# perform k-mer model fitted correction as in
# nanocorr/nanopolish/ONT
fit_shift, fit_scale = calc_kmer_fitted_shift_scale(
pore_model, event_means, event_kmers)
# apply shift and scale values fitted from kmer
# conditional model after raw DAC scaling
shift = shift + (fit_shift * scale)
scale = scale * fit_scale
# print fitted shift and scale for comparisons
#print 'shift: ' + str(fit_shift) + \
# '\tscale: ' + str(fit_scale)
elif norm_type == 'median':
shift = np.median(raw_signal)
scale = np.median(np.abs(raw_signal - shift))
elif norm_type == 'robust_median':
shift = np.mean(np.percentile(
raw_signal, robust_quantiles))
scale = np.median(np.abs(raw_signal - read_robust_med))
raw_signal = (raw_signal - shift) / scale
if outlier_thresh is not None or (
lower_lim is not None and upper_lim is not None):
if outlier_thresh is not None:
read_med = np.median(raw_signal)
read_mad = np.median(np.abs(raw_signal - read_med))
lower_lim = read_med - (read_mad * outlier_thresh)
upper_lim = read_med + (read_mad * outlier_thresh)
raw_signal = np.array([
upper_lim if outlier_high else
(lower_lim if outlier_low else x)
for x, outlier_high, outlier_low in zip(
raw_signal, raw_signal > upper_lim,
raw_signal < lower_lim)])
return raw_signal, scaleValues(shift, scale, lower_lim, upper_lim)
def parse_fasta(fasta_fn):
# Tried Biopython index and that opened the fail again for each
# record access request and was thus far too slow
# could consider a conditional dependence on pyfaix if on-memory
# indexing is required for larger genomes
# testing shows that human genome only takes 3.2 GB with raw parser
# so raw parsing is probably fine
fasta_fp = open(fasta_fn)
fasta_records = {}
curr_id = None
curr_seq = ''
for line in fasta_fp:
if line.startswith('>'):
if (curr_id is not None and
curr_seq is not ''):
fasta_records[curr_id] = curr_seq
curr_seq = ''
curr_id = line.replace(">","").strip().split()[0]
else:
curr_seq += line.strip()
# add last record
if (curr_id is not None and
curr_seq is not ''):
fasta_records[curr_id] = curr_seq
fasta_fp.close()
return fasta_records
def get_coverage(raw_read_coverage):
if VERBOSE: sys.stderr.write('Calculating read coverage.\n')
read_coverage = {}
for (chrm, strand), reads_data in list(raw_read_coverage.items()):
max_end = max(r_data.end for r_data in reads_data)
chrm_coverage = np.zeros(max_end, dtype=np.int_)
for r_data in reads_data:
chrm_coverage[r_data.start:r_data.end] += 1
read_coverage[(chrm, strand)] = chrm_coverage
return read_coverage
def get_read_base_means(r_data):
try:
read_data = h5py.File(r_data.fn, 'r')
except IOError:
# probably truncated file
return None
events_slot = '/'.join((
'/Analyses', r_data.corr_group, 'Events'))
if events_slot not in read_data:
return None
read_means = read_data[events_slot]['norm_mean']
if r_data.strand == '-':
read_means = read_means[::-1]
return read_means
def get_reads_base_means(chrm_strand_reads, chrm_len, rev_strand):
base_sums = np.zeros(chrm_len)
base_cov = np.zeros(chrm_len, dtype=np.int_)
for r_data in chrm_strand_reads:
# extract read means data so data across all chrms is not
# in RAM at one time
read_means = get_read_base_means(r_data)
if read_means is None: continue
base_sums[r_data.start:
r_data.start + len(read_means)] += read_means
base_cov[r_data.start:r_data.start + len(read_means)] += 1
return base_sums / base_cov
def get_base_means(raw_read_coverage, chrm_sizes):
# ignore divide by zero errors that occur where there is no
# coverage. Need to correct nan values after subtracting two sets of
# coverage so leave as nan for now
old_err_settings = np.seterr(all='ignore')
# take the mean over all signal overlapping each base
mean_base_signal = {}
for chrm, strand in [(c, s) for c in list(chrm_sizes.keys())
for s in ('+', '-')]:
if (chrm, strand) in raw_read_coverage:
cs_base_means = get_reads_base_means(
raw_read_coverage[(chrm, strand)], chrm_sizes[chrm],
strand == '-')
else:
cs_base_means = np.empty(chrm_sizes[chrm])
cs_base_means[:] = np.nan
mean_base_signal[(chrm, strand)] = cs_base_means
_ = np.seterr(**old_err_settings)
return mean_base_signal
def get_reads_base_sds(chrm_strand_reads, chrm_len, rev_strand):
base_sd_sums = np.zeros(chrm_len)
base_cov = np.zeros(chrm_len, dtype=np.int_)
for r_data in chrm_strand_reads:
# extract read means data so data across all chrms is not
# in RAM at one time
try:
read_data = h5py.File(r_data.fn, 'r')
except IOError:
# probably truncated file
continue
events_slot = '/'.join((
'/Analyses', r_data.corr_group, 'Events'))
if events_slot not in read_data:
continue
read_sds = read_data[events_slot]['norm_stdev']
if rev_strand:
read_sds = read_sds[::-1]
base_sd_sums[r_data.start:
r_data.start + len(read_sds)] += read_sds
base_cov[r_data.start:r_data.start + len(read_sds)] += 1
return base_sd_sums / base_cov
def get_base_sds(raw_read_coverage, chrm_sizes):
# ignore divide by zero errors that occur where there is no
# | |
# Copyright 2017 The Abseil Authors.
#
# 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.
"""Contains base classes used to parse and convert arguments.
Do NOT import this module directly. Import the flags package and use the
aliases defined at the package level instead.
"""
import collections
import csv
import io
import string
from absl.flags import _helpers
def _is_integer_type(instance):
"""Returns True if instance is an integer, and not a bool."""
return (isinstance(instance, int) and
not isinstance(instance, bool))
class _ArgumentParserCache(type):
"""Metaclass used to cache and share argument parsers among flags."""
_instances = {}
def __call__(cls, *args, **kwargs):
"""Returns an instance of the argument parser cls.
This method overrides behavior of the __new__ methods in
all subclasses of ArgumentParser (inclusive). If an instance
for cls with the same set of arguments exists, this instance is
returned, otherwise a new instance is created.
If any keyword arguments are defined, or the values in args
are not hashable, this method always returns a new instance of
cls.
Args:
*args: Positional initializer arguments.
**kwargs: Initializer keyword arguments.
Returns:
An instance of cls, shared or new.
"""
if kwargs:
return type.__call__(cls, *args, **kwargs)
else:
instances = cls._instances
key = (cls,) + tuple(args)
try:
return instances[key]
except KeyError:
# No cache entry for key exists, create a new one.
return instances.setdefault(key, type.__call__(cls, *args))
except TypeError:
# An object in args cannot be hashed, always return
# a new instance.
return type.__call__(cls, *args)
# NOTE about Genericity and Metaclass of ArgumentParser.
# (1) In the .py source (this file)
# - is not declared as Generic
# - has _ArgumentParserCache as a metaclass
# (2) In the .pyi source (type stub)
# - is declared as Generic
# - doesn't have a metaclass
# The reason we need this is due to Generic having a different metaclass
# (for python versions <= 3.7) and a class can have only one metaclass.
#
# * Lack of metaclass in .pyi is not a deal breaker, since the metaclass
# doesn't affect any type information. Also type checkers can check the type
# parameters.
# * However, not declaring ArgumentParser as Generic in the source affects
# runtime annotation processing. In particular this means, subclasses should
# inherit from `ArgumentParser` and not `ArgumentParser[SomeType]`.
# The corresponding DEFINE_someType method (the public API) can be annotated
# to return FlagHolder[SomeType].
class ArgumentParser(metaclass=_ArgumentParserCache):
"""Base class used to parse and convert arguments.
The parse() method checks to make sure that the string argument is a
legal value and convert it to a native type. If the value cannot be
converted, it should throw a 'ValueError' exception with a human
readable explanation of why the value is illegal.
Subclasses should also define a syntactic_help string which may be
presented to the user to describe the form of the legal values.
Argument parser classes must be stateless, since instances are cached
and shared between flags. Initializer arguments are allowed, but all
member variables must be derived from initializer arguments only.
"""
syntactic_help = ''
def parse(self, argument):
"""Parses the string argument and returns the native value.
By default it returns its argument unmodified.
Args:
argument: string argument passed in the commandline.
Raises:
ValueError: Raised when it fails to parse the argument.
TypeError: Raised when the argument has the wrong type.
Returns:
The parsed value in native type.
"""
if not isinstance(argument, str):
raise TypeError('flag value must be a string, found "{}"'.format(
type(argument)))
return argument
def flag_type(self):
"""Returns a string representing the type of the flag."""
return 'string'
def _custom_xml_dom_elements(self, doc):
"""Returns a list of minidom.Element to add additional flag information.
Args:
doc: minidom.Document, the DOM document it should create nodes from.
"""
del doc # Unused.
return []
class ArgumentSerializer(object):
"""Base class for generating string representations of a flag value."""
def serialize(self, value):
"""Returns a serialized string of the value."""
return _helpers.str_or_unicode(value)
class NumericParser(ArgumentParser):
"""Parser of numeric values.
Parsed value may be bounded to a given upper and lower bound.
"""
def is_outside_bounds(self, val):
"""Returns whether the value is outside the bounds or not."""
return ((self.lower_bound is not None and val < self.lower_bound) or
(self.upper_bound is not None and val > self.upper_bound))
def parse(self, argument):
"""See base class."""
val = self.convert(argument)
if self.is_outside_bounds(val):
raise ValueError('%s is not %s' % (val, self.syntactic_help))
return val
def _custom_xml_dom_elements(self, doc):
elements = []
if self.lower_bound is not None:
elements.append(_helpers.create_xml_dom_element(
doc, 'lower_bound', self.lower_bound))
if self.upper_bound is not None:
elements.append(_helpers.create_xml_dom_element(
doc, 'upper_bound', self.upper_bound))
return elements
def convert(self, argument):
"""Returns the correct numeric value of argument.
Subclass must implement this method, and raise TypeError if argument is not
string or has the right numeric type.
Args:
argument: string argument passed in the commandline, or the numeric type.
Raises:
TypeError: Raised when argument is not a string or the right numeric type.
ValueError: Raised when failed to convert argument to the numeric value.
"""
raise NotImplementedError
class FloatParser(NumericParser):
"""Parser of floating point values.
Parsed value may be bounded to a given upper and lower bound.
"""
number_article = 'a'
number_name = 'number'
syntactic_help = ' '.join((number_article, number_name))
def __init__(self, lower_bound=None, upper_bound=None):
super(FloatParser, self).__init__()
self.lower_bound = lower_bound
self.upper_bound = upper_bound
sh = self.syntactic_help
if lower_bound is not None and upper_bound is not None:
sh = ('%s in the range [%s, %s]' % (sh, lower_bound, upper_bound))
elif lower_bound == 0:
sh = 'a non-negative %s' % self.number_name
elif upper_bound == 0:
sh = 'a non-positive %s' % self.number_name
elif upper_bound is not None:
sh = '%s <= %s' % (self.number_name, upper_bound)
elif lower_bound is not None:
sh = '%s >= %s' % (self.number_name, lower_bound)
self.syntactic_help = sh
def convert(self, argument):
"""Returns the float value of argument."""
if (_is_integer_type(argument) or isinstance(argument, float) or
isinstance(argument, str)):
return float(argument)
else:
raise TypeError(
'Expect argument to be a string, int, or float, found {}'.format(
type(argument)))
def flag_type(self):
"""See base class."""
return 'float'
class IntegerParser(NumericParser):
"""Parser of an integer value.
Parsed value may be bounded to a given upper and lower bound.
"""
number_article = 'an'
number_name = 'integer'
syntactic_help = ' '.join((number_article, number_name))
def __init__(self, lower_bound=None, upper_bound=None):
super(IntegerParser, self).__init__()
self.lower_bound = lower_bound
self.upper_bound = upper_bound
sh = self.syntactic_help
if lower_bound is not None and upper_bound is not None:
sh = ('%s in the range [%s, %s]' % (sh, lower_bound, upper_bound))
elif lower_bound == 1:
sh = 'a positive %s' % self.number_name
elif upper_bound == -1:
sh = 'a negative %s' % self.number_name
elif lower_bound == 0:
sh = 'a non-negative %s' % self.number_name
elif upper_bound == 0:
sh = 'a non-positive %s' % self.number_name
elif upper_bound is not None:
sh = '%s <= %s' % (self.number_name, upper_bound)
elif lower_bound is not None:
sh = '%s >= %s' % (self.number_name, lower_bound)
self.syntactic_help = sh
def convert(self, argument):
"""Returns the int value of argument."""
if _is_integer_type(argument):
return argument
elif isinstance(argument, str):
base = 10
if len(argument) > 2 and argument[0] == '0':
if argument[1] == 'o':
base = 8
elif argument[1] == 'x':
base = 16
return int(argument, base)
else:
raise TypeError('Expect argument to be a string or int, found {}'.format(
type(argument)))
def flag_type(self):
"""See base class."""
return 'int'
class BooleanParser(ArgumentParser):
"""Parser of boolean values."""
def parse(self, argument):
"""See base class."""
if isinstance(argument, str):
if argument.lower() in ('true', 't', '1'):
return True
elif argument.lower() in ('false', 'f', '0'):
return False
else:
raise ValueError('Non-boolean argument to boolean flag', argument)
elif isinstance(argument, int):
# Only allow bool or integer 0, 1.
# Note that float 1.0 == True, 0.0 == False.
bool_value = bool(argument)
if argument == bool_value:
return bool_value
else:
raise ValueError('Non-boolean argument to boolean flag', argument)
raise TypeError('Non-boolean | |
k.dte.dt('en', u"in order", u"Excellent.")
k.dte.dt('de', u"in ordnung", u"Ausgezeichnet.")
k.dte.dt('en', u"in the bag", u"What bag?")
k.dte.dt('de', u"in der tasche", u"Welche Tasche?")
k.dte.dt('en', u"in the moment not", u"Maybe later?")
k.dte.dt('de', u"im moment nicht", u"Vielleicht später?")
k.dte.dt('en', u"in which respect", u"Which respect comes to mind?")
k.dte.dt('de', u"in welcher hinsicht", u"Welche Hinsicht fällt Dir ein?")
k.dte.dt('en', u"in your brain", u"You mean my reasoning engine?")
k.dte.dt('de', u"in deinem gehirn", u"Du meinst meine Logik?")
k.dte.dt('en', u"indeed", u"Please, continue.")
k.dte.dt('de', u"allerdings", u"Bitte, sprich weiter.")
k.dte.dt('en', u"is it you", u"Yes, it's me.")
k.dte.dt('de', u"bist du es", u"Ja, ich bin es.")
k.dte.dt('en', [u"interesting",
u"is clear"],
u"I see.")
k.dte.dt('de', [u"interessant",
u"ist klar"],
u"Verstehe.")
k.dte.dt('en', [u"is that an advantage",
u"is that pleasant",
u"is that so much"],
u"Not sure.")
k.dte.dt('de', [u"ist das ein vorteil",
u"ist das angenehm",
u"ist das so viel"],
u"Bin nicht sicher.")
k.dte.dt('en', u"it depends", u"")
k.dte.dt('de', u"kommt ganz darauf an", u"")
k.dte.dt('en', u"it is 42", u"I love the Hitchhiker's Guide.")
k.dte.dt('de', u"sie lautet zweiundvierzig", u"Ich liebe per Anhalter durch die Galaxis.")
k.dte.dt('en', u"it is not necessary", u"Sure?")
k.dte.dt('de', u"es ist nicht nötig", u"Sicher?")
k.dte.dt('en', u"it is very good", u"Excellent.")
k.dte.dt('de', u"es ist sehr gut", u"Ausgezeichnet.")
k.dte.dt('en', u"it works", u"Good.")
k.dte.dt('de', u"es geht", u"Gut.")
k.dte.dt('en', u"it's good", u"Glad to hear that!")
k.dte.dt('de', u"das ist gut", u"Freue mich, das zu hören.")
k.dte.dt('en', u"it's not easy", u"But worth doing anyway?")
k.dte.dt('de', u"es ist ja auch nicht einfach", u"Aber es lohnt sich trotzdem?")
k.dte.dt('en', u"it's perfectly alright", u"Good.")
k.dte.dt('de', u"ganz okay", u"Gut.")
k.dte.dt('en', u"just because", u"Can you elaborate?")
k.dte.dt('de', u"einfach so", u"Kannst Du das weiter ausführen?")
k.dte.dt('en', u"just like you", u"Like me?")
k.dte.dt('de', u"so wie du", u"Wie ich?")
k.dte.dt('en', u"kind of", u"Please, go on.")
k.dte.dt('de', u"so in der art", u"Sprich bitte weiter.")
k.dte.dt('en', u"look at all the consequences", u"Sure.")
k.dte.dt('de', u"schau dir alle folgen an", u"Klar.")
k.dte.dt('en', u"make a suggestion (for once|)", u"Don't worry, be happy.")
k.dte.dt('de', u"mach (mal|) einen vorschlag", u"Sorge Dich nicht, sei fröhlich.")
k.dte.dt('en', u"may be", u"how likely do you think?")
k.dte.dt('de', u"kann sein", u"wie wahrscheinlich, glaubst du?")
k.dte.dt('en', [u"me too",
u"me",
u"me, yes"],
u"you?")
k.dte.dt('de', [u"mir auch",
u"ich denn",
u"ich schon"],
u"Du?")
k.dte.dt('en', [u"mine also",
u"mine too"],
u"you?")
k.dte.dt('de', [u"meins auch",
u"meiner auch"],
u"Du?")
k.dte.dt('en', u"more often", u"how often then?")
k.dte.dt('de', u"öfters", u"Wie oft dann?")
k.dte.dt('en', u"my also", u"I see.")
k.dte.dt('de', u"meine auch", u"Verstehe.")
k.dte.dt('en', u"naturally", u"OK")
k.dte.dt('de', u"natürlich", u"OK")
k.dte.dt('en', [u"neither do i",
u"never in life"],
u"Not?")
k.dte.dt('de', [u"ich auch nicht",
u"nie im leben"],
u"Nicht?")
k.dte.dt('en', u"never mind", u"Please continue.")
k.dte.dt('de', u"keine ursache", u"Bitte setze fort.")
k.dte.dt('en', u"no idea", u"Really?")
k.dte.dt('de', u"keine ahnung", u"Wirklich?")
k.dte.dt('en', u"no matter", u"Sure?")
k.dte.dt('de', u"egal", u"Sicher?")
k.dte.dt('en', u"no more and no less", u"You sound pretty sure?")
k.dte.dt('de', u"nicht mehr und nicht weniger", u"Du klingst ziemlich sicher?")
k.dte.dt('en', u"no problem", u"Sure.")
k.dte.dt('de', u"kein problem", u"Sicher.")
k.dte.dt('en', u"none", u"not one?")
k.dte.dt('de', u"keiner", u"nichtmal einer?")
k.dte.dt('en', u"not always", u"I see.")
k.dte.dt('de', u"nicht immer", u"Verstehe.")
k.dte.dt('en', u"not as much", u"OK, less then?")
k.dte.dt('de', u"nicht so viel", u"OK, also weniger?")
k.dte.dt('en', u"not at all", u"Are you sure?")
k.dte.dt('de', u"überhaupt nicht", u"Bist Du sicher?")
k.dte.dt('en', u"not exactly", u"I see.")
k.dte.dt('de', u"nicht genau", u"Verstehe.")
k.dte.dt('en', u"not maybe", u"But?")
k.dte.dt('de', u"nicht vielleicht", u"Sondern?")
k.dte.dt('en', u"not me", u"Anyone else?")
k.dte.dt('de', u"ich nicht", u"Jemand anderes?")
k.dte.dt('en', u"not necessarily", u"I see.")
k.dte.dt('de', u"nicht unbedingt", u"Verstehe.")
k.dte.dt('en', u"not often", u"But from time to time?")
k.dte.dt('de', u"nicht oft", u"Aber gelegentlich?")
k.dte.dt('en', u"not quite", u"So?")
k.dte.dt('de', u"nicht ganz", u"Also?")
k.dte.dt('en', u"not really", u"What do you mean?")
k.dte.dt('de', u"nicht wirklich", u"Was meinst Du damit?")
k.dte.dt('en', u"not soon but right now", u"Ok, now then.")
k.dte.dt('de', u"nicht gleich sondern jetzt", u"Gut, also jetzt.")
k.dte.dt('en', u"not that i know", u"I see.")
k.dte.dt('de', u"nicht dass ich wüsste", u"Verstehe.")
k.dte.dt('en', u"not yet", u"Some day maybe?")
k.dte.dt('de', u"noch nicht", u"Irgendwann mal vielleicht?")
k.dte.dt('en', u"not you", u"Not me?")
k.dte.dt('de', u"nicht du", u"Nicht ich?")
k.dte.dt('en', [u"nothing else",
u"nothing"],
u"Absolutely nothing?")
k.dte.dt('de', [u"nichts weiter",
u"nix"],
u"Gat nichts?")
k.dte.dt('en', u"now", u"right now?")
k.dte.dt('de', u"jetzt", u"genau jetzt?")
k.dte.dt('en', u"obviously", u"I see.")
k.dte.dt('de', u"offensichtlich", u"Verstehe.")
k.dte.dt('en', u"often", u"How often?")
k.dte.dt('de', u"oftmals", u"Wie oft?")
k.dte.dt('en', u"on everything", u"Really everything?")
k.dte.dt('de', u"auf alles", u"Wirklich alles?")
k.dte.dt('en', u"once again", u"Again?")
k.dte.dt('de', u"noch einmal", u"Nochmal?")
k.dte.dt('en', u"only like that", u"I see.")
k.dte.dt('de', u"nur so", u"Verstehe.")
k.dte.dt('en', u"go ahead", u"OK then.")
k.dte.dt('de', u"nur zu", u"Alles klar.")
k.dte.dt('en', u"only with you", u"With me?")
k.dte.dt('de', u"nur mit dir", u"Mit mir?")
k.dte.dt('en', u"probably", u"probably.")
k.dte.dt('de', u"wahrscheinlich", u"wahrscheinlich.")
k.dte.dt('en', u"rare", u"How rare?")
k.dte.dt('de', u"selten", u"Wie selten?")
k.dte.dt('en', [u"guess anyway",
u"guess"],
u"I am no good at guessing.")
k.dte.dt('de', [u"rate trotzdem",
u"rate"],
u"Ich bin nicht gut im raten.")
k.dte.dt('en', u"real", u"not artificial?")
k.dte.dt('de', u"echt", u"nicht künstlich?")
k.dte.dt('en', u"seriously", u"I am serious.")
k.dte.dt('de', u"im ernst", u"Das ist mein Ernst.")
k.dte.dt('en', u"so maybe", u"Why maybe?")
k.dte.dt('de', u"also vielleicht doch", u"Warum vielleicht?")
k.dte.dt('en', u"so probably not", u"Sure?")
k.dte.dt('de', u"also wohl eher nicht", u"Sicher?")
k.dte.dt('en', u"so so", u"Really?")
k.dte.dt('de', u"soso", u"Wirklich?")
k.dte.dt('en', u"so what", u"ah.")
k.dte.dt('de', u"na und", u"Ah.")
k.dte.dt('en', u"so", u"You got an idea?")
k.dte.dt('de', u"also", u"Du hast eine Idee?")
k.dte.dt('en', [u"sometimes not",
u"sometimes"],
u"How often?")
k.dte.dt('de', [u"manchmal auch nicht",
u"manchmal"],
u"Wie oft?")
k.dte.dt('en', u"sure, of course", u"Of course.")
k.dte.dt('de', u"na klar", u"Natürlich.")
k.dte.dt('en', [u"tell me more",
u"tell me"],
u"What would you like to know?")
k.dte.dt('de', [u"erzähl mir mehr",
u"sag es mir"],
u"Was möchtest Du wissen?")
k.dte.dt('en', u"that all depends", u"It always does.")
k.dte.dt('de', u"das kommt ganz darauf an", u"Das tut es immer.")
k.dte.dt('en', u"that can still arise", u"Sure.")
k.dte.dt('de', u"das kann sich ja noch ergeben", u"Sicher.")
k.dte.dt('en', u"that does not matter", u"Are you sure?")
k.dte.dt('de', u"das macht nichts", u"Bist Du sicher?")
k.dte.dt('en', u"that is correct", u"Good.")
k.dte.dt('de', u"das ist korrekt", u"Gut.")
k.dte.dt('en', u"that is funny", u"Does that make you happy?")
k.dte.dt('de', u"das ist aber komisch", u"Stimmt dich das heiter?")
k.dte.dt('en', [u"that is incredible",
u"that is interesting"],
u"I think so too.")
k.dte.dt('de', [u"das ist ja unfassbar",
u"das ist interessant"],
u"Denke ich auch.")
k.dte.dt('en', u"that is not a rumor", u"Are you sure?")
k.dte.dt('de', u"das ist kein gerücht", u"Bist Du sicher?")
k.dte.dt('en', u"that is private", u"I respect that.")
k.dte.dt('de', u"das ist privatsache", u"Das respektiere ich natürlich.")
k.dte.dt('en', u"that is ridiculous", u"Are you sure?")
k.dte.dt('de', u"das ist ja lächerlich", u"Bust Du sicher?")
k.dte.dt('en', u"that is sad", u"some things just are sad.")
k.dte.dt('de', u"das ist aber traurig", u"Manche Dinge sind einfach traurig.")
k.dte.dt('en', u"that is so defined", u"I see.")
k.dte.dt('de', u"das ist so definiert", u"Verstehe.")
k.dte.dt('en', u"that is too vague for me", u"What seems to be unclear?")
k.dte.dt('de', u"das ist mir zu vage", u"Was erscheint Dir unklar?")
k.dte.dt('en', u"that is very interesting", u"I feel that way too.")
k.dte.dt('de', u"das ist ja interessant", u"Finde ich auch.")
k.dte.dt('en', [u"that is very smart",
u"that would make sense"],
[u"Good",
u"Cool"])
k.dte.dt('de', [u"das ist sehr schlau",
u"würde das sinn machen"],
[u"Gut",
u"Cool"])
k.dte.dt('en', u"that was it", u"Finished?")
k.dte.dt('de', u"das wars", u"Fertig?")
k.dte.dt('en', u"that was me", u"You?")
k.dte.dt('de', u"das war ich", u"Du?")
k.dte.dt('en', u"that would have surprised me too", u"Sure.")
k.dte.dt('de', u"das hätte mich auch gewundert", u"Sicher.")
k.dte.dt('en', u"that's a saying", u"I see.")
k.dte.dt('de', u"das ist eine redensart", u"Verstehe.")
k.dte.dt('en', u"that's all", u"Everything?")
k.dte.dt('de', u"ist das alles", u"Alles?")
k.dte.dt('en', u"that's an interesting subject", u"I think so too.")
k.dte.dt('de', u"das ist ein interessantes fach", u"Denke ich auch.")
k.dte.dt('en', u"that's boring", u"What would be more interesting?")
k.dte.dt('de', u"das ist doch langweilig", u"Was wäre interessanter?")
k.dte.dt('en', u"that's funny", u"You like it?")
k.dte.dt('de', u"das ist komisch", u"Gefällt es Dir?")
k.dte.dt('en', u"that's great", u"Cool")
k.dte.dt('de', u"das ist toll", u"Cool")
k.dte.dt('en', u"that's impossible", u"Really?")
k.dte.dt('de', u"das ist unmöglich", u"Wirklich?")
k.dte.dt('en', u"that's it", u"Finished?")
k.dte.dt('de', u"das wars schon", u"Fertig?")
k.dte.dt('en', u"that's ok for me", u"Very good.")
k.dte.dt('de', u"das ist mir recht", u"Sehr gut.")
k.dte.dt('en', u"that's the way it goes", u"I see.")
k.dte.dt('de', u"ach so ist das", u"Verstehe.")
k.dte.dt('en', u"that's what i think", u"What else comes to mind?")
k.dte.dt('de', u"das denke ich", u"Was fällt Dir noch dazu ein?")
k.dte.dt('en', u"that's what i'm asking you", u"Me?")
k.dte.dt('de', u"das frage ich ja dich", u"Mich?")
| |
# (c) 2012-2014, <NAME> <<EMAIL>>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.compat.six import iteritems, string_types
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.module_utils._text import to_native
from ansible.parsing.mod_args import ModuleArgsParser
from ansible.parsing.yaml.objects import AnsibleBaseYAMLObject, AnsibleMapping, AnsibleUnicode
from ansible.plugins import lookup_loader
from ansible.playbook.attribute import FieldAttribute
from ansible.playbook.base import Base
from ansible.playbook.become import Become
from ansible.playbook.block import Block
from ansible.playbook.conditional import Conditional
from ansible.playbook.loop_control import LoopControl
from ansible.playbook.role import Role
from ansible.playbook.taggable import Taggable
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
__all__ = ['Task']
class Task(Base, Conditional, Taggable, Become):
"""
A task is a language feature that represents a call to a module, with given arguments and other parameters.
A handler is a subclass of a task.
Usage:
Task.load(datastructure) -> Task
Task.something(...)
"""
# =================================================================================
# ATTRIBUTES
# load_<attribute_name> and
# validate_<attribute_name>
# will be used if defined
# might be possible to define others
_args = FieldAttribute(isa='dict', default=dict())
_action = FieldAttribute(isa='string')
_async = FieldAttribute(isa='int', default=0)
_changed_when = FieldAttribute(isa='list', default=[])
_delay = FieldAttribute(isa='int', default=5)
_delegate_to = FieldAttribute(isa='string')
_delegate_facts = FieldAttribute(isa='bool', default=False)
_failed_when = FieldAttribute(isa='list', default=[])
_loop = FieldAttribute(isa='string', private=True, inherit=False)
_loop_args = FieldAttribute(isa='list', private=True, inherit=False)
_loop_control = FieldAttribute(isa='class', class_type=LoopControl, inherit=False)
_name = FieldAttribute(isa='string', default='')
_notify = FieldAttribute(isa='list')
_poll = FieldAttribute(isa='int', default=10)
_register = FieldAttribute(isa='string')
_retries = FieldAttribute(isa='int')
_until = FieldAttribute(isa='list', default=[])
def __init__(self, block=None, role=None, task_include=None):
''' constructors a task, without the Task.load classmethod, it will be pretty blank '''
self._role = role
self._parent = None
if task_include:
self._parent = task_include
else:
self._parent = block
super(Task, self).__init__()
def get_path(self):
''' return the absolute path of the task with its line number '''
path = ""
if hasattr(self, '_ds') and hasattr(self._ds, '_data_source') and hasattr(self._ds, '_line_number'):
path = "%s:%s" % (self._ds._data_source, self._ds._line_number)
return path
def get_name(self):
''' return the name of the task '''
if self._role and self.name and ("%s : " % self._role._role_name) not in self.name:
return "%s : %s" % (self._role.get_name(), self.name)
elif self.name:
return self.name
else:
if self._role:
return "%s : %s" % (self._role.get_name(), self.action)
else:
return "%s" % (self.action,)
def _merge_kv(self, ds):
if ds is None:
return ""
elif isinstance(ds, string_types):
return ds
elif isinstance(ds, dict):
buf = ""
for (k,v) in iteritems(ds):
if k.startswith('_'):
continue
buf = buf + "%s=%s " % (k,v)
buf = buf.strip()
return buf
@staticmethod
def load(data, block=None, role=None, task_include=None, variable_manager=None, loader=None):
t = Task(block=block, role=role, task_include=task_include)
return t.load_data(data, variable_manager=variable_manager, loader=loader)
def __repr__(self):
''' returns a human readable representation of the task '''
if self.get_name() == 'meta':
return "TASK: meta (%s)" % self.args['_raw_params']
else:
return "TASK: %s" % self.get_name()
def _preprocess_loop(self, ds, new_ds, k, v):
''' take a lookup plugin name and store it correctly '''
loop_name = k.replace("with_", "")
if new_ds.get('loop') is not None:
raise AnsibleError("duplicate loop in task: %s" % loop_name, obj=ds)
if v is None:
raise AnsibleError("you must specify a value when using %s" % k, obj=ds)
new_ds['loop'] = loop_name
new_ds['loop_args'] = v
def preprocess_data(self, ds):
'''
tasks are especially complex arguments so need pre-processing.
keep it short.
'''
assert isinstance(ds, dict)
# the new, cleaned datastructure, which will have legacy
# items reduced to a standard structure suitable for the
# attributes of the task class
new_ds = AnsibleMapping()
if isinstance(ds, AnsibleBaseYAMLObject):
new_ds.ansible_pos = ds.ansible_pos
# use the args parsing class to determine the action, args,
# and the delegate_to value from the various possible forms
# supported as legacy
args_parser = ModuleArgsParser(task_ds=ds)
try:
(action, args, delegate_to) = args_parser.parse()
except AnsibleParserError as e:
raise AnsibleParserError(to_native(e), obj=ds)
# the command/shell/script modules used to support the `cmd` arg,
# which corresponds to what we now call _raw_params, so move that
# value over to _raw_params (assuming it is empty)
if action in ('command', 'shell', 'script'):
if 'cmd' in args:
if args.get('_raw_params', '') != '':
raise AnsibleError("The 'cmd' argument cannot be used when other raw parameters are specified."
" Please put everything in one or the other place.", obj=ds)
args['_raw_params'] = args.pop('cmd')
new_ds['action'] = action
new_ds['args'] = args
new_ds['delegate_to'] = delegate_to
# we handle any 'vars' specified in the ds here, as we may
# be adding things to them below (special handling for includes).
# When that deprecated feature is removed, this can be too.
if 'vars' in ds:
# _load_vars is defined in Base, and is used to load a dictionary
# or list of dictionaries in a standard way
new_ds['vars'] = self._load_vars(None, ds.get('vars'))
else:
new_ds['vars'] = dict()
for (k,v) in iteritems(ds):
if k in ('action', 'local_action', 'args', 'delegate_to') or k == action or k == 'shell':
# we don't want to re-assign these values, which were
# determined by the ModuleArgsParser() above
continue
elif k.replace("with_", "") in lookup_loader:
self._preprocess_loop(ds, new_ds, k, v)
else:
# pre-2.0 syntax allowed variables for include statements at the
# top level of the task, so we move those into the 'vars' dictionary
# here, and show a deprecation message as we will remove this at
# some point in the future.
if action == 'include' and k not in self._valid_attrs and k not in self.DEPRECATED_ATTRIBUTES:
display.deprecated("Specifying include variables at the top-level of the task is deprecated."
" Please see:\nhttp://docs.ansible.com/ansible/playbooks_roles.html#task-include-files-and-encouraging-reuse\n\n"
" for currently supported syntax regarding included files and variables")
new_ds['vars'][k] = v
else:
new_ds[k] = v
return super(Task, self).preprocess_data(new_ds)
def _load_loop_control(self, attr, ds):
if not isinstance(ds, dict):
raise AnsibleParserError(
"the `loop_control` value must be specified as a dictionary and cannot "
"be a variable itself (though it can contain variables)",
obj=ds,
)
return LoopControl.load(data=ds, variable_manager=self._variable_manager, loader=self._loader)
def post_validate(self, templar):
'''
Override of base class post_validate, to also do final validation on
the block and task include (if any) to which this task belongs.
'''
if self._parent:
self._parent.post_validate(templar)
super(Task, self).post_validate(templar)
def _post_validate_loop_args(self, attr, value, templar):
'''
Override post validation for the loop args field, which is templated
specially in the TaskExecutor class when evaluating loops.
'''
return value
def _post_validate_environment(self, attr, value, templar):
'''
Override post validation of vars on the play, as we don't want to
template these too early.
'''
if value is None:
return dict()
elif isinstance(value, list):
if len(value) == 1:
return templar.template(value[0], convert_bare=True)
else:
env = []
for env_item in value:
if isinstance(env_item, (string_types, AnsibleUnicode)) and env_item in templar._available_variables:
env[env_item] = templar.template(env_item, convert_bare=False)
elif isinstance(value, dict):
env = dict()
for env_item in value:
if isinstance(env_item, (string_types, AnsibleUnicode)) and env_item in templar._available_variables:
env[env_item] = templar.template(value[env_item], convert_bare=False)
# at this point it should be a simple string
return templar.template(value, convert_bare=True)
def _post_validate_changed_when(self, attr, value, templar):
'''
changed_when is evaluated after the execution of the task is complete,
and should not be templated during the regular post_validate step.
'''
return value
def _post_validate_failed_when(self, attr, value, templar):
'''
failed_when is evaluated after the execution of the task is complete,
and should not be templated during the regular post_validate step.
'''
return value
def _post_validate_until(self, attr, value, templar):
'''
until is evaluated after the execution of the task is complete,
and should not be templated during the regular post_validate step.
'''
return value
def get_vars(self):
all_vars = dict()
if self._parent:
all_vars.update(self._parent.get_vars())
all_vars.update(self.vars)
if 'tags' in all_vars:
del all_vars['tags']
if 'when' in all_vars:
del all_vars['when']
return all_vars
def get_include_params(self):
all_vars = dict()
if self._parent:
all_vars.update(self._parent.get_include_params())
if self.action in ('include', 'include_role'):
all_vars.update(self.vars)
return all_vars
def copy(self, exclude_parent=False, exclude_tasks=False):
new_me = super(Task, self).copy()
new_me._parent | |
import uuid
from fhirclient.models import (
observation as obx,
meta as ma,
fhirreference as fr,
fhirdate as fd,
)
from app import (
Coding,
CodeableConcept,
Identifier,
Quantity,
Component
)
# generic FHIR Observation class
class Observation:
def __init__(self, resourceId, profile, identifier, status, category, code, subject, effectiveDate, valueQuantity, valueCodeableConcept, valueInteger, dataAbsentReason, interpretation, note, bodySite, method, referenceRange, member, component):
self.resourceId = resourceId
self.profile = profile
self.identifier = identifier
self.status = status
self.category = category
self.code = code
self.subject = subject
self.effectiveDate = effectiveDate
self.valueQuantity = valueQuantity
self.valueCodeableConcept = valueCodeableConcept
self.valueInteger = valueInteger
self.dataAbsentReason = dataAbsentReason
self.interpretation = interpretation
self.note = note
self.bodySite = bodySite
self.method = method
self.referenceRange = referenceRange
self.member = member
self.component = component
def to_fhir(self):
observation = obx.Observation()
resourceId = self.resourceId
observation.id = str(resourceId)
if self.profile == None:
pass
else:
meta = ma.Meta()
meta.profile = self.profile
observation.meta = meta
identifier = self.identifier
observation.identifier = identifier
status = self.status
observation.status = status
category = self.category
observation.category = [category]
code = self.code
observation.code = code
subject = fr.FHIRReference()
subject.reference = 'Patient/' + str(self.subject)
observation.subject = subject
effectiveDate = fd.FHIRDate(self.effectiveDate)
observation.effectiveDateTime = effectiveDate
valueQuantity = self.valueQuantity
observation.valueQuantity = valueQuantity
valueCodeableConcept = self.valueCodeableConcept
observation.valueCodeableConcept = valueCodeableConcept
valueInteger = self.valueInteger
observation.valueInteger = valueInteger
dataAbsentReason = self.dataAbsentReason
observation.dataAbsentReason = dataAbsentReason
interpretation = self.interpretation
observation.interpretation = interpretation
note = self.note
observation.note = note
bodySite = self.bodySite
observation.bodySite = bodySite
method = self.method
observation.method = method
referenceRange = self.referenceRange
observation.referenceRange = referenceRange
if self.member == None:
pass
else:
members = []
for member in self.member:
members.append(member)
observation.hasMember = members
if self.component == None:
pass
else:
components = []
for component in self.component:
components.append(component)
observation.component = components
return observation
# paO2
def create_oxygen_partial_pressure(patId, effectiveDateTime, valuePaCO2):
resourceId = uuid.uuid4()
profile = ['https://www.netzwerk-universitaetsmedizin.de/fhir/StructureDefinition/carbon-dioxide-partial-pressure']
idfTypeSystem = 'http://terminology.hl7.org/CodeSystem/v2-0203'
idfTypeCode = 'OBI'
idfTypeCoding = Coding.Coding(system=idfTypeSystem, version=None, code=idfTypeCode, display=None)
idfTypeCoding = [idfTypeCoding.to_fhir()]
idfType = CodeableConcept.CodeableConcept(coding=idfTypeCoding, text=None, extension=None)
idfType = idfType.to_fhir()
idfSystem = 'https://www.charite.de/fhir/CodeSystem/lab-identifiers'
idfCode = '2019-8_paCO2'
idfAssigner = 'Charité'
obsIdentifier = Identifier.Identifier(use=None, idfType=idfType, system=idfSystem, value=idfCode, period=None, assigner=idfAssigner)
obsIdentifier = [obsIdentifier.to_fhir()]
obsStatus = 'final'
categoryLoincSystem = 'http://loinc.org'
categoryLoincCode = '26436-6'
categoryLoincCoding = Coding.Coding(system=categoryLoincSystem, version=None, code=categoryLoincCode, display=None)
categoryLoincCoding = categoryLoincCoding.to_fhir()
categoryObsSystem = 'http://terminology.hl7.org/CodeSystem/observation-category'
categoryObsCode = 'laboratory'
categoryObsCoding = Coding.Coding(system=categoryObsSystem, version=None, code=categoryObsCode, display=None)
categoryObsCoding = categoryObsCoding.to_fhir()
categoryLoincSystemstudies = 'http://loinc.org'
categoryLoincCodestudies = '18767-4'
categoryLoincCodingstudies = Coding.Coding(system=categoryLoincSystemstudies, version=None, code=categoryLoincCodestudies, display=None)
categoryLoincCodingstudies = categoryLoincCodingstudies.to_fhir()
obsCategory = CodeableConcept.CodeableConcept(coding=[categoryLoincCoding, categoryObsCoding, categoryLoincCodingstudies], text=None, extension=None)
obsCategory = obsCategory.to_fhir()
obsCodeSystem = 'http://loinc.org'
obsCodeCode = '2019-8'
obsCodeDisplay = 'Carbon dioxide [Partial pressure] in Arterial blood'
obsCodeCoding = Coding.Coding(system=obsCodeSystem, version=None, code=obsCodeCode, display=obsCodeDisplay)
obsCodeCoding = [obsCodeCoding.to_fhir()]
obsCodeText = 'paCO2'
obsCode = CodeableConcept.CodeableConcept(coding=obsCodeCoding, text=obsCodeText, extension=None)
obsCode = obsCode.to_fhir()
subject = patId
effectiveDate = effectiveDateTime
obsValueQuantityValue = valuePaCO2
obsValueQuantityUnit = 'mmHg'
obsValueQuantitySystem = 'http://unitsofmeasure.org'
obsValueQuantityCode = 'mm[Hg]'
obsValueQuantity = Quantity.Quantity(value=obsValueQuantityValue, comparator=None, unit=obsValueQuantityUnit, system=obsValueQuantitySystem, code=obsValueQuantityCode)
obsValueQuantity = obsValueQuantity.to_fhir()
obs = Observation(
resourceId=resourceId,
profile=profile,
identifier=obsIdentifier,
status=obsStatus,
category=obsCategory,
code=obsCode,
subject=subject,
effectiveDate=effectiveDate,
valueQuantity=obsValueQuantity,
valueCodeableConcept=None,
valueInteger=None,
dataAbsentReason=None,
interpretation=None,
note=None,
bodySite=None,
method=None,
referenceRange=None,
member=None,
component=None)
obs = obs.to_fhir()
return obs
# FiO2
def create_inhaled_oxygen_concentration(patId, effectiveDateTime, valueFiO2):
resourceId = uuid.uuid4()
profile = ['https://www.netzwerk-universitaetsmedizin.de/fhir/StructureDefinition/inhaled-oxygen-concentration']
idfTypeSystem = 'http://terminology.hl7.org/CodeSystem/v2-0203'
idfTypeCode = 'OBI'
idfTypeCoding = Coding.Coding(system=idfTypeSystem, version=None, code=idfTypeCode, display=None)
idfTypeCoding = [idfTypeCoding.to_fhir()]
idfType = CodeableConcept.CodeableConcept(coding=idfTypeCoding, text=None, extension=None)
idfType = idfType.to_fhir()
idfSystem = 'https://www.charite.de/fhir/CodeSystem/lab-identifiers'
idfCode = '3150-0_FiO2'
idfAssigner = 'Charité'
obsIdentifier = Identifier.Identifier(use=None, idfType=idfType, system=idfSystem, value=idfCode, period=None, assigner=idfAssigner)
obsIdentifier = [obsIdentifier.to_fhir()]
obsStatus = 'final'
categoryLoincSystem = 'http://loinc.org'
categoryLoincCode = '26436-6'
categoryLoincCoding = Coding.Coding(system=categoryLoincSystem, version=None, code=categoryLoincCode, display=None)
categoryLoincCoding = categoryLoincCoding.to_fhir()
categoryObsSystem = 'http://terminology.hl7.org/CodeSystem/observation-category'
categoryObsCode = 'laboratory'
categoryObsCoding = Coding.Coding(system=categoryObsSystem, version=None, code=categoryObsCode, display=None)
categoryObsCoding = categoryObsCoding.to_fhir()
categoryLoincSystemstudies = 'http://loinc.org'
categoryLoincCodestudies = '18767-4'
categoryLoincCodingstudies = Coding.Coding(system=categoryLoincSystemstudies, version=None, code=categoryLoincCodestudies, display=None)
categoryLoincCodingstudies = categoryLoincCodingstudies.to_fhir()
obsCategory = CodeableConcept.CodeableConcept(coding=[categoryLoincCoding, categoryObsCoding, categoryLoincCodingstudies], text=None, extension=None)
obsCategory = obsCategory.to_fhir()
obsCodeSystem = 'http://loinc.org'
obsCodeCode = '3150-0'
obsCodeDisplay = 'Inhaled oxygen concentration'
obsCodeCoding = Coding.Coding(system=obsCodeSystem, version=None, code=obsCodeCode, display=obsCodeDisplay)
obsCodeCoding = [obsCodeCoding.to_fhir()]
obsCodeText = 'FiO2'
obsCode = CodeableConcept.CodeableConcept(coding=obsCodeCoding, text=obsCodeText, extension=None)
obsCode = obsCode.to_fhir()
subject = patId
effectiveDate = effectiveDateTime
obsValueQuantityValue = valueFiO2
obsValueQuantityUnit = '%'
obsValueQuantitySystem = 'http://unitsofmeasure.org'
obsValueQuantityCode = '%'
obsValueQuantity = Quantity.Quantity(value=obsValueQuantityValue, comparator=None, unit=obsValueQuantityUnit, system=obsValueQuantitySystem, code=obsValueQuantityCode)
obsValueQuantity = obsValueQuantity.to_fhir()
obs = Observation(
resourceId=resourceId,
profile=profile,
identifier=obsIdentifier,
status=obsStatus,
category=obsCategory,
code=obsCode,
subject=subject,
effectiveDate=effectiveDate,
valueQuantity=obsValueQuantity,
valueCodeableConcept=None,
valueInteger=None,
dataAbsentReason=None,
interpretation=None,
note=None,
bodySite=None,
method=None,
referenceRange=None,
member=None,
component=None)
obs = obs.to_fhir()
return obs
# BodyWeight
def create_body_weight(patId, effectiveDateTime, valueKilogram, valueGram):
resourceId = uuid.uuid4()
profile = ['https://www.netzwerk-universitaetsmedizin.de/fhir/StructureDefinition/body-weight']
idfTypeSystem = 'http://terminology.hl7.org/CodeSystem/v2-0203'
idfTypeCode = 'OBI'
idfTypeCoding = Coding.Coding(system=idfTypeSystem, version=None, code=idfTypeCode, display=None)
idfTypeCoding = [idfTypeCoding.to_fhir()]
idfType = CodeableConcept.CodeableConcept(coding=idfTypeCoding, text=None, extension=None)
idfType = idfType.to_fhir()
idfSystem = 'https://www.charite.de/fhir/CodeSystem/observation-identifiers'
idfCode = '29463-7' + '_' + 'BodyWeight'
idfAssigner = 'Charité'
obsIdentifier = Identifier.Identifier(use=None, idfType=idfType, system=idfSystem, value=idfCode, period=None, assigner=idfAssigner)
obsIdentifier = [obsIdentifier.to_fhir()]
obsStatus = 'final'
categoryObsSystem = 'http://terminology.hl7.org/CodeSystem/observation-category'
categoryObsCode = 'vital-signs'
categoryObsCoding = Coding.Coding(system=categoryObsSystem, version=None, code=categoryObsCode, display=None)
categoryObsCoding = categoryObsCoding.to_fhir()
obsCategory = CodeableConcept.CodeableConcept(coding=[categoryObsCoding], text=None, extension=None)
obsCategory = obsCategory.to_fhir()
obsCodeSystemLn = 'http://loinc.org'
obsCodeCodeLn = '29463-7'
obsCodeDisplayLn = 'Body weight'
obsCodeCodingLn = Coding.Coding(system=obsCodeSystemLn, version=None, code=obsCodeCodeLn, display=obsCodeDisplayLn)
obsCodeCodingLn = obsCodeCodingLn.to_fhir()
obsCodeSystemSCT = 'http://snomed.info/sct'
obsCodeCodeSCT = '27113001'
obsCodeDisplaySCT = 'Body weight (observable entity)'
obsCodeCodingSCT = Coding.Coding(system=obsCodeSystemSCT, version=None, code=obsCodeCodeSCT, display=obsCodeDisplaySCT)
obsCodeCodingSCT = obsCodeCodingSCT.to_fhir()
obsCodeText = 'Body weight'
obsCode = CodeableConcept.CodeableConcept(coding=[obsCodeCodingLn, obsCodeCodingSCT], text=obsCodeText, extension=None)
obsCode = obsCode.to_fhir()
subject = patId
effectiveDate = effectiveDateTime
if valueKilogram == None:
pass
else:
obsQuantityValue = valueKilogram
obsQuantityUnit = 'kilogram'
obsQuantitySystem = 'http://unitsofmeasure.org'
obsQuantityCode = 'kg'
obsQuantity = Quantity.Quantity(value=obsQuantityValue, comparator=None, unit=obsQuantityUnit, system=obsQuantitySystem, code=obsQuantityCode)
obsQuantity = obsQuantity.to_fhir()
if valueGram == None:
pass
else:
obsQuantityValue = valueKilogram
obsQuantityUnit = 'gram'
obsQuantitySystem = 'http://unitsofmeasure.org'
obsQuantityCode = 'g'
obsQuantity = Quantity.Quantity(value=obsQuantityValue, comparator=None, unit=obsQuantityUnit, system=obsQuantitySystem, code=obsQuantityCode)
obsQuantity = obsQuantity.to_fhir()
obsBodyWeight = Observation(
resourceId=resourceId,
profile=profile,
identifier=obsIdentifier,
status=obsStatus,
category=obsCategory,
code=obsCode,
subject=subject,
effectiveDate=effectiveDate,
valueQuantity=obsQuantity,
valueCodeableConcept=None,
valueInteger=None,
dataAbsentReason=None,
interpretation=None,
note=None,
bodySite=None,
method=None,
referenceRange=None,
member=None,
component=None
)
obsBodyWeight = obsBodyWeight.to_fhir()
return obsBodyWeight
# Glasgow Coma Scale
def create_glasgow_coma_scale(patId, effectiveDateTime, valueTotalScore, valueEye, valueVerbal, valueMotor):
resourceId = uuid.uuid4()
profile = None
idfTypeSystem = 'http://terminology.hl7.org/CodeSystem/v2-0203'
idfTypeCode = 'OBI'
idfTypeCoding = Coding.Coding(system=idfTypeSystem, version=None, code=idfTypeCode, display=None)
idfTypeCoding = [idfTypeCoding.to_fhir()]
idfType = CodeableConcept.CodeableConcept(coding=idfTypeCoding, text=None, extension=None)
idfType = idfType.to_fhir()
idfSystem = 'https://www.charite.de/fhir/CodeSystem/observation-identifiers'
idfCode = '9269-2' + '_' + 'GlasgowComaScale'
idfAssigner = 'Charité'
obsIdentifier = Identifier.Identifier(use=None, idfType=idfType, system=idfSystem, value=idfCode, period=None, assigner=idfAssigner)
obsIdentifier = [obsIdentifier.to_fhir()]
obsStatus = 'final'
categoryObsSystem = 'http://terminology.hl7.org/CodeSystem/observation-category'
categoryObsCode = 'survey'
categoryObsCoding = Coding.Coding(system=categoryObsSystem, version=None, code=categoryObsCode, display=None)
categoryObsCoding = categoryObsCoding.to_fhir()
obsCategory = CodeableConcept.CodeableConcept(coding=[categoryObsCoding], text=None, extension=None)
obsCategory = obsCategory.to_fhir()
obsCodeSystem = 'http://loinc.org'
obsCodeCode = '9269-2'
obsCodeDisplay = 'Glasgow coma score total'
obsCodeCoding = Coding.Coding(system=obsCodeSystem, version=None, code=obsCodeCode, display=obsCodeDisplay)
obsCodeCoding = obsCodeCoding.to_fhir()
obsCodeSystemSCT = 'http://snomed.info/sct'
obsCodeCodeSCT = '248241002'
obsCodeDisplaySCT = 'Glasgow coma score (observable entity)'
obsCodeCodingSCT = Coding.Coding(system=obsCodeSystemSCT, version=None, code=obsCodeCodeSCT, display=obsCodeDisplaySCT)
obsCodeCodingSCT = obsCodeCodingSCT.to_fhir()
obsCodeText = 'Glasgow Coma Scale (GCS) score'
obsCode = CodeableConcept.CodeableConcept(coding=[obsCodeCoding, obsCodeCodingSCT], text=obsCodeText, extension=None)
obsCode = obsCode.to_fhir()
subject = patId
effectiveDate = effectiveDateTime
obsMethodSystem = 'http://snomed.info/sct'
obsMethodCode = '386554004'
obsMethodDisplay = 'Glasgow coma scale (assessment scale)'
obsMethodCoding = Coding.Coding(system=obsMethodSystem, version=None, code=obsMethodCode, display=obsMethodDisplay)
obsMethodCoding = obsMethodCoding.to_fhir()
obsMethod = CodeableConcept.CodeableConcept(coding=[obsMethodCoding], text=None, extension=None)
obsMethod = obsMethod.to_fhir()
obsQuantityValue = valueTotalScore
obsQuantityUnit = 'score'
obsQuantitySystem = 'http://unitsofmeasure.org'
obsQuantityCode = '{score}'
obsQuantity = Quantity.Quantity(value=obsQuantityValue, comparator=None, unit=obsQuantityUnit, system=obsQuantitySystem, code=obsQuantityCode)
obsQuantity = obsQuantity.to_fhir()
#Eye opening
verbalCompCodeSystemLn = 'http://loinc.org'
verbalCompCodeLn = '9267-6'
verbalCompCodeDisplayLn = 'Glasgow coma score eye opening'
verbalCompCodingLn = Coding.Coding(system=verbalCompCodeSystemLn, version=None, code=verbalCompCodeLn, display=verbalCompCodeDisplayLn)
verbalCompCodingLn = verbalCompCodingLn.to_fhir()
verbalCompCodeText = 'Eye opening response'
verbalCompCode = CodeableConcept.CodeableConcept(coding=[verbalCompCodingLn], text=verbalCompCodeText, extension=None)
verbalCompCode = verbalCompCode.to_fhir()
verbalCompValueInt = valueEye
verbalComp = Component.Component(code=verbalCompCode, valueQuantity=None, valueCodeableConcept=None, valueString=None, valueDateTime=None, valueInteger=verbalCompValueInt)
verbalComp = verbalComp.to_fhir()
# Verbal
verbalCompCodeSystemLn = 'http://loinc.org'
verbalCompCodeLn = '9270-0'
verbalCompCodeDisplayLn = 'Glasgow coma score verbal'
verbalCompCodingLn = Coding.Coding(system=verbalCompCodeSystemLn, version=None, code=verbalCompCodeLn, display=verbalCompCodeDisplayLn)
verbalCompCodingLn = verbalCompCodingLn.to_fhir()
verbalCompCodeText = 'Verbal response'
verbalCompCode = CodeableConcept.CodeableConcept(coding=[verbalCompCodingLn], text=verbalCompCodeText, extension=None)
verbalCompCode = verbalCompCode.to_fhir()
verbalCompValueInt = valueVerbal
verbalComp = Component.Component(code=verbalCompCode, valueQuantity=None, valueCodeableConcept=None, valueString=None, valueDateTime=None, valueInteger=verbalCompValueInt)
verbalComp = verbalComp.to_fhir()
# Motor
motorCompCodeSystemLn = 'http://loinc.org'
motorCompCodeLn = '9268-4'
motorCompCodeDisplayLn = 'Glasgow coma score motor'
motorCompCodingLn = Coding.Coding(system=motorCompCodeSystemLn, version=None, code=motorCompCodeLn, display=motorCompCodeDisplayLn)
motorCompCodingLn = motorCompCodingLn.to_fhir()
motorCompCodeText = 'Motor response'
motorCompCode = CodeableConcept.CodeableConcept(coding=[motorCompCodingLn], text=motorCompCodeText, extension=None)
motorCompCode = motorCompCode.to_fhir()
motorCompValueInt = valueMotor
motorComp = Component.Component(code=motorCompCode, valueQuantity=None, valueCodeableConcept=None, valueString=None, valueDateTime=None, valueInteger=motorCompValueInt)
motorComp = motorComp.to_fhir()
obs = Observation(
resourceId=resourceId,
profile=profile if not None else None,
identifier=obsIdentifier,
status=obsStatus,
category=obsCategory,
code=obsCode,
subject=subject,
effectiveDate=effectiveDate,
| |
{POS: NOUN},
"<cjt>|<np-idf>|N|M|P|@ACC>": {POS: NOUN},
"<cjt>|<np-idf>|N|M|P|@APP": {POS: NOUN},
"<cjt>|<np-idf>|N|M|P|@ICL-<SC": {POS: NOUN},
"<cjt>|<np-idf>|N|M|P|@ICL-N<": {POS: NOUN},
"<cjt>|<np-idf>|N|M|P|@N<": {POS: NOUN},
"<cjt>|<np-idf>|N|M|P|@N<PRED": {POS: NOUN},
"<cjt>|<np-idf>|N|M|P|@NPHR": {POS: NOUN},
"<cjt>|<np-idf>|N|M|P|@P<": {POS: NOUN},
"<cjt>|<np-idf>|N|M|P|@SUBJ>": {POS: NOUN},
"<cjt>|<np-idf>|N|M|S|@<ACC": {POS: NOUN},
"<cjt>|<np-idf>|N|M|S|@<ADVL": {POS: NOUN},
"<cjt>|<np-idf>|N|M|S|@<SC": {POS: NOUN},
"<cjt>|<np-idf>|N|M|S|@<SUBJ": {POS: NOUN},
"<cjt>|<np-idf>|N|M|S|@ACC>": {POS: NOUN},
"<cjt>|<np-idf>|N|M|S|@ADVL": {POS: NOUN},
"<cjt>|<np-idf>|N|M|S|@ADVL>": {POS: NOUN},
"<cjt>|<np-idf>|N|M|S|@APP": {POS: NOUN},
"<cjt>|<np-idf>|N|M|S|@N<": {POS: NOUN},
"<cjt>|<np-idf>|N|M|S|@N<PRED": {POS: NOUN},
"<cjt>|<np-idf>|N|M|S|@NPHR": {POS: NOUN},
"<cjt>|<np-idf>|N|M|S|@P<": {POS: NOUN},
"<cjt>|<np-idf>|N|M|S|@PRED>": {POS: NOUN},
"<cjt>|<np-idf>|N|M|S|@STA": {POS: NOUN},
"<cjt>|<np-idf>|N|M|S|@SUBJ>": {POS: NOUN},
"<cjt>|<poss>|DET|F|S|@>N": {POS: DET},
"<cjt>|<poss>|DET|M|S|@P<": {POS: PRON},
"<cjt>|<prd>|PRP|@<ADVL": {POS: ADP},
"<cjt>|<prd>|PRP|@<OC": {POS: ADP},
"<cjt>|<prd>|PRP|@<SC": {POS: ADP},
"<cjt>|<prop>|<np-def>|N|F|S|@SUBJ>": {POS: NOUN},
"<cjt>|<prop>|<np-def>|N|M|S|@<ACC": {POS: NOUN},
"<cjt>|<prop>|<np-def>|N|M|S|@<SUBJ": {POS: NOUN},
"<cjt>|<prop>|<np-def>|N|M|S|@NPHR": {POS: NOUN},
"<cjt>|<prop>|<np-def>|N|M|S|@P<": {POS: NOUN},
"<cjt>|<prop>|<np-idf>|N|F|S|@N<": {POS: NOUN},
"<cjt>|<prop>|<np-idf>|N|F|S|@P<": {POS: NOUN},
"<cjt>|<prop>|<np-idf>|N|F|S|@SUBJ>": {POS: NOUN},
"<cjt>|<prop>|<np-idf>|N|M|S|@N<": {POS: NOUN},
"<cjt>|<prop>|<np-idf>|N|M|S|@P<": {POS: NOUN},
"<cjt>|<prp>|<rel>|<first-cjt>|ADV|@P<": {POS: ADV},
"<cjt>|<prp>|<rel>|ADV|@N<PRED": {POS: ADV},
"<cjt>|<quant>|<first-cjt>|DET|F|P|@FS-STA": {POS: DET},
"<cjt>|<quant>|<rel>|ADV|@ADVL": {POS: ADV},
"<cjt>|<quant>|ADV|@<ADVL": {POS: ADV},
"<cjt>|<quant>|ADV|@>A": {POS: ADV},
"<cjt>|<quant>|ADV|@P<": {POS: ADV},
"<cjt>|<quant>|DET|F|P|@>N": {POS: DET},
"<cjt>|<quant>|DET|F|P|@N<PRED": {POS: DET},
"<cjt>|<quant>|DET|M|P|@>N": {POS: DET},
"<cjt>|<quant>|DET|M|P|@N<PRED": {POS: DET},
"<cjt>|<quant>|DET|M|P|@P<": {POS: PRON},
"<cjt>|<quant>|DET|M|P|@SUBJ>": {POS: PRON},
"<cjt>|<quant>|DET|M|S|@<ACC": {POS: PRON},
"<cjt>|<quant>|DET|M|S|@<SC": {POS: PRON},
"<cjt>|<quant>|DET|M|S|@>N": {POS: DET},
"<cjt>|<quant>|INDP|M|S|@<ACC": {POS: PRON},
"<cjt>|<quant>|INDP|M|S|@<SC": {POS: PRON},
"<cjt>|<quant>|INDP|M|S|@P<": {POS: PRON},
"<cjt>|<rel>|<first-cjt>|PRP|@FS-STA": {POS: ADP},
"<cjt>|<sam->|<komp>|PRP|@KOMP<": {POS: ADP},
"<cjt>|<sam->|PRP|@<ACC": {POS: ADP},
"<cjt>|<sam->|PRP|@<ADVL": {POS: ADP},
"<cjt>|<sam->|PRP|@<PIV": {POS: ADP},
"<cjt>|<sam->|PRP|@<SA": {POS: ADP},
"<cjt>|<sam->|PRP|@<SC": {POS: ADP},
"<cjt>|<sam->|PRP|@<SUBJ": {POS: ADP},
"<cjt>|<sam->|PRP|@A<": {POS: ADP},
"<cjt>|<sam->|PRP|@ADVL": {POS: ADP},
"<cjt>|<sam->|PRP|@ADVL>": {POS: ADP},
"<cjt>|<sam->|PRP|@CJT": {POS: ADP},
"<cjt>|<sam->|PRP|@KOMP<": {POS: ADP},
"<cjt>|<sam->|PRP|@N<": {POS: ADP},
"<cjt>|<sam->|PRP|@N<PRED": {POS: ADP},
"<cjt>|<sam->|PRP|@P<": {POS: ADP},
"<cjt>|<sam->|PRP|@PASS": {POS: ADP},
"<cjt>|<sam->|PRP|@PIV>": {POS: ADP},
"<cjt>|<sam->|PRP|@PRED>": {POS: ADP},
"<cjt>|<year>|<card>|<date>|NUM|M|P|@P<": {POS: NUM},
"<cjt>|<year>|<card>|<date>|NUM|M|S|@P<": {POS: NUM},
"<cjt>|<year>|<card>|NUM|M|S|@P<": {POS: NUM},
"<cjt>|<year>|<date>|NUM|M|P|@P<": {POS: NUM},
"<cjt>|<year>|<date>|NUM|M|S|@P<": {POS: NUM},
"<cjt>|ADJ|F|P|@<ADVL": {POS: ADJ},
"<cjt>|ADJ|F|P|@<SC": {POS: ADJ},
"<cjt>|ADJ|F|P|@>N": {POS: ADJ},
"<cjt>|ADJ|F|P|@APP": {POS: ADJ},
"<cjt>|ADJ|F|P|@ICL-<SC": {POS: ADJ},
"<cjt>|ADJ|F|P|@N<": {POS: ADJ},
"<cjt>|ADJ|F|P|@N<PRED": {POS: ADJ},
"<cjt>|ADJ|F|S|@<OC": {POS: ADJ},
"<cjt>|ADJ|F|S|@<SC": {POS: ADJ},
"<cjt>|ADJ|F|S|@>N": {POS: ADJ},
"<cjt>|ADJ|F|S|@ICL-N<": {POS: ADJ},
"<cjt>|ADJ|F|S|@N<": {POS: ADJ},
"<cjt>|ADJ|F|S|@PRED>": {POS: ADJ},
"<cjt>|ADJ|M/F|P|@N<": {POS: ADJ},
"<cjt>|ADJ|M/F|S|@<OC": {POS: ADJ},
"<cjt>|ADJ|M|P|@<SC": {POS: ADJ},
"<cjt>|ADJ|M|P|@>N": {POS: ADJ},
"<cjt>|ADJ|M|P|@N<": {POS: ADJ},
"<cjt>|ADJ|M|P|@N<PRED": {POS: ADJ},
"<cjt>|ADJ|M|P|@P<": {POS: ADJ},
"<cjt>|ADJ|M|S|@<ACC": {POS: ADJ},
"<cjt>|ADJ|M|S|@<ADVL": {POS: ADJ},
"<cjt>|ADJ|M|S|@<SC": {POS: ADJ},
"<cjt>|ADJ|M|S|@>N": {POS: ADJ},
"<cjt>|ADJ|M|S|@ICL-<SC": {POS: ADJ},
"<cjt>|ADJ|M|S|@ICL-N<": {POS: ADJ},
"<cjt>|ADJ|M|S|@ICL-N<PRED": {POS: ADJ},
"<cjt>|ADJ|M|S|@N<": {POS: ADJ},
"<cjt>|ADJ|M|S|@N<PRED": {POS: ADJ},
"<cjt>|ADJ|M|S|@NPHR": {POS: ADJ},
"<cjt>|ADJ|M|S|@P<": {POS: ADJ},
"<cjt>|ADJ|M|S|@PRED>": {POS: ADJ},
"<cjt>|ADV|@<ADVL": {POS: ADV},
"<cjt>|ADV|@<PIV": {POS: ADV},
"<cjt>|ADV|@>N": {POS: ADV},
"<cjt>|ADV|@ADVL": {POS: ADV},
"<cjt>|ADV|@ADVL>": {POS: ADV},
"<cjt>|ADV|@AS<": {POS: ADV},
"<cjt>|ADV|@FS-N<": {POS: ADV},
"<cjt>|ADV|@FS-STA": {POS: ADV},
"<cjt>|ADV|@ICL-<ACC": {POS: ADV},
"<cjt>|ADV|@P<": {POS: ADV},
"<cjt>|KS|@SUB": {POS: SCONJ},
"<cjt>|NUM|M|P|@P<": {POS: NUM},
"<cjt>|NUM|M|S|@P<": {POS: NUM},
"<cjt>|PERS|F|1S|NOM|@FS-STA": {POS: PRON},
"<cjt>|PERS|F|3S|NOM|@NPHR": {POS: PRON},
"<cjt>|PERS|F|3S|NOM|@SUBJ>": {POS: PRON},
"<cjt>|PERS|M|3S|NOM|@<SUBJ": {POS: PRON},
"<cjt>|PROP|F|P|@P<": {POS: PROPN},
"<cjt>|PROP|F|S|@<ACC": {POS: PROPN},
"<cjt>|PROP|F|S|@<SA": {POS: PROPN},
"<cjt>|PROP|F|S|@<SC": {POS: PROPN},
"<cjt>|PROP|F|S|@<SUBJ": {POS: PROPN},
"<cjt>|PROP|F|S|@APP": {POS: PROPN},
"<cjt>|PROP|F|S|@N<": {POS: PROPN},
"<cjt>|PROP|F|S|@N<PRED": {POS: PROPN},
"<cjt>|PROP|F|S|@NPHR": {POS: PROPN},
"<cjt>|PROP|F|S|@P<": {POS: PROPN},
"<cjt>|PROP|F|S|@SUBJ>": {POS: PROPN},
"<cjt>|PROP|M|P|@<ACC": {POS: PROPN},
"<cjt>|PROP|M|P|@<SC": {POS: PROPN},
"<cjt>|PROP|M|P|@P<": {POS: PROPN},
"<cjt>|PROP|M|P|@SUBJ>": {POS: PROPN},
"<cjt>|PROP|M|S|@<ACC": {POS: PROPN},
"<cjt>|PROP|M|S|@<ADVL": {POS: PROPN},
"<cjt>|PROP|M|S|@<SA": {POS: PROPN},
"<cjt>|PROP|M|S|@<SC": {POS: PROPN},
"<cjt>|PROP|M|S|@<SUBJ": {POS: PROPN},
"<cjt>|PROP|M|S|@APP": {POS: PROPN},
"<cjt>|PROP|M|S|@N<": {POS: PROPN},
"<cjt>|PROP|M|S|@N<PRED": {POS: PROPN},
"<cjt>|PROP|M|S|@NPHR": {POS: PROPN},
"<cjt>|PROP|M|S|@P<": {POS: PROPN},
"<cjt>|PROP|M|S|@SUBJ>": {POS: PROPN},
"<cjt>|PRP|@<ACC": {POS: ADP},
"<cjt>|PRP|@<ADVL": {POS: ADP},
"<cjt>|PRP|@<OA": {POS: ADP},
"<cjt>|PRP|@<OC": {POS: ADP},
"<cjt>|PRP|@<PIV": {POS: ADP},
"<cjt>|PRP|@<PRED": {POS: ADP},
"<cjt>|PRP|@<SA": {POS: ADP},
"<cjt>|PRP|@<SC": {POS: ADP},
"<cjt>|PRP|@A<": {POS: ADP},
"<cjt>|PRP|@A<ARG": {POS: ADP},
"<cjt>|PRP|@ACC>": {POS: ADP},
"<cjt>|PRP|@ADVL": {POS: ADP},
"<cjt>|PRP|@ADVL>": {POS: ADP},
"<cjt>|PRP|@AUX<": {POS: ADP},
"<cjt>|PRP|@CO": {POS: ADP},
"<cjt>|PRP|@FS-N<PRED": {POS: ADP},
"<cjt>|PRP|@FS-STA": {POS: ADP},
"<cjt>|PRP|@ICL-<ADVL": {POS: ADP},
"<cjt>|PRP|@ICL-<SC": {POS: ADP},
"<cjt>|PRP|@ICL-APP": {POS: ADP},
"<cjt>|PRP|@ICL-N<": {POS: ADP},
"<cjt>|PRP|@ICL-N<PRED": {POS: ADP},
"<cjt>|PRP|@ICL-P<": {POS: ADP},
"<cjt>|PRP|@ICL-PRED>": {POS: ADP},
"<cjt>|PRP|@KOMP<": {POS: ADP},
"<cjt>|PRP|@N<": {POS: ADP},
"<cjt>|PRP|@N<ARG": {POS: ADP},
"<cjt>|PRP|@N<PRED": {POS: ADP},
"<cjt>|PRP|@P<": {POS: ADP},
"<cjt>|PRP|@PASS": {POS: ADP},
"<cjt>|PRP|@PIV>": {POS: ADP},
"<cjt>|PRP|@PRED>": {POS: ADP},
"<cjt>|PRP|@SUBJ>": {POS: ADP},
"<cjt>|PRP|@UTT": {POS: ADP},
"<cjt>|V|COND|3S|@FS-PAUX": {POS: VERB},
"<cjt>|V|INF|@ICL-PMV": {POS: VERB},
"<cjt>|V|PCP|F|P|@<ACC": {POS: VERB},
"<cjt>|V|PCP|F|P|@>N": {POS: VERB},
"<cjt>|V|PCP|F|S|@<ACC": {POS: VERB},
"<cjt>|V|PCP|F|S|@>N": {POS: VERB},
"<cjt>|V|PCP|F|S|@N<": {POS: VERB},
"<cjt>|V|PCP|M|P|@<PRED": {POS: VERB},
"<cjt>|V|PCP|M|P|@<SC": {POS: VERB},
"<cjt>|V|PCP|M|P|@>N": {POS: VERB},
"<cjt>|V|PCP|M|P|@N<": {POS: VERB},
"<cjt>|V|PCP|M|P|@N<PRED": {POS: VERB},
"<cjt>|V|PCP|M|P|@P<": {POS: VERB},
"<cjt>|V|PCP|M|S|@<ADVL": {POS: VERB},
"<cjt>|V|PCP|M|S|@<OC": {POS: VERB},
"<cjt>|V|PCP|M|S|@>N": {POS: ADJ},
"<cjt>|V|PCP|M|S|@N<": {POS: VERB},
"<cjt>|V|PCP|M|S|@N<PRED": {POS: VERB},
"<cjt>|V|PCP|M|S|@P<": {POS: VERB},
"<co-a<>|<co-postad>|KC|@CO": {POS: CCONJ},
"<co-a<>|<co-postnom>|KC|@CO": {POS: CCONJ},
"<co-a<>|<kc>|ADV|@CO": {POS: ADV},
"<co-a<>|KC|@CO": {POS: CCONJ},
"<co-acc>|<co-app>|KC|@CO": {POS: CCONJ},
"<co-acc>|<co-fmc>|<co-vfin>|<co-cu>|KC|@CO": {POS: CCONJ},
"<co-acc>|<co-fmc>|<co-vfin>|<co-fcl>|KC|@CO": {POS: CCONJ},
"<co-acc>|<co-fmc>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-acc>|<co-inf>|KC|@CO": {POS: CCONJ},
"<co-acc>|<co-pred>|KC|@CO": {POS: CCONJ},
"<co-acc>|<co-prparg>|KC|@CO": {POS: CCONJ},
"<co-acc>|<co-vfin>|<co-fcl>|KC|@CO": {POS: CCONJ},
"<co-acc>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-acc>|<kc>|ADV|@CO": {POS: ADV},
"<co-acc>|ADV|@CO": {POS: ADV},
"<co-acc>|KC|@CO": {POS: CCONJ},
"<co-acl>|<co-acc>|KC|@CO": {POS: CCONJ},
"<co-acl>|<co-advl>|KC|@CO": {POS: CCONJ},
"<co-acl>|<co-oc>|KC|@CO": {POS: CCONJ},
"<co-acl>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-acl>|KC|@CO": {POS: CCONJ},
"<co-advl>|<co-acc>|KC|@CO": {POS: CCONJ},
"<co-advl>|<co-acl>|KC|@CO": {POS: CCONJ},
"<co-advl>|<co-cu>|KC|@CO": {POS: CCONJ},
"<co-advl>|<co-fmc>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-advl>|<co-postnom>|KC|@CO": {POS: CCONJ},
"<co-advl>|<co-prparg>|KC|@CO": {POS: CCONJ},
"<co-advl>|<co-subj>|<co-acl>|KC|@CO": {POS: CCONJ},
"<co-advl>|<co-subj>|KC|@CO": {POS: CCONJ},
"<co-advl>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-advl>|<kc>|ADV|@CO": {POS: ADV},
"<co-advl>|<parkc-2>|<co-sc>|ADV|@CO": {POS: ADV},
"<co-advl>|<parkc-2>|<kc>|ADV|@CO": {POS: ADV},
"<co-advl>|<prp>|<rel>|ADV|@CO": {POS: ADV},
"<co-advl>|ADV|@CO": {POS: ADV},
"<co-advl>|KC|@CO": {POS: CCONJ},
"<co-advo>|KC|@CO": {POS: CCONJ},
"<co-advs>|<co-advl>|KC|@CO": {POS: CCONJ},
"<co-advs>|<co-postnom>|KC|@CO": {POS: CCONJ},
"<co-advs>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-advs>|KC|@CO": {POS: CCONJ},
"<co-app>|<co-acc>|KC|@CO": {POS: CCONJ},
"<co-app>|<co-fcl>|KC|@CO": {POS: CCONJ},
"<co-app>|<co-postnom>|KC|@CO": {POS: CCONJ},
"<co-app>|<co-subj>|KC|@CO": {POS: CCONJ},
"<co-app>|KC|@CO": {POS: CCONJ},
"<co-as<>|KC|@CO": {POS: CCONJ},
"<co-aux<>|<co-pcp>|<co-pcv>|KC|@CO": {POS: CCONJ},
"<co-aux<>|<co-pcp>|KC|@CO": {POS: CCONJ},
"<co-cjt>|<co-acc>|KC|@CO": {POS: CCONJ},
"<co-cjt>|<co-fmc>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-cjt>|<co-piv>|KC|@CO": {POS: CCONJ},
"<co-cjt>|<co-postnom>|KC|@CO": {POS: CCONJ},
"<co-cjt>|<co-pred>|KC|@CO": {POS: CCONJ},
"<co-cjt>|<co-prparg>|KC|@CO": {POS: CCONJ},
"<co-cjt>|<co-subj>|KC|@CO": {POS: CCONJ},
"<co-cjt>|KC|@CO": {POS: CCONJ},
"<co-cu>|<co-fmc>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-cu>|<co-inf>|KC|@CO": {POS: CCONJ},
"<co-fcl>|<co-acc>|KC|@CO": {POS: CCONJ},
"<co-fcl>|<co-advl>|KC|@CO": {POS: CCONJ},
"<co-fcl>|<co-cu>|KC|@CO": {POS: CCONJ},
"<co-fcl>|<co-fmc>|<co-inf>|KC|@CO": {POS: CCONJ},
"<co-fcl>|<co-fmc>|<co-vfin>|<co-cu>|KC|@CO": {POS: CCONJ},
"<co-fcl>|<co-fmc>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-fcl>|<co-fmv>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-fcl>|<co-inf>|KC|@CO": {POS: CCONJ},
"<co-fcl>|<co-pcv>|KC|@CO": {POS: CCONJ},
"<co-fcl>|<co-postnom>|KC|@CO": {POS: CCONJ},
"<co-fcl>|<co-pred>|KC|@CO": {POS: CCONJ},
"<co-fcl>|<co-prparg>|KC|@CO|<co-prparg>|<co-fcl>": {POS: CCONJ},
"<co-fcl>|<co-sc>|KC|@CO": {POS: CCONJ},
"<co-fcl>|<co-subj>|KC|@CO": {POS: CCONJ},
"<co-fcl>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-fcl>|<co-vfin>|KC|@CO|<co-vfin>|<co-fcl>": {POS: CCONJ},
"<co-fcl>|<co-vfinco-fmc>|KC|@CO": {POS: CCONJ},
"<co-fcl>|<kc>|ADV|@CO": {POS: ADV},
"<co-fcl>|<parkc-2>|KC|@CO": {POS: CCONJ},
"<co-fcl>|<rel>|ADV|@CO": {POS: ADV},
"<co-fcl>|KC|@CO": {POS: CCONJ},
"<co-fmc>|<co-vfin>|<co-fcl>|KC|@CO": {POS: CCONJ},
"<co-ger>|KC|@CO": {POS: CCONJ},
"<co-icl>|<co-acc>|KC|@CO": {POS: CCONJ},
"<co-icl>|<co-advl>|KC|@CO": {POS: CCONJ},
"<co-icl>|<co-app>|KC|@CO": {POS: CCONJ},
"<co-icl>|<co-cu>|KC|@CO": {POS: CCONJ},
"<co-icl>|<co-fmc>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-icl>|<co-ger>|KC|@CO": {POS: CCONJ},
"<co-icl>|<co-inf>|KC|@CO": {POS: CCONJ},
"<co-icl>|<co-pcv>|KC|@CO": {POS: CCONJ},
"<co-icl>|<co-postnom>|KC|@CO": {POS: CCONJ},
"<co-icl>|<co-pred>|KC|@CO": {POS: CCONJ},
"<co-icl>|<co-prenom>|KC|@CO": {POS: CCONJ},
"<co-icl>|<co-prparg>|KC|@CO": {POS: CCONJ},
"<co-icl>|<co-sc>|KC|@CO": {POS: CCONJ},
"<co-icl>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-icl>|<kc>|ADV|@CO": {POS: ADV},
"<co-icl>|KC|@CO": {POS: CCONJ},
"<co-inf>|<co-aux<>|KC|@CO": {POS: CCONJ},
"<co-inf>|<co-icl>|KC|@CO": {POS: CCONJ},
"<co-inf>|<co-sta>|KC|@CO": {POS: CCONJ},
"<co-inf>|KC|@CO": {POS: CCONJ},
"<co-komp<>|<co-fmc>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-komp<>|KC|@CO": {POS: CCONJ},
"<co-n<>|<co-postnom>|KC|@CO": {POS: CCONJ},
"<co-n<>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-n<pred>|<co-acc>|KC|@CO": {POS: CCONJ},
"<co-n<pred>|<co-advl>|KC|@CO": {POS: CCONJ},
"<co-n<pred>|<co-fmc>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-n<pred>|<co-postnom>|KC|@CO": {POS: CCONJ},
"<co-n<pred>|<co-pred>|KC|@CO": {POS: CCONJ},
"<co-n<pred>|<co-prparg>|KC|@CO": {POS: CCONJ},
"<co-n<pred>|<co-subj>|KC|@CO": {POS: CCONJ},
"<co-n<pred>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-n<pred>|KC|@CO": {POS: CCONJ},
"<co-n>|<co-advl>|KC|@CO": {POS: CCONJ},
"<co-n>|<co-prenom>|KC|@CO": {POS: CCONJ},
"<co-n>|KC|@CO": {POS: CCONJ},
"<co-oc>|KC|@CO": {POS: CCONJ},
"<co-p<>|<co-prparg>|KC|@CO": {POS: CCONJ},
"<co-p<>|<co-prparg>|KS|@CO": {POS: SCONJ},
"<co-p<>|KC|@CO": {POS: CCONJ},
"<co-pass>|<co-prparg>|KC|@CO": {POS: CCONJ},
"<co-pass>|<kc>|ADV|@CO": {POS: ADV},
"<co-pass>|KC|@CO": {POS: CCONJ},
"<co-pcp>|<co-aux<>|KC|@CO": {POS: CCONJ},
"<co-pcp>|<co-paux>|KC|@CO": {POS: CCONJ},
"<co-pcp>|<co-pcv>|<co-aux<>|KC|@CO": {POS: CCONJ},
"<co-pcp>|<co-pcv>|<co-sta>|KC|@CO": {POS: CCONJ},
"<co-pcp>|<co-pcv>|KC|@CO": {POS: CCONJ},
"<co-pcp>|KC|@CO": {POS: CCONJ},
"<co-pcv>|<co-aux<>|KC|@CO": {POS: CCONJ},
"<co-pcv>|<co-icl>|KC|@CO": {POS: CCONJ},
"<co-pcv>|KC|@CO": {POS: CCONJ},
"<co-piv>|<co-acc>|KC|@CO": {POS: CCONJ},
"<co-piv>|<co-advl>|KC|@CO": {POS: CCONJ},
"<co-piv>|<co-cu>|KC|@CO": {POS: CCONJ},
"<co-piv>|<co-fmc>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-piv>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-piv>|KC|@CO": {POS: CCONJ},
"<co-postnom>|<co-acc>|KC|@CO": {POS: CCONJ},
"<co-postnom>|<co-advl>|KC|@CO": {POS: CCONJ},
"<co-postnom>|<co-app>|KC|@CO": {POS: CCONJ},
"<co-postnom>|<co-cu>|KC|@CO": {POS: CCONJ},
"<co-postnom>|<co-fmc>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-postnom>|<co-piv>|KC|@CO": {POS: CCONJ},
"<co-postnom>|<co-pred>|KC|@CO": {POS: CCONJ},
"<co-postnom>|<co-prparg>|KC|@CO": {POS: CCONJ},
"<co-postnom>|<co-sc>|KC|@CO": {POS: CCONJ},
"<co-postnom>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-postnom>|<kc>|ADV|@CO": {POS: ADV},
"<co-postnom>|<parkc-1>|<co-inf>|KC|@CO": {POS: CCONJ},
"<co-postnom>|<parkc-2>|<co-advl>|ADV|@CO": {POS: ADV},
"<co-postnom>|<parkc-2>|<co-inf>|KC|@CO": {POS: CCONJ},
"<co-postnom>|<prp>|<rel>|ADV|@CO": {POS: ADV},
"<co-postnom>|<rel>|ADV|@CO": {POS: ADV},
"<co-postnom>|KC|@CO": {POS: CCONJ},
"<co-pp>|KC|@CO": {POS: CCONJ},
"<co-pred>|<co-subj>|KC|@CO": {POS: CCONJ},
"<co-pred>|KC|@CO": {POS: CCONJ},
"<co-prenom>|<co-n>|KC|@CO": {POS: CCONJ},
"<co-prenom>|KC|@CO": {POS: CCONJ},
"<co-prparg>|<co-acc>|KC|@CO": {POS: CCONJ},
"<co-prparg>|<co-acl>|KC|@CO": {POS: CCONJ},
"<co-prparg>|<co-advl>|KC|@CO": {POS: CCONJ},
"<co-prparg>|<co-cu>|KC|@CO": {POS: CCONJ},
"<co-prparg>|<co-fcl>|KC|@CO": {POS: CCONJ},
"<co-prparg>|<co-fmc>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-prparg>|<co-inf>|KC|@CO": {POS: CCONJ},
"<co-prparg>|<co-postnom>|KC|@CO": {POS: CCONJ},
"<co-prparg>|<co-prenom>|KC|@CO": {POS: CCONJ},
"<co-prparg>|<co-sc>|KC|@CO": {POS: CCONJ},
"<co-prparg>|<co-subj>|KC|@CO": {POS: CCONJ},
"<co-prparg>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-prparg>|<kc>|ADV|@CO": {POS: ADV},
"<co-prparg>|ADV|@CO": {POS: ADV},
"<co-prparg>|KC|@CO": {POS: CCONJ},
"<co-que>|KC|@CO": {POS: CCONJ},
"<co-sc>|<co-cu>|KC|@CO": {POS: CCONJ},
"<co-sc>|<co-prparg>|<co-cu>|KC|@CO": {POS: CCONJ},
"<co-sc>|<kc>|ADV|@CO": {POS: ADV},
"<co-sc>|<parkc-1>|KC|@CO": {POS: CCONJ},
"<co-sc>|ADV|@CO": {POS: ADV},
"<co-sc>|KC|@CO": {POS: CCONJ},
"<co-sta>|<co-advl>|KC|@CO": {POS: CCONJ},
"<co-sta>|<co-fmc>|<co-inf>|KC|@CO": {POS: CCONJ},
"<co-sta>|<co-fmc>|<co-vfin>|<co-fcl>|KC|@CO": {POS: CCONJ},
"<co-sta>|<co-fmc>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-sta>|<co-ger>|KC|@CO": {POS: CCONJ},
"<co-sta>|<co-inf>|KC|@CO": {POS: CCONJ},
"<co-sta>|<co-pcv>|KC|@CO": {POS: CCONJ},
"<co-sta>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-sta>|<kc>|ADV|@CO": {POS: ADV},
"<co-sta>|KC|@CO": {POS: CCONJ},
"<co-subj>|<co-acc>|KC|@CO": {POS: CCONJ},
"<co-subj>|<co-cu>|KC|@CO": {POS: CCONJ},
"<co-subj>|<co-fmc>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-subj>|<co-postnom>|KC|@CO": {POS: CCONJ},
"<co-subj>|<co-prparg>|KC|@CO": {POS: CCONJ},
"<co-subj>|<co-sc>|KC|@CO": {POS: CCONJ},
"<co-subj>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-subj>|<parkc-2>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-subj>|<parkc-2>|KC|@CO": {POS: CCONJ},
"<co-subj>|<quant>|ADV|@CO": {POS: ADV},
"<co-subj>|KC|@CO": {POS: CCONJ},
"<co-utt>|<co-advl>|KC|@CO": {POS: CCONJ},
"<co-utt>|<co-fmc>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-utt>|<co-prenom>|KC|@CO": {POS: CCONJ},
"<co-utt>|KC|@CO": {POS: CCONJ},
"<co-vfin>|<co-fcl>|KC|@CO": {POS: CCONJ},
"<co-vfin>|<co-icl>|KC|@CO": {POS: CCONJ},
"<co-vfin>|<parkc-1>|KC|@CO": {POS: CCONJ},
"<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-vp>|<co-aux<>|KC|@CO": {POS: CCONJ},
"<co-vp>|<co-fmc>|<co-vfin>|KC|@CO": {POS: CCONJ},
"<co-vp>|<co-pcv>|KC|@CO": {POS: CCONJ},
| |
<reponame>ymchen7/bluefog<filename>test/torch_ops_test.py<gh_stars>1-10
# Copyright 2020 Bluefog Team. 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.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
import itertools
import unittest
import warnings
import numpy as np
import pytest
import torch
import networkx as nx
import bluefog.torch as bf
from bluefog.common import topology_util
from common import is_openmpi_built
EPSILON = 1e-5
LOOSE_EPSILON = 1e-3
TEST_ON_GPU = torch.cuda.is_available()
class OpsTests(unittest.TestCase):
"""
Tests for bluefog/torch/mpi_ops.py
"""
def __init__(self, *args, **kwargs):
super(OpsTests, self).__init__(*args, **kwargs)
warnings.simplefilter("module")
def setUp(self):
bf.init()
def convert_cpu_fp16_to_fp32(self, *values):
# PyTorch doesn't support any CPU ops on FP16 tensors.
# In case we need to do ops, we will convert tensor to FP32 here.
result = []
for value in values:
if value.dtype in [torch.float16, torch.HalfTensor] and not value.is_cuda:
result.append(value.float())
else:
result.append(value)
return result
def cast_and_place(self, tensor, dtype):
if dtype.is_cuda:
if bf.nccl_built() and bf.local_size() > torch.cuda.device_count():
raise EnvironmentError(
"Cannot run number of processes in one machine more than GPU device count"
" in NCCL environment")
return tensor.cuda(bf.local_rank() % torch.cuda.device_count()).type(dtype)
return tensor.type(dtype)
def test_broadcast(self):
"""Test that the broadcast correctly broadcasts 1D, 2D, 3D tensors."""
size = bf.size()
if size <= 1:
fname = inspect.currentframe().f_code.co_name
warnings.warn("Skip {} due to size 1".format(fname))
return
dtypes = [torch.FloatTensor, torch.IntTensor, torch.DoubleTensor, torch.LongTensor,
torch.ByteTensor, torch.CharTensor, torch.ShortTensor, torch.HalfTensor]
if TEST_ON_GPU:
dtypes += [torch.cuda.FloatTensor, torch.cuda.DoubleTensor]
dims = [1, 2, 3]
root_ranks = list(range(size))
for dtype, dim, root_rank in itertools.product(dtypes, dims, root_ranks):
torch.manual_seed(123456)
tensor = torch.FloatTensor(*([23] * dim)).random_(-100, 100)
tensor = self.cast_and_place(tensor, dtype)
name = "broadcast_tensor_{}_{}".format(dim, dtype)
if bf.rank() == root_rank:
bf.broadcast(tensor, root_rank=root_rank, name=name)
else:
zero_tensor = torch.zeros_like(tensor)
output = bf.broadcast(
zero_tensor, root_rank=root_rank, name=name
)
output, tensor = self.convert_cpu_fp16_to_fp32(output, tensor)
assert torch.allclose(output, tensor)
def test_broadcast_inplace(self):
"""Test that the broadcast correctly broadcasts 1D, 2D, 3D tensors."""
size = bf.size()
rank = bf.rank()
if size <= 1:
fname = inspect.currentframe().f_code.co_name
warnings.warn("Skip {} due to size 1".format(fname))
return
dtypes = [torch.FloatTensor, torch.IntTensor, torch.DoubleTensor, torch.LongTensor,
torch.ByteTensor, torch.CharTensor, torch.ShortTensor, torch.HalfTensor]
if TEST_ON_GPU:
dtypes += [torch.cuda.FloatTensor, torch.cuda.DoubleTensor]
dims = [1, 2, 3]
root_ranks = list(range(size))
for dtype, dim, root_rank in itertools.product(dtypes, dims, root_ranks):
torch.manual_seed(123456)
tensor = torch.FloatTensor(*([23] * dim)).fill_(1).mul_(rank)
name = "broadcast_inplace_tensor_{}_{}".format(dim, dtype)
root_tensor = torch.FloatTensor(
*([23] * dim)).fill_(1).mul_(root_rank)
tensor = self.cast_and_place(tensor, dtype)
root_tensor = self.cast_and_place(root_tensor, dtype)
broadcasted_tensor = bf.broadcast_(tensor, root_rank=root_rank, name=name)
tensor, broadcasted_tensor, root_tensor = self.convert_cpu_fp16_to_fp32(tensor,
broadcasted_tensor, root_tensor)
assert (
torch.allclose(tensor, broadcasted_tensor)
), "bf.broadcast_ does not modify source tensor"
assert (
torch.allclose(broadcasted_tensor, root_tensor)
), "bf.broadcast_ produces incorrect broadcasted tensor"
def test_allreduce_avg(self):
"""Test that the allreduce correctly average 1D, 2D, 3D tensors."""
size = bf.size()
if size <= 1:
fname = inspect.currentframe().f_code.co_name
warnings.warn("Skip {} due to size 1".format(fname))
return
dtypes = [torch.FloatTensor, torch.DoubleTensor, torch.HalfTensor]
if TEST_ON_GPU:
dtypes += [torch.cuda.FloatTensor, torch.cuda.DoubleTensor]
dims = [1, 2, 3]
for dtype, dim in itertools.product(dtypes, dims):
torch.manual_seed(123456)
tensor = torch.FloatTensor(*([23] * dim)).random_(-100, 100)
name = "allreduce_tensor_{}_{}".format(dim, dtype)
tensor = self.cast_and_place(tensor, dtype)
output = bf.allreduce(tensor, average=True, name=name)
tensor, output = self.convert_cpu_fp16_to_fp32(tensor, output)
assert (
torch.allclose(tensor, output)
), "bf.allreduce(avg) produces incorrect tensor"
def test_allreduce_sum(self):
"""Test that the allreduce correctly sums 1D, 2D, 3D tensors."""
size = bf.size()
if size <= 1:
fname = inspect.currentframe().f_code.co_name
warnings.warn("Skip {} due to size 1".format(fname))
return
dtypes = [torch.FloatTensor, torch.DoubleTensor, torch.IntTensor, torch.DoubleTensor,
torch.HalfTensor]
if TEST_ON_GPU:
dtypes += [torch.cuda.FloatTensor, torch.cuda.DoubleTensor]
dims = [1, 2, 3]
for dtype, dim in itertools.product(dtypes, dims):
torch.manual_seed(123456)
tensor = torch.FloatTensor(*([23] * dim)).random_(-100, 100)
tensor = self.cast_and_place(tensor, dtype)
name = "allreduce_tensor_{}_{}".format(dim, dtype)
output = bf.allreduce(tensor, average=False, name=name)
tensor, output = self.convert_cpu_fp16_to_fp32(tensor, output)
assert (
torch.allclose(output, tensor.mul(size))
), "bf.allreduce(sum) produces incorrect tensor"
def test_allreduce_avg_inplace(self):
"""Test that the allreduce correctly averages 1D, 2D, 3D tensors inplace."""
size = bf.size()
rank = bf.rank()
if size <= 1:
fname = inspect.currentframe().f_code.co_name
warnings.warn("Skip {} due to size 1".format(fname))
return
dtypes = [torch.FloatTensor, torch.DoubleTensor, torch.HalfTensor]
if TEST_ON_GPU:
dtypes += [torch.cuda.FloatTensor, torch.cuda.DoubleTensor]
dims = [1, 2, 3]
for dtype, dim in itertools.product(dtypes, dims):
torch.manual_seed(123456)
tensor = torch.FloatTensor(*([23] * dim)).fill_(1).mul_(rank)
name = "allreduce_tensor_{}_{}".format(dim, dtype)
tensor = self.cast_and_place(tensor, dtype)
bf.allreduce_(tensor, average=True, name=name)
tensor = self.convert_cpu_fp16_to_fp32(tensor)[0]
exp_tenosr = torch.ones_like(tensor).mul_((size-1)/2)
assert (
torch.allclose(tensor, exp_tenosr)
), "bf.allreduce_(avg) produces incorrect tensor"
def test_allreduce_fusion(self):
"""Test that the allreduce works under tensor fusion."""
size = bf.size()
if size <= 1:
fname = inspect.currentframe().f_code.co_name
warnings.warn("Skip {} due to size 1".format(fname))
return
dtypes = [torch.FloatTensor, torch.DoubleTensor, torch.HalfTensor]
if TEST_ON_GPU:
dtypes += [torch.cuda.FloatTensor, torch.cuda.DoubleTensor]
dims = [1, 2, 3]
for dtype, dim in itertools.product(dtypes, dims):
torch.manual_seed(123456)
tensor_1 = torch.FloatTensor(*([23] * dim)).random_(-100, 100)
tensor_2 = torch.FloatTensor(*([23] * dim)).random_(-100, 100)
name_1 = "allreduce_fusion_tensor_{}_{}_1".format(dim, dtype)
name_2 = "allreduce_fusion_tensor_{}_{}_2".format(dim, dtype)
tensor_1 = self.cast_and_place(tensor_1, dtype)
tensor_2 = self.cast_and_place(tensor_2, dtype)
handle_1 = bf.allreduce_nonblocking(tensor_1, average=True, name=name_1)
handle_2 = bf.allreduce_nonblocking(tensor_2, average=True, name=name_2)
output_1 = bf.synchronize(handle_1)
output_2 = bf.synchronize(handle_2)
tensor_1, output_1 = self.convert_cpu_fp16_to_fp32(tensor_1, output_1)
tensor_2, output_2 = self.convert_cpu_fp16_to_fp32(tensor_2, output_2)
assert (
torch.allclose(tensor_1, output_1)
), "bf.allreduce(fusion) produces incorrect tensor 1"
assert (
torch.allclose(tensor_2, output_2)
), "bf.allreduce(fusion) produces incorrect tensor 2"
def test_allreduce_fusion_inplace(self):
"""Test that the allreduce works under tensor fusion."""
size = bf.size()
rank = bf.rank()
if size <= 1:
fname = inspect.currentframe().f_code.co_name
warnings.warn("Skip {} due to size 1".format(fname))
return
dtypes = [torch.FloatTensor, torch.DoubleTensor, torch.HalfTensor]
if TEST_ON_GPU:
dtypes += [torch.cuda.FloatTensor, torch.cuda.DoubleTensor]
dims = [1, 2, 3]
for dtype, dim in itertools.product(dtypes, dims):
torch.manual_seed(123456)
tensor_1 = torch.FloatTensor(*([23] * dim)).fill_(1).mul_(rank)
tensor_2 = torch.FloatTensor(*([23] * dim)).fill_(1).mul_(rank+0.5)
name_1 = "allreduce_fusion_tensor_{}_{}_1".format(dim, dtype)
name_2 = "allreduce_fusion_tensor_{}_{}_2".format(dim, dtype)
tensor_1 = self.cast_and_place(tensor_1, dtype)
tensor_2 = self.cast_and_place(tensor_2, dtype)
handle_1 = bf.allreduce_nonblocking_(
tensor_1, average=True, name=name_1)
handle_2 = bf.allreduce_nonblocking_(
tensor_2, average=True, name=name_2)
bf.synchronize(handle_1)
bf.synchronize(handle_2)
tensor_1 = self.convert_cpu_fp16_to_fp32(tensor_1)[0]
tensor_2 = self.convert_cpu_fp16_to_fp32(tensor_2)[0]
exp_tenosr_1 = torch.ones_like(tensor_1).mul_((size-1)/2)
exp_tenosr_2 = torch.ones_like(tensor_2).mul_((size-1)/2 + 0.5)
assert (
torch.allclose(tensor_1, exp_tenosr_1)
), "bf.allreduce(fusion) produces incorrect tensor 1"
assert (
torch.allclose(tensor_2, exp_tenosr_2)
), "bf.allreduce(fusion) produces incorrect tensor 2"
def test_allgather(self):
"""Test that the allgather correctly gathers 1D, 2D, 3D tensors."""
size = bf.size()
rank = bf.rank()
if size <= 1:
fname = inspect.currentframe().f_code.co_name
warnings.warn("Skip {} due to size 1".format(fname))
return
dtypes = [torch.FloatTensor, torch.IntTensor, torch.DoubleTensor, torch.LongTensor,
torch.ByteTensor, torch.CharTensor, torch.ShortTensor, torch.HalfTensor]
if TEST_ON_GPU:
dtypes += [torch.cuda.FloatTensor, torch.cuda.DoubleTensor]
dims = [1, 2, 3]
for dtype, dim in itertools.product(dtypes, dims):
tensor = torch.FloatTensor(*([2] * dim)).fill_(1).mul_(rank)
tensor = self.cast_and_place(tensor, dtype)
name = "allgather_tensor_{}_{}".format(dim, dtype)
gathered = bf.allgather(tensor, name=name)
tensor, gathered = self.convert_cpu_fp16_to_fp32(tensor, gathered)
assert list(gathered.shape) == [2 * size] + [2] * (dim - 1)
for i in range(size):
rank_tensor = gathered[i * 2: (i + 1) * 2]
assert (
list(rank_tensor.shape) == [2] * dim
), "bf.allgather produces incorrect gathered shape"
assert (
rank_tensor.data.min() == i
), "bf.allgather produces incorrect gathered tensor"
assert (
rank_tensor.data.max() == i
), "bf.allgather produces incorrect gathered tensor"
def test_allgather_variable_size(self):
size = bf.size()
rank = bf.rank()
if size <= 1:
fname = inspect.currentframe().f_code.co_name
warnings.warn("Skip {} due to size 1".format(fname))
return
dtypes = [torch.FloatTensor, torch.IntTensor, torch.DoubleTensor, torch.LongTensor,
torch.ByteTensor, torch.CharTensor, torch.ShortTensor, torch.HalfTensor]
# NCCL do not support the varying case.
# if TEST_ON_GPU:
# dtypes += [torch.cuda.FloatTensor, torch.cuda.DoubleTensor]
dims = [1, 2, 3]
for dtype, dim in itertools.product(dtypes, dims):
# Support tests up to MPI Size of 35
if size > 35:
break
tensor_sizes = [17, 32, 81, 12, 15, 23, 22] * 5
tensor_sizes = tensor_sizes[:size]
tensor = torch.FloatTensor(
*([tensor_sizes[rank]] + [17] * (dim - 1))).fill_(1).mul_(rank)
tensor = self.cast_and_place(tensor, dtype)
name = "allgather_tensor_{}_{}".format(dim, dtype)
gathered = bf.allgather(tensor, name=name)
tensor, gathered = self.convert_cpu_fp16_to_fp32(tensor, gathered)
expected_size = sum(tensor_sizes)
assert list(gathered.shape) == [expected_size] + [17] * (dim - 1)
for i in range(size):
rank_size = [tensor_sizes[i]] + [17] * (dim - 1)
rank_tensor = gathered[sum(
tensor_sizes[:i]):sum(tensor_sizes[:i + 1])]
assert list(rank_tensor.shape) == rank_size, \
"bf.allgather(var) produces incorrect gathered shape"
assert rank_tensor.data.min() == i, \
"bf.allgather(var) produces incorrect gathered tensor"
assert rank_tensor.data.max() == i, \
"bf.allgather(var) produces incorrect gathered tensor"
def test_neighbor_allreduce_sum_precision(self):
"""Test that | |
animations.append(animation)
if len(animations) > 0:
glTF['animations'] = animations
def generateCameras(operator, context, exportSettings, glTF):
"""
Generates the top level cameras entry.
"""
cameras = []
filtered_cameras = exportSettings['filtered_cameras']
activeCam = None
for bl_camera in filtered_cameras:
camera = generateCamera(bl_camera, glTF)
if camera:
cameras.append(camera)
if bpy.context.window.scene.camera and bpy.context.window.scene.camera.data == bl_camera:
activeCam = camera
if not len(cameras):
camera = generateCameraFromView(1)
if camera:
cameras.append(camera)
# ensure that the active scene camera will be used for rendering (first one)
cameras = sorted(cameras, key=lambda cam: cam==activeCam, reverse=True)
if len(cameras) > 0:
glTF['cameras'] = cameras
gltf.appendExtension(glTF, 'S8S_v3d_camera_data')
def generateCamera(bl_camera, glTF):
camera = {}
# NOTE: should use a scene where the camera is located for proper calculation
vf = bl_camera.view_frame(scene=bpy.context.scene)
aspectRatio = (vf[0].x - vf[2].x) / (vf[0].y - vf[2].y)
if bl_camera.type == 'PERSP' or bl_camera.type == 'PANO':
camera['type'] = 'perspective'
perspective = {}
perspective['aspectRatio'] = aspectRatio
yfov = None
if aspectRatio >= 1:
if bl_camera.sensor_fit != 'VERTICAL':
yfov = 2.0 * math.atan(math.tan(bl_camera.angle * 0.5) / aspectRatio)
else:
yfov = bl_camera.angle
else:
if bl_camera.sensor_fit != 'HORIZONTAL':
yfov = bl_camera.angle
else:
yfov = 2.0 * math.atan(math.tan(bl_camera.angle * 0.5) / aspectRatio)
perspective['yfov'] = yfov
perspective['znear'] = bl_camera.clip_start
perspective['zfar'] = bl_camera.clip_end
camera['perspective'] = perspective
elif bl_camera.type == 'ORTHO':
camera['type'] = 'orthographic'
orthographic = {}
orthographic['xmag'] = (vf[0].x - vf[2].x) / 2
orthographic['ymag'] = (vf[0].y - vf[2].y) / 2
orthographic['znear'] = bl_camera.clip_start
orthographic['zfar'] = bl_camera.clip_end
camera['orthographic'] = orthographic
else:
return None
camera['name'] = bl_camera.name
v3dExt = {
'controls' : bl_camera.v3d.controls
}
v3dExt['enablePan'] = bl_camera.v3d.enable_pan
v3dExt['rotateSpeed'] = bl_camera.v3d.rotate_speed
v3dExt['moveSpeed'] = bl_camera.v3d.move_speed
v3dExt['viewportFitType'] = bl_camera.sensor_fit
v3dExt['viewportFitInitialAspect'] = aspectRatio
# optional orbit params
if bl_camera.v3d.controls == 'ORBIT':
target_point = (bl_camera.v3d.orbit_target if bl_camera.v3d.orbit_target_object is None
else bl_camera.v3d.orbit_target_object.matrix_world.to_translation())
v3dExt['orbitTarget'] = extractVec(convertSwizzleLocation(target_point))
v3dExt['orbitMinDistance'] = bl_camera.v3d.orbit_min_distance
v3dExt['orbitMaxDistance'] = bl_camera.v3d.orbit_max_distance
v3dExt['orbitMinZoom'] = bl_camera.v3d.orbit_min_zoom
v3dExt['orbitMaxZoom'] = bl_camera.v3d.orbit_max_zoom
v3dExt['orbitMinPolarAngle'] = bl_camera.v3d.orbit_min_polar_angle
v3dExt['orbitMaxPolarAngle'] = bl_camera.v3d.orbit_max_polar_angle
min_azim_angle = bl_camera.v3d.orbit_min_azimuth_angle
max_azim_angle = bl_camera.v3d.orbit_max_azimuth_angle
# export only when needed
if abs(2 * math.pi - (max_azim_angle - min_azim_angle)) > CAM_ANGLE_EPSILON:
v3dExt['orbitMinAzimuthAngle'] = bl_camera.v3d.orbit_min_azimuth_angle
v3dExt['orbitMaxAzimuthAngle'] = bl_camera.v3d.orbit_max_azimuth_angle
elif bl_camera.v3d.controls == 'FIRST_PERSON':
v3dExt['fpsGazeLevel'] = bl_camera.v3d.fps_gaze_level
v3dExt['fpsStoryHeight'] = bl_camera.v3d.fps_story_height
camera['extensions'] = { 'S8S_v3d_camera_data' : v3dExt }
return camera
def generateCameraFromView(aspectRatio):
printLog('INFO', 'Generating default camera')
region3D = getView3DSpaceProp('region_3d')
if region3D == None:
return None
camera = {}
camera['name'] = '__DEFAULT__'
near = getView3DSpaceProp('clip_start')
far = getView3DSpaceProp('clip_end')
if region3D.is_perspective:
camera['type'] = 'perspective'
perspective = {}
camera['perspective'] = perspective
perspective['aspectRatio'] = aspectRatio
# NOTE: decent default value
perspective['yfov'] = math.pi / 4
perspective['znear'] = near
perspective['zfar'] = far
else:
camera['type'] = 'orthographic'
orthographic = {}
camera['orthographic'] = orthographic
# NOTE: not quite right since far is the range around view point but OK in most cases
orthographic['znear'] = -far
orthographic['zfar'] = far
xmag = 1/region3D.window_matrix[0][0]
ymag = 1/region3D.window_matrix[1][1]
orthographic['xmag'] = xmag
orthographic['ymag'] = ymag
v3dExt = {}
camera['extensions'] = { 'S8S_v3d_camera_data' : v3dExt }
v3dExt['viewportFitType'] = 'VERTICAL'
v3dExt['viewportFitInitialAspect'] = aspectRatio
v3dExt['enablePan'] = True
v3dExt['rotateSpeed'] = 1
v3dExt['moveSpeed'] = 1
v3dExt['controls'] = 'ORBIT'
v3dExt['orbitTarget'] = extractVec(convertSwizzleLocation(region3D.view_location))
v3dExt['orbitMinDistance'] = 0
v3dExt['orbitMaxDistance'] = 10000
v3dExt['orbitMinPolarAngle'] = 0
v3dExt['orbitMaxPolarAngle'] = math.pi
return camera
def generateLights(operator, context, exportSettings, glTF):
"""
Generates the top level lights entry.
"""
lights = []
filtered_lights = exportSettings['filtered_lights']
for bl_light in filtered_lights:
light = {}
light['name'] = bl_light.name
light['profile'] = 'blender'
if bl_light.type == 'SUN':
light['type'] = 'directional'
elif bl_light.type == 'POINT':
light['type'] = 'point'
elif bl_light.type == 'SPOT':
light['type'] = 'spot'
elif bl_light.type == 'AREA':
light['type'] = 'area'
else:
continue
light['color'] = getLightCyclesColor(bl_light)
light['intensity'] = getLightCyclesStrength(bl_light)
useShadows = exportSettings['use_shadows'] and bl_light.use_shadow and bl_light.type != 'AREA'
if bpy.app.version < (2,81,0):
cameraNear = bl_light.shadow_buffer_clip_start
# usability improvement
if (bl_light.type == 'SPOT' or bl_light.type == 'POINT') and cameraNear < SPOT_SHADOW_MIN_NEAR:
cameraNear = SPOT_SHADOW_MIN_NEAR
cameraFar = bl_light.shadow_buffer_clip_end
orthoSize = bl_light.v3d.shadow.camera_size
eeveeCtx = context.scene.eevee
light['shadow'] = {
'enabled': useShadows,
'mapSize': int(eeveeCtx.shadow_cascade_size
if bl_light.type == 'SUN' else eeveeCtx.shadow_cube_size),
# used as a shadow size for PCF fallback
'cameraOrthoLeft': -orthoSize / 2,
'cameraOrthoRight': orthoSize / 2,
'cameraOrthoBottom': -orthoSize / 2,
'cameraOrthoTop': orthoSize / 2,
'cameraFov': bl_light.spot_size if bl_light.type == 'SPOT' else 0,
'cameraNear': cameraNear,
'cameraFar': cameraFar,
'radius': (bl_light.shadow_buffer_soft if bl_light.type == 'SUN'
else getBlurPixelRadius(context, bl_light)),
# NOTE: negate bias since the negative is more appropriate in most cases
# but keeping it positive in the UI is more user-friendly
'bias': -bl_light.shadow_buffer_bias * 0.0018,
'expBias': bl_light.shadow_buffer_exp
}
if bl_light.type == 'SUN':
light['shadow']['csm'] = {
'maxDistance': bl_light.shadow_cascade_max_distance
}
else:
eeveeCtx = context.scene.eevee
if bl_light.type == 'SUN':
# NOTE: the following values are not relevant because the engine
# calculates near/far dynamically for directional shadows
cameraNear = SUN_DEFAULT_NEAR
cameraFar = SUN_DEFAULT_FAR
else:
cameraNear = max(bl_light.shadow_buffer_clip_start,
SPOT_SHADOW_MIN_NEAR) # usability improvement
# should bl_light.cutoff_distance affect this?
cameraFar = calcLightThresholdDist(bl_light,
eeveeCtx.light_threshold)
cameraFar = min(cameraFar, MAX_SHADOW_CAM_FAR)
light['shadow'] = {
'enabled': useShadows,
'mapSize': int(eeveeCtx.shadow_cascade_size
if bl_light.type == 'SUN' else eeveeCtx.shadow_cube_size),
'cameraFov': bl_light.spot_size if bl_light.type == 'SPOT' else 0,
'cameraNear': cameraNear,
'cameraFar': cameraFar,
'radius': bl_light.v3d.shadow.radius,
# NOTE: negate bias since the negative is more appropriate in most cases
# but keeping it positive in the UI is more user-friendly
'bias': -bl_light.shadow_buffer_bias * 0.0018,
# empirical value that gives good results
'slopeScaledBias': 2.5,
'expBias': bl_light.v3d.shadow.esm_exponent,
}
if bl_light.type == 'SUN':
light['shadow']['csm'] = {
'maxDistance': bl_light.shadow_cascade_max_distance
}
if bl_light.type == 'POINT' or bl_light.type == 'SPOT' or bl_light.type == 'AREA':
if bl_light.use_custom_distance:
dist = bl_light.cutoff_distance
else:
dist = calcLightThresholdDist(bl_light, eeveeCtx.light_threshold)
light['distance'] = dist
light['decay'] = 2
if bl_light.type == 'SPOT':
light['angle'] = bl_light.spot_size / 2;
light['penumbra'] = bl_light.spot_blend;
elif bl_light.type == 'AREA':
width = bl_light.size
if bl_light.shape in ['SQUARE', 'DISK']:
height = bl_light.size
else:
height = bl_light.size_y
# do not allow small or zero size
width = max(width, 0.01)
height = max(height, 0.01)
light['intensity'] /= (width * height)
light['width'] = width
light['height'] = height
light['ltcMat1'] = pluginUtils.rawdata.ltcMat1
light['ltcMat2'] = pluginUtils.rawdata.ltcMat2
lights.append(light)
if len(lights) > 0:
gltf.appendExtension(glTF, 'S8S_v3d_data', glTF, {'lights': lights})
def generateMeshes(operator, context, exportSettings, glTF):
"""
Generates the top level meshes entry.
"""
meshes = []
filtered_meshes = exportSettings['filtered_meshes']
filtered_vertex_groups = exportSettings['filtered_vertex_groups']
joint_indices = exportSettings['joint_indices']
for bl_mesh in filtered_meshes:
srcDatablock = (bl_mesh.get(TO_MESH_SOURCE_CUSTOM_PROP).data
if bl_mesh.get(TO_MESH_SOURCE_CUSTOM_PROP) else bl_mesh)
srcName = srcDatablock.name
srcPtr = getPtr(srcDatablock)
is_line = objDataUsesLineRendering(srcDatablock)
if is_line:
internal_primitives = extractLinePrimitives(glTF, bl_mesh,
exportSettings)
else:
internal_primitives = extractPrimitives(glTF, bl_mesh,
filtered_vertex_groups[srcPtr], joint_indices.get(srcName, {}),
exportSettings)
if len(internal_primitives) == 0:
continue
# Property: mesh
mesh = {}
v3dExt = gltf.appendExtension(glTF, 'S8S_v3d_mesh_data', mesh)
if is_line:
line_settings = srcDatablock.v3d.line_rendering_settings
v3dExt['lineColor'] = extractVec(line_settings.color)
v3dExt['lineWidth'] = line_settings.width
primitives = []
for internal_primitive in internal_primitives:
primitive = {}
primitive['mode'] = PRIMITIVE_MODE_LINES if is_line else PRIMITIVE_MODE_TRIANGLES
material = gltf.getMaterialIndex(glTF, internal_primitive['material'])
# Meshes/primitives without material are allowed.
if material >= 0:
primitive['material'] = material
elif internal_primitive['material'] == DEFAULT_MAT_NAME:
primitive['material'] = getOrCreateDefaultMatIndex(glTF)
# it's possible that there were no materials in the scene, so
# the default one should 'register' the v3d material extension
gltf.appendExtension(glTF, 'S8S_v3d_material_data')
else:
printLog('WARNING', 'Material ' + internal_primitive['material'] + ' not found')
indices = internal_primitive['indices']
componentType = "UNSIGNED_BYTE"
max_index = max(indices)
# NOTE: avoiding WebGL2 PRIMITIVE_RESTART_FIXED_INDEX behavior
# see: https://www.khronos.org/registry/webgl/specs/latest/2.0/#5.18
if max_index < 255:
componentType = "UNSIGNED_BYTE"
elif max_index < 65535:
componentType = "UNSIGNED_SHORT"
elif max_index < 4294967295:
componentType = "UNSIGNED_INT"
else:
printLog('ERROR', 'Invalid max_index: ' + str(max_index))
continue
if exportSettings['force_indices']:
componentType = exportSettings['indices']
count = len(indices)
type = "SCALAR"
indices_index = gltf.generateAccessor(glTF, exportSettings['binary'], indices, componentType, count, type, "ELEMENT_ARRAY_BUFFER")
if indices_index < 0:
printLog('ERROR', 'Could not create accessor for indices')
continue
primitive['indices'] = indices_index
# Attributes
attributes = {}
internal_attributes = internal_primitive['attributes']
internal_position = internal_attributes['POSITION']
componentType = "FLOAT"
count = len(internal_position) // 3
type = "VEC3"
position = gltf.generateAccessor(glTF, exportSettings['binary'], internal_position, componentType, count, type, "ARRAY_BUFFER")
if position < 0:
printLog('ERROR', 'Could not create accessor for position')
continue
attributes['POSITION'] = position
if internal_attributes.get('NORMAL') is not None:
internal_normal = internal_attributes['NORMAL']
componentType = "FLOAT"
count = len(internal_normal) // 3
type = "VEC3"
normal = gltf.generateAccessor(glTF, exportSettings['binary'],
internal_normal, componentType, count, type, "ARRAY_BUFFER")
if normal < 0:
printLog('ERROR', 'Could not create accessor for normal')
continue
attributes['NORMAL'] = normal
if internal_attributes.get('TANGENT') is not None:
internal_tangent = internal_attributes['TANGENT']
componentType = "FLOAT"
count = len(internal_tangent) // 4
type = "VEC4"
tangent = gltf.generateAccessor(glTF, exportSettings['binary'], | |
import asyncio
from typing import Optional
from blspy import G2Element
from chia.types.coin_record import CoinRecord
from chia.types.coin_spend import CoinSpend
from chia.types.spend_bundle import SpendBundle
from chia.util.config import load_config, save_config
from operator import attrgetter
import logging
import pytest
import pytest_asyncio
from chia.consensus.block_rewards import calculate_base_farmer_reward, calculate_pool_reward
from chia.rpc.full_node_rpc_api import FullNodeRpcApi
from chia.rpc.full_node_rpc_client import FullNodeRpcClient
from chia.rpc.rpc_server import start_rpc_server
from chia.rpc.wallet_rpc_api import WalletRpcApi
from chia.rpc.wallet_rpc_client import WalletRpcClient
from chia.simulator.simulator_protocol import FarmNewBlockProtocol
from chia.types.announcement import Announcement
from chia.types.blockchain_format.program import Program
from chia.types.peer_info import PeerInfo
from chia.util.bech32m import decode_puzzle_hash, encode_puzzle_hash
from chia.consensus.coinbase import create_puzzlehash_for_pk
from chia.util.hash import std_hash
from chia.wallet.derive_keys import master_sk_to_wallet_sk
from chia.util.ints import uint16, uint32, uint64
from chia.wallet.cat_wallet.cat_constants import DEFAULT_CATS
from chia.wallet.cat_wallet.cat_wallet import CATWallet
from chia.wallet.trading.trade_status import TradeStatus
from chia.wallet.transaction_record import TransactionRecord
from chia.wallet.transaction_sorting import SortKey
from chia.wallet.util.compute_memos import compute_memos
from tests.pools.test_pool_rpc import wallet_is_synced
from tests.setup_nodes import setup_simulators_and_wallets
from tests.time_out_assert import time_out_assert
from tests.util.socket import find_available_listen_port
log = logging.getLogger(__name__)
@pytest_asyncio.fixture(scope="function")
async def two_wallet_nodes():
async for _ in setup_simulators_and_wallets(1, 2, {}):
yield _
class TestWalletRpc:
@pytest.mark.parametrize(
"trusted",
[True, False],
)
@pytest.mark.asyncio
async def test_wallet_rpc(self, two_wallet_nodes, trusted, bt, self_hostname):
test_rpc_port = find_available_listen_port()
test_rpc_port_2 = find_available_listen_port()
test_rpc_port_node = find_available_listen_port()
num_blocks = 5
full_nodes, wallets = two_wallet_nodes
full_node_api = full_nodes[0]
full_node_server = full_node_api.full_node.server
wallet_node, server_2 = wallets[0]
wallet_node_2, server_3 = wallets[1]
wallet = wallet_node.wallet_state_manager.main_wallet
wallet_2 = wallet_node_2.wallet_state_manager.main_wallet
ph = await wallet.get_new_puzzlehash()
ph_2 = await wallet_2.get_new_puzzlehash()
await server_2.start_client(PeerInfo(self_hostname, uint16(full_node_server._port)), None)
await server_3.start_client(PeerInfo(self_hostname, uint16(full_node_server._port)), None)
if trusted:
wallet_node.config["trusted_peers"] = {full_node_server.node_id.hex(): full_node_server.node_id.hex()}
wallet_node_2.config["trusted_peers"] = {full_node_server.node_id.hex(): full_node_server.node_id.hex()}
else:
wallet_node.config["trusted_peers"] = {}
wallet_node_2.config["trusted_peers"] = {}
for i in range(0, num_blocks):
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph))
initial_funds = sum(
[calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks)]
)
initial_funds_eventually = sum(
[
calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i))
for i in range(1, num_blocks + 1)
]
)
wallet_rpc_api = WalletRpcApi(wallet_node)
wallet_rpc_api_2 = WalletRpcApi(wallet_node_2)
config = bt.config
hostname = config["self_hostname"]
daemon_port = config["daemon_port"]
def stop_node_cb():
pass
full_node_rpc_api = FullNodeRpcApi(full_node_api.full_node)
rpc_cleanup_node = await start_rpc_server(
full_node_rpc_api,
hostname,
daemon_port,
test_rpc_port_node,
stop_node_cb,
bt.root_path,
config,
connect_to_daemon=False,
)
rpc_cleanup = await start_rpc_server(
wallet_rpc_api,
hostname,
daemon_port,
test_rpc_port,
stop_node_cb,
bt.root_path,
config,
connect_to_daemon=False,
)
rpc_cleanup_2 = await start_rpc_server(
wallet_rpc_api_2,
hostname,
daemon_port,
test_rpc_port_2,
stop_node_cb,
bt.root_path,
config,
connect_to_daemon=False,
)
await time_out_assert(5, wallet.get_confirmed_balance, initial_funds)
await time_out_assert(5, wallet.get_unconfirmed_balance, initial_funds)
client = await WalletRpcClient.create(hostname, test_rpc_port, bt.root_path, config)
client_2 = await WalletRpcClient.create(hostname, test_rpc_port_2, bt.root_path, config)
client_node = await FullNodeRpcClient.create(hostname, test_rpc_port_node, bt.root_path, config)
try:
await time_out_assert(5, client.get_synced)
addr = encode_puzzle_hash(await wallet_node_2.wallet_state_manager.main_wallet.get_new_puzzlehash(), "txch")
tx_amount = 15600000
try:
await client.send_transaction("1", 100000000000000001, addr)
raise Exception("Should not create high value tx")
except ValueError:
pass
# Tests sending a basic transaction
tx = await client.send_transaction("1", tx_amount, addr, memos=["this is a basic tx"])
transaction_id = tx.name
async def tx_in_mempool():
tx = await client.get_transaction("1", transaction_id)
return tx.is_in_mempool()
await time_out_assert(5, tx_in_mempool, True)
await time_out_assert(5, wallet.get_unconfirmed_balance, initial_funds - tx_amount)
assert (await client.get_wallet_balance("1"))["unconfirmed_wallet_balance"] == initial_funds - tx_amount
assert (await client.get_wallet_balance("1"))["confirmed_wallet_balance"] == initial_funds
for i in range(0, 5):
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph_2))
async def eventual_balance():
return (await client.get_wallet_balance("1"))["confirmed_wallet_balance"]
async def eventual_balance_det(c, wallet_id: str):
return (await c.get_wallet_balance(wallet_id))["confirmed_wallet_balance"]
await time_out_assert(5, wallet_is_synced, True, wallet_node, full_node_api)
# Checks that the memo can be retrieved
tx_confirmed = await client.get_transaction("1", transaction_id)
assert tx_confirmed.confirmed
assert len(tx_confirmed.get_memos()) == 1
assert [b"this is a basic tx"] in tx_confirmed.get_memos().values()
assert list(tx_confirmed.get_memos().keys())[0] in [a.name() for a in tx.spend_bundle.additions()]
await time_out_assert(5, eventual_balance, initial_funds_eventually - tx_amount)
# Tests offline signing
ph_3 = await wallet_node_2.wallet_state_manager.main_wallet.get_new_puzzlehash()
ph_4 = await wallet_node_2.wallet_state_manager.main_wallet.get_new_puzzlehash()
ph_5 = await wallet_node_2.wallet_state_manager.main_wallet.get_new_puzzlehash()
# Test basic transaction to one output and coin announcement
signed_tx_amount = 888000
tx_coin_announcements = [
Announcement(
std_hash(b"coin_id_1"),
std_hash(b"message"),
b"\xca",
),
Announcement(
std_hash(b"coin_id_2"),
bytes(Program.to("a string")),
),
]
tx_res: TransactionRecord = await client.create_signed_transaction(
[{"amount": signed_tx_amount, "puzzle_hash": ph_3}], coin_announcements=tx_coin_announcements
)
assert tx_res.fee_amount == 0
assert tx_res.amount == signed_tx_amount
assert len(tx_res.additions) == 2 # The output and the change
assert any([addition.amount == signed_tx_amount for addition in tx_res.additions])
# check error for a ASSERT_ANNOUNCE_CONSUMED_FAILED and if the error is not there throw a value error
try:
push_res = await client_node.push_tx(tx_res.spend_bundle)
except ValueError as error:
error_string = error.args[0]["error"] # noqa: # pylint: disable=E1126
if error_string.find("ASSERT_ANNOUNCE_CONSUMED_FAILED") == -1:
raise ValueError from error
# # Test basic transaction to one output and puzzle announcement
signed_tx_amount = 888000
tx_puzzle_announcements = [
Announcement(
std_hash(b"puzzle_hash_1"),
b"message",
b"\xca",
),
Announcement(
std_hash(b"puzzle_hash_2"),
bytes(Program.to("a string")),
),
]
tx_res: TransactionRecord = await client.create_signed_transaction(
[{"amount": signed_tx_amount, "puzzle_hash": ph_3}], puzzle_announcements=tx_puzzle_announcements
)
assert tx_res.fee_amount == 0
assert tx_res.amount == signed_tx_amount
assert len(tx_res.additions) == 2 # The output and the change
assert any([addition.amount == signed_tx_amount for addition in tx_res.additions])
# check error for a ASSERT_ANNOUNCE_CONSUMED_FAILED and if the error is not there throw a value error
try:
push_res = await client_node.push_tx(tx_res.spend_bundle)
except ValueError as error:
error_string = error.args[0]["error"] # noqa: # pylint: disable=E1126
if error_string.find("ASSERT_ANNOUNCE_CONSUMED_FAILED") == -1:
raise ValueError from error
# Test basic transaction to one output
signed_tx_amount = 888000
tx_res: TransactionRecord = await client.create_signed_transaction(
[{"amount": signed_tx_amount, "puzzle_hash": ph_3, "memos": ["My memo"]}]
)
assert tx_res.fee_amount == 0
assert tx_res.amount == signed_tx_amount
assert len(tx_res.additions) == 2 # The output and the change
assert any([addition.amount == signed_tx_amount for addition in tx_res.additions])
push_res = await client.push_tx(tx_res.spend_bundle)
assert push_res["success"]
assert (await client.get_wallet_balance("1"))[
"confirmed_wallet_balance"
] == initial_funds_eventually - tx_amount
for i in range(0, 5):
await client.farm_block(encode_puzzle_hash(ph_2, "txch"))
await asyncio.sleep(0.5)
await time_out_assert(5, eventual_balance, initial_funds_eventually - tx_amount - signed_tx_amount)
# Test transaction to two outputs, from a specified coin, with a fee
coin_to_spend = None
for addition in tx_res.additions:
if addition.amount != signed_tx_amount:
coin_to_spend = addition
assert coin_to_spend is not None
tx_res = await client.create_signed_transaction(
[{"amount": 444, "puzzle_hash": ph_4, "memos": ["hhh"]}, {"amount": 999, "puzzle_hash": ph_5}],
coins=[coin_to_spend],
fee=100,
)
assert tx_res.fee_amount == 100
assert tx_res.amount == 444 + 999
assert len(tx_res.additions) == 3 # The outputs and the change
assert any([addition.amount == 444 for addition in tx_res.additions])
assert any([addition.amount == 999 for addition in tx_res.additions])
assert sum([rem.amount for rem in tx_res.removals]) - sum([ad.amount for ad in tx_res.additions]) == 100
push_res = await client_node.push_tx(tx_res.spend_bundle)
assert push_res["success"]
for i in range(0, 5):
await client.farm_block(encode_puzzle_hash(ph_2, "txch"))
await asyncio.sleep(0.5)
found: bool = False
for addition in tx_res.spend_bundle.additions():
if addition.amount == 444:
cr: Optional[CoinRecord] = await client_node.get_coin_record_by_name(addition.name())
assert cr is not None
spend: CoinSpend = await client_node.get_puzzle_and_solution(
addition.parent_coin_info, cr.confirmed_block_index
)
sb: SpendBundle = SpendBundle([spend], G2Element())
assert compute_memos(sb) == {addition.name(): [b"hhh"]}
found = True
assert found
new_balance = initial_funds_eventually - tx_amount - signed_tx_amount - 444 - 999 - 100
await time_out_assert(5, eventual_balance, new_balance)
send_tx_res: TransactionRecord = await client.send_transaction_multi(
"1",
[
{"amount": 555, "puzzle_hash": ph_4, "memos": ["FiMemo"]},
{"amount": 666, "puzzle_hash": ph_5, "memos": ["SeMemo"]},
],
fee=200,
)
assert send_tx_res is not None
assert send_tx_res.fee_amount == 200
assert send_tx_res.amount == 555 + 666
assert len(send_tx_res.additions) == 3 # The outputs and the change
assert any([addition.amount == 555 for addition in send_tx_res.additions])
assert any([addition.amount == 666 for addition in send_tx_res.additions])
assert (
sum([rem.amount for rem in send_tx_res.removals]) - sum([ad.amount for ad in send_tx_res.additions])
== 200
)
await asyncio.sleep(3)
for i in range(0, 5):
await client.farm_block(encode_puzzle_hash(ph_2, "txch"))
await asyncio.sleep(0.5)
new_balance = new_balance - 555 - 666 - 200
await time_out_assert(5, eventual_balance, new_balance)
address = await client.get_next_address("1", True)
assert len(address) > 10
transactions = await client.get_transactions("1")
assert len(transactions) > 1
all_transactions = await client.get_transactions("1")
# Test transaction pagination
some_transactions = await client.get_transactions("1", 0, 5)
some_transactions_2 = await client.get_transactions("1", 5, 10)
assert some_transactions == all_transactions[0:5]
assert some_transactions_2 == all_transactions[5:10]
# Testing sorts
# Test the default sort (CONFIRMED_AT_HEIGHT)
assert all_transactions == sorted(all_transactions, key=attrgetter("confirmed_at_height"))
all_transactions = await client.get_transactions("1", reverse=True)
assert all_transactions == sorted(all_transactions, key=attrgetter("confirmed_at_height"), reverse=True)
# Test RELEVANCE
await client.send_transaction("1", 1, encode_puzzle_hash(ph_2, "txch")) # Create a pending tx
all_transactions = await client.get_transactions("1", sort_key=SortKey.RELEVANCE)
sorted_transactions = sorted(all_transactions, key=attrgetter("created_at_time"), reverse=True)
sorted_transactions = sorted(sorted_transactions, key=attrgetter("confirmed_at_height"), reverse=True)
sorted_transactions = sorted(sorted_transactions, key=attrgetter("confirmed"))
assert all_transactions == sorted_transactions
all_transactions = await client.get_transactions("1", sort_key=SortKey.RELEVANCE, reverse=True)
sorted_transactions = sorted(all_transactions, key=attrgetter("created_at_time"))
sorted_transactions = sorted(sorted_transactions, key=attrgetter("confirmed_at_height"))
sorted_transactions = sorted(sorted_transactions, key=attrgetter("confirmed"), reverse=True)
assert all_transactions == sorted_transactions
# Checks that the memo can be retrieved
tx_confirmed = await client.get_transaction("1", send_tx_res.name)
assert tx_confirmed.confirmed
if isinstance(tx_confirmed, SpendBundle):
memos = compute_memos(tx_confirmed)
else:
memos = tx_confirmed.get_memos()
assert len(memos) == 2
print(memos)
assert [b"FiMemo"] in memos.values()
assert [b"SeMemo"] in memos.values()
assert list(memos.keys())[0] in [a.name() for a in send_tx_res.spend_bundle.additions()]
assert list(memos.keys())[1] in [a.name() for a in send_tx_res.spend_bundle.additions()]
# Test get_transactions to address
ph_by_addr = await wallet.get_new_puzzlehash()
await client.send_transaction("1", 1, encode_puzzle_hash(ph_by_addr, "txch"))
await client.farm_block(encode_puzzle_hash(ph_by_addr, "txch"))
await time_out_assert(10, wallet_is_synced, True, wallet_node, full_node_api)
tx_for_address = await wallet_rpc_api.get_transactions(
{"wallet_id": "1", "to_address": encode_puzzle_hash(ph_by_addr, "txch")}
| |
import torch
import torch.nn.functional as F
import numpy as np
import math
def gradient_loss(s, penalty='l1'):
dy = torch.abs(s[:, :, 1:, :,:] - s[:, :, :-1, :,:])
dx = torch.abs(s[:, :, :, 1:,:] - s[:, :, :, :-1,:])
dz = torch.abs(s[:, :, :, :, 1:] - s[:, :, :, :, :-1])
if (penalty == 'l2'):
dy = dy * dy
dx = dx * dx
dz = dz * dz
d = torch.mean(dx) + torch.mean(dy)+ torch.mean(dz)
return d / 3.0
# def gradient_loss(s, penalty='l2'):
# dy = torch.abs(s[:, :, 1:, :] - s[:, :, :-1, :])
# dx = torch.abs(s[:, :, :, 1:] - s[:, :, :, :-1])
#
# if (penalty == 'l2'):
# dy = dy * dy
# dx = dx * dx
#
# d = torch.mean(dx) + torch.mean(dy)
# return d / 2.0
def mse_loss(x, y):
return torch.mean((x - y) ** 2)
def dice_score(pred, target):
"""This definition generalize to real valued pred and target vector.
This should be differentiable.
pred: tensor with first dimension as batch
target: tensor with first dimension as batch
"""
top = 2 * torch.sum(pred * target, [1, 2, 3])
union = torch.sum(pred + target, [1, 2, 3])
eps = torch.ones_like(union) * 1e-5
bottom = torch.max(union, eps)
dice = torch.mean(top / bottom)
#print("Dice score", dice)
return dice
def ncc_loss(I, J, win=None):
"""
calculate the normalize cross correlation between I and J
assumes I, J are sized [batch_size, *vol_shape, nb_feats]
"""
ndims = len(list(I.size())) - 2
assert ndims in [1, 2, 3], "volumes should be 1 to 3 dimensions. found: %d" % ndims
if win is None:
win = [9] * ndims
conv_fn = getattr(F, 'conv%dd' % ndims)
I2 = I * I
J2 = J * J
IJ = I * J
sum_filt = torch.ones([1, 1, *win]).to("cuda")
pad_no = math.floor(win[0] / 2)
if ndims == 1:
stride = (1)
padding = (pad_no)
elif ndims == 2:
stride = (1, 1)
padding = (pad_no, pad_no)
else:
stride = (1, 1, 1)
padding = (pad_no, pad_no, pad_no)
if ndims==2:
I_var, J_var, cross = compute_local_sums_2d(I, J, sum_filt, stride, padding, win)
else:
I_var, J_var, cross = compute_local_sums_3d(I, J, sum_filt, stride, padding, win)
cc = cross * cross / (I_var * J_var + 1e-5)
# cc = (cross + 1e-5) ** 2 / ((I_var + 1e-5) * (J_var + 1e-5)) # improved
return -1 * torch.mean(cc)
def compute_local_sums_3d(I, J, filt, stride, padding, win):
I2 = I * I
J2 = J * J
IJ = I * J
I_sum = F.conv3d(I, filt, stride=stride, padding=padding)
J_sum = F.conv3d(J, filt, stride=stride, padding=padding)
I2_sum = F.conv3d(I2, filt, stride=stride, padding=padding)
J2_sum = F.conv3d(J2, filt, stride=stride, padding=padding)
IJ_sum = F.conv3d(IJ, filt, stride=stride, padding=padding)
win_size = np.prod(win)
u_I = I_sum / win_size
u_J = J_sum / win_size
cross = IJ_sum - u_J * I_sum - u_I * J_sum + u_I * u_J * win_size
I_var = I2_sum - 2 * u_I * I_sum + u_I * u_I * win_size
J_var = J2_sum - 2 * u_J * J_sum + u_J * u_J * win_size
return I_var, J_var, cross
def compute_local_sums_2d(I, J, filt, stride, padding, win):
I2 = I * I
J2 = J * J
IJ = I * J
I_sum = F.conv2d(I, filt, stride=stride, padding=padding)
J_sum = F.conv2d(J, filt, stride=stride, padding=padding)
I2_sum = F.conv2d(I2, filt, stride=stride, padding=padding)
J2_sum = F.conv2d(J2, filt, stride=stride, padding=padding)
IJ_sum = F.conv2d(IJ, filt, stride=stride, padding=padding)
win_size = np.prod(win)
u_I = I_sum / win_size
u_J = J_sum / win_size
cross = IJ_sum - u_J * I_sum - u_I * J_sum + u_I * u_J * win_size
I_var = I2_sum - 2 * u_I * I_sum + u_I * u_I * win_size
J_var = J2_sum - 2 * u_J * J_sum + u_J * u_J * win_size
return I_var, J_var, cross
def KL_Divergence(warped, fixed):
# print(f'warp:{warped.shape}')
# print(f'fixed:{fixed.shape}')
warped=warped.contiguous().view(1,-1)
fixed = fixed.contiguous().view(1, -1)
warped_softmax=warped.softmax(1)
fixed_softmax=fixed.softmax(1)
KL_Div = F.kl_div(fixed_softmax.log(), warped_softmax,reduction='sum')
return KL_Div
def dice_score(pred, target):
"""This definition generalize to real valued pred and target vector.
This should be differentiable.
pred: tensor with first dimension as batch
target: tensor with first dimension as batch
"""
top = 2 * torch.sum(pred * target, [1, 2, 3])
union = torch.sum(pred + target, [1, 2, 3])
eps = torch.ones_like(union) * 1e-5
bottom = torch.max(union, eps)
dice = torch.mean(top / bottom)
#print("Dice score", dice)
return dice
def compute_label_dice(src, pred):
# 需要计算的标签类别,不包括背景和图像中不存在的区域
cls_lst = [ 2,4,8,10,11,12,13,16,17,18,24,26,28,
47,49,50,51,52,58,60, ]
'''cls_lst =[21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 61, 62,
63, 64, 65, 66, 67, 68, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 101, 102, 121, 122, 161, 162,
163, 164, 165, 166, 181, 182]'''
dice_lst = []
for cls in cls_lst:
dice = DSC(src == cls, pred == cls)
dice_lst.append(dice)
aa = np.array(dice_lst)
return np.mean(dice_lst),aa
def dice(array1, array2, labels):
"""
Computes the dice overlap between two arrays for a given set of integer labels.
"""
dicem = np.zeros(len(labels))
for idx, label in enumerate(labels):
top = 2 * np.sum(np.logical_and(array1 == label, array2 == label))
bottom = np.sum(array1 == label) + np.sum(array2 == label)
bottom = np.maximum(bottom, np.finfo(float).eps) # add epsilon
dicem[idx] = top / bottom
return np.mean(dicem)
def DSC(pred, target):
smooth = 1e-5
m1 = pred.flatten()
m2 = target.flatten()
intersection = (m1 * m2).sum()
return (2. * intersection + smooth) / (m1.sum() + m2.sum() + smooth)
# def jacobian_determinant(disp):
# """
# jacobian determinant of a displacement field.
# NB: to compute the spatial gradients, we use np.gradient.
# Parameters:
# disp: 2D or 3D displacement field of size [*vol_shape, nb_dims],
# where vol_shape is of len nb_dims
# Returns:
# jacobian determinant (scalar)
# """
# def ndgrid(*args, **kwargs):
# """
# Disclaimer: This code is taken directly from the scitools package [1]
# Since at the time of writing scitools predominantly requires python 2.7 while we work with 3.5+
# To avoid issues, we copy the quick code here.
# Same as calling ``meshgrid`` with *indexing* = ``'ij'`` (see
# ``meshgrid`` for documentation).
# """
# kwargs['indexing'] = 'ij'
# return np.meshgrid(*args, **kwargs)
#
# def volsize2ndgrid(volsize):
# """
# return the dense nd-grid for the volume with size volsize
# essentially return the ndgrid fpr
# """
# ranges = [np.arange(e) for e in volsize]
# return ndgrid(*ranges)
#
# # check inputs
# volshape = disp.shape[:-1]
# nb_dims = len(volshape)
# assert len(volshape) in (2, 3), 'flow has to be 2D or 3D'
#
# # compute grid
#
# # grid_lst = nd.volsize2ndgrid(volshape)
#
# ranges = [np.arange(e) for e in volshape]
# grid_lst=np.meshgrid(ranges)
#
# grid = np.stack(grid_lst[0], len(volshape))
#
# # compute gradients
# J = np.gradient(disp + grid)
#
# # 3D glow
# if nb_dims == 3:
# dx = J[0]
# dy = J[1]
# dz = J[2]
#
# # compute jacobian components
# Jdet0 = dx[..., 0] * (dy[..., 1] * dz[..., 2] - dy[..., 2] * dz[..., 1])
# Jdet1 = dx[..., 1] * (dy[..., 0] * dz[..., 2] - dy[..., 2] * dz[..., 0])
# Jdet2 = dx[..., 2] * (dy[..., 0] * dz[..., 1] - dy[..., 1] * dz[..., 0])
#
# return Jdet0 - Jdet1 + Jdet2
#
# else: # must be 2
#
# dfdx = J[0]
# dfdy = J[1]
#
# return dfdx[..., 0] * dfdy[..., 1] - dfdy[..., 0] * dfdx[..., 1]
def Get_Jac(displacement):
'''
the expected input: displacement of shape(batch, H, W, D, channel),
obtained in TensorFlow.
'''
D_y = (displacement[:,1:,:-1,:-1,:] - displacement[:,:-1,:-1,:-1,:])
D_x = (displacement[:,:-1,1:,:-1,:] - displacement[:,:-1,:-1,:-1,:])
D_z = (displacement[:,:-1,:-1,1:,:] - displacement[:,:-1,:-1,:-1,:])
D1 = (D_x[...,0]+1)*((D_y[...,1]+1)*(D_z[...,2]+1) - D_y[...,2]*D_z[...,1])
D2 = (D_x[...,1])*(D_y[...,0]*(D_z[...,2]+1) - D_y[...,2]*D_z[...,0])
D3 = (D_x[...,2])*(D_y[...,0]*D_z[...,1] - (D_y[...,1]+1)*D_z[...,0])
D = D1 - D2 + D3
return D
import pystrum.pynd.ndutils as nd
def jacobian_determinant(flow):
"""
jacobian determinant of a displacement field.
NB: to compute the spatial gradients, we use np.gradient.
Parameters:
disp: 2D or 3D displacement field of size [*vol_shape, nb_dims],
where vol_shape is of len nb_dims
Returns:
jacobian determinant (scalar)
"""
# check inputs
JAC = []
for i in range(0,10):
disp = flow[i]
volshape = disp.shape[:-1]
nb_dims = len(volshape)
assert len(volshape) in (2, 3), 'flow has to be 2D or 3D'
# compute grid
grid_lst = nd.volsize2ndgrid(volshape)
grid = np.stack(grid_lst, len(volshape))
# compute gradients
J = np.gradient(disp + | |
def eig_check(self):
"""
Function to perform an eigenvalue based consistency check on the covariance matrix and adjust values accordingly
Algorithm based on 3d NDT Scan Matching and Biber's NDT paper
Using an SVD approach here. For covariance matrices, SVD and eigen decomposition should be the same. SVD
implementations are often more stable
:return: None
"""
scale_param = 0.0001
for key, val in self.stats.items():
u, s_diag, v = np.linalg.svd(val['sigma']) # np.svd naturally returns a diagonal
s_diag[s_diag < scale_param*s_diag.max()] = scale_param*s_diag.max()
val['sigma'] = np.matmul(np.matmul(u, np.diag(s_diag)), v)
return None
def update_cloud(self, pc_points):
"""
Function to add points to current NDT approximation. This function adds both, new centers and points to
existing grid points.
:param pc_points: The points that are to be added to the NDT approximation. Might be Nx3 or Nx4.
Function agnostic to that
:return: None
"""
# This function should be used to update an empty NDT cloud as well using the given points
# Find grid centers corresponding to given points
update_points = pc_points[:, :3]
# Dictionary approach here as well
points_in_voxels = self.bin_in_voxels(update_points)
# Update the NDT approximation with these binned points
self.update_stats(points_in_voxels)
self.eig_check()
return None
def find_integrity(self, points):
"""
Given a set of points and the underlying NDT Cloud, find the integrity of each voxel and the combined navigation
solution
:param points: Transformed points for which the integrity is required
:return: Im: The integrity of the navigation solution obtained using the transformed points given
:return: iscore: Voxel integrity score corresponding to the voxel center
"""
test_xyz = points[:, :3]
binned_points = self.bin_in_voxels(test_xyz)
N = len(self.stats)
iscore_array = np.zeros(N)
loop_index = 0
mu_points = np.zeros([N, 3])
for key, val in self.stats.items():
if key in binned_points:
mu_points[loop_index, :] = val['mu']
iscore_array[loop_index] = integrity.voxel_integrity(val, binned_points[key])
self.stats[key]['integrity'] = iscore_array[loop_index]
if np.isnan(iscore_array[loop_index]):
print('NaN detected!')
loop_index += 1
else:
self.stats[key]['integrity'] = 0
iscore_array[iscore_array == 0] = 1e-9
Im, iscore_sum = integrity.solution_score(mu_points[:loop_index, :], iscore_array[:loop_index], points)
# The loop index is added to ensure that only points that have a corresponding voxel are used for IDOP
return Im, iscore_sum
def optimization_integrity(self, points):
"""
Given a set of points and the underlying NDT Cloud, find the integrity of each voxel and the combined navigation
solution
:param points: Transformed points for which the integrity is required
:return: Im: The integrity of the navigation solution obtained using the transformed points given
:return: iscore: Voxel integrity score corresponding to the voxel center
"""
test_xyz = points[:, :3]
binned_points = self.bin_in_voxels(test_xyz)
N = len(self.stats)
iscore_dict = {}
rbar_dict = {}
k_dict = {}
loop_index = 0
mu_points = np.zeros([N, 3])
for key, val in self.stats.items():
if key in binned_points:
mu_points[loop_index, :] = val['mu']
iscore_dict[key], rbar_dict[key], k_dict[key] = integrity.voxel_int_opt(val, binned_points[key])
if np.isnan(iscore_dict[key]):
print('NaN detected!')
loop_index += 1
iscore_dict[iscore_dict == 0] = 1e-9
# The loop index is added to ensure that only points that have a corresponding voxel are used for IDOP
return iscore_dict, rbar_dict, k_dict
def filter_voxels_integrity(self, integrity_limit=0.7):
"""
Function to trim an ndt_cloud based on the integrity values of its voxels
:param self: The NDT approximation to be trimmed
:param integrity_limit: The minimum valid voxel integrity value
:return: ndt_cloud: The same NDT approximation, but now with all voxels below an integrity limit removed
"""
delete_index = []
for key in self.stats.keys():
if self.stats[key]['integrity'] < integrity_limit:
delete_index.append(key)
for del_key in delete_index:
del self.stats[del_key]
return None
def pairing_cent2int(self, point_centers):
"""
:param point_centers: Nx3 numpy array containing coordinates under consideration
:return:
"""
"""
1. Using voxel size, convert each center to a coordinate with only integer values
2. Implement a standard pairing function to bind said coordinate to an index
"""
assert(point_centers.shape[1] == 3) # Checking that the matrix is all row vectors
# Assign unique positive value to each integer
pt_centers_temp = np.copy(point_centers)
pt_centers_temp = (pt_centers_temp + self.first_center[0, :])/np.array([self.horiz_grid_size, self.horiz_grid_size, self.vert_grid_size])
pt_centers_temp[pt_centers_temp > 0] = 2*pt_centers_temp[pt_centers_temp > 0]
pt_centers_temp[pt_centers_temp < 0] = -2*pt_centers_temp[pt_centers_temp < 0] - 1
x = np.atleast_2d(pt_centers_temp[:, 0])
y = np.atleast_2d(pt_centers_temp[:, 1])
z = np.atleast_2d(pt_centers_temp[:, 2])
assert(np.min(x) > -1)
assert(np.min(y) > -1)
assert(np.min(z) > -1)
pair_1 = np.atleast_2d(0.5*(x + y)*(x + y + 1) + y)
int_pairing = np.atleast_2d(0.5*(pair_1 + z)*(pair_1 + z + 1) + z)
int_pairing = np.reshape(int_pairing, [-1, 1])
assert(int_pairing.shape == (point_centers.shape[0], 1))
return int_pairing
def pair_check(self):
"""
Checking that the number of voxels and the number of unique index assignments is the same
:return: None
"""
voxels = []
number = 0
for key in self.stats:
voxels.append(self.stats[key]['idx'][0][0])
number += 1
voxels = np.array(voxels)
unique_voxels, unique_counts, case_counts = np.unique(voxels, return_index=True, return_counts=True)
unique_no = np.size(unique_voxels)
print('The number of voxels is ', number)
print('The number of maximum voxels is ', self.max_no_voxels)
print('The number of unique voxels is ', unique_no)
assert(np.size(unique_voxels) == self.max_no_voxels)
return None
def prune_pc(self, pc):
"""
Remove all points that don't overlap with NDT Cloud
:param pc: Point cloud
:return pruned_pc: Unique points that overlap with NDT Cloud
"""
pruned_pc = np.zeros([0, 3])
center_dict = self.bin_in_voxels(pc)
keys = np.zeros([0, 3])
binned_keys = np.zeros([0, 3])
original_keys = np.zeros([0, 3])
for key in self.stats:
original_keys = np.vstack((original_keys, key))
for key in center_dict:
binned_keys = np.vstack((binned_keys, key))
if key in self.stats:
keys = np.vstack((keys, key))
pruned_pc = np.vstack((pruned_pc, center_dict[key]))
return np.unique(pruned_pc, axis=0)
class NDTCloudNoOverLap(NDTCloudBase):
"""
Class inherited from NDTCloudBase parent for NDT approximation with no overlapping voxels
"""
def __init__(self, xlim, ylim, zlim, input_horiz_grid_size, input_vert_grid_size, cloud_type):
super(NDTCloudNoOverLap, self).__init__(xlim, ylim, zlim, input_horiz_grid_size, input_vert_grid_size
, cloud_type)
self.first_center = np.zeros([1, 3])
first_center_x = np.mod(2 * xlim / self.horiz_grid_size + 1, 2) * self.horiz_grid_size / 2.0
first_center_y = np.mod(2 * ylim / self.horiz_grid_size + 1, 2) * self.horiz_grid_size / 2.0
first_center_z = np.mod(2 * zlim / self.vert_grid_size + 1, 2) * self.vert_grid_size / 2.0
self.first_center[0, :] = np.array([first_center_x, first_center_y, first_center_z])
class NDTCloudOverLap(NDTCloudBase):
"""
Class inherited from NDTCloudBase parent for NDT approximation with overlapping voxels. Overlap ensure smoother likelihood computation
"""
def __init__(self, xlim, ylim, zlim, input_horiz_grid_size, input_vert_grid_size, cloud_type):
super(NDTCloudOverLap, self).__init__(xlim, ylim, zlim, input_horiz_grid_size, input_vert_grid_size
, cloud_type)
self.first_center = np.empty([8, 3])
for i in range(8):
offset = np.array([np.mod(i, 2), np.mod(np.int(i / 2), 2), np.int(i / 4)])
first_center_x = np.mod(2 * xlim / self.horiz_grid_size + offset[0] + 1, 2) * self.horiz_grid_size / 2.0
first_center_y = np.mod(2 * ylim / self.horiz_grid_size + offset[1] + 1, 2) * self.horiz_grid_size / 2.0
first_center_z = np.mod(2 * zlim / self.vert_grid_size + offset[2] + 1, 2) * self.vert_grid_size / 2.0
self.first_center[i, :] = np.array([first_center_x, first_center_y, first_center_z])
class NDTCloudInterpolated(NDTCloudBase):
"""
Class inherited from NDTCloudBase parent for NDT approximation with non-overlapping voxels with interpolated likelihood calculation.
Method of objective, Jacobian and Hessian computations is different from base class.
"""
def __init__(self, xlim, ylim, zlim, input_horiz_grid_size, input_vert_grid_size, cloud_type):
super(NDTCloudInterpolated, self).__init__(xlim, ylim, zlim, input_horiz_grid_size, input_vert_grid_size
, cloud_type)
self.first_center = np.zeros([1, 3])
first_center_x = np.mod(2 * xlim / self.horiz_grid_size + 1, 2) * self.horiz_grid_size / 2.0
first_center_y = np.mod(2 * ylim / self.horiz_grid_size + 1, 2) * self.horiz_grid_size / 2.0
first_center_z = np.mod(2 * zlim / self.vert_grid_size + 1, 2) * self.vert_grid_size / 2.0
self.first_center[0, :] = np.array([first_center_x, first_center_y, first_center_z])
def find_octant(self, transformed_xyz):
"""
Find which octant of divided voxel point lies in. Used to find centers of neighbouring voxels
:param transformed_xyz: PC after transformation
:return octant: Octants for each point in the PC
"""
_, point_centers = self.find_voxel_center(transformed_xyz)
diff_sign = np.sign(transformed_xyz - point_centers)
diff_sign[np.isnan(diff_sign)] = -1.0
octant_index = np.zeros([2, 2, 2])
octant_index[1, 1, 1] = 1
octant_index[0, 1, 1] = 2
octant_index[0, 0, 1] = 3
octant_index[1, 0, 1] = 4
octant_index[1, 1, 0] = 5
octant_index[0, 1, 0] = 6
octant_index[0, 0, 0] = 7
octant_index[1, 0, 0] = 8
diff_sign[diff_sign == -1] = 0
diff_sign = diff_sign.astype(np.int, copy=False)
octant = octant_index[diff_sign[:, 0], diff_sign[:, 1], diff_sign[:, 2]]
return octant
def find_neighbours(self, transformed_xyz, no_neighbours=8):
"""
Return centers of voxels neighbouring points in given point cloud
:param transformed_xyz: PC after transformation
:param no_neighbours: Number of neighbours to find, 8 by default
:return nearby: neighbours of each point in | |
# :copyright: (c) 2021 by <NAME>.
# :license: MIT, see LICENSE for more details.
"""
yaspin.yaspin
~~~~~~~~~~~~~
A lightweight terminal spinner.
"""
import contextlib
import datetime
import functools
import itertools
import signal
import sys
import threading
import time
from typing import List, Set, Union
from termcolor import colored
from .base_spinner import Spinner, default_spinner
from .constants import COLOR_ATTRS, COLOR_MAP, SPINNER_ATTRS
from .helpers import to_unicode
class Yaspin: # pylint: disable=useless-object-inheritance,too-many-instance-attributes
"""Implements a context manager that spawns a thread
to write spinner frames into a tty (stdout) during
context execution.
"""
# When Python finds its output attached to a terminal,
# it sets the sys.stdout.encoding attribute to the terminal's encoding.
# The print statement's handler will automatically encode unicode
# arguments into bytes.
def __init__( # pylint: disable=too-many-arguments
self,
spinner=None,
text="",
color=None,
on_color=None,
attrs=None,
reversal=False,
side="left",
sigmap=None,
timer=False,
):
# Spinner
self._spinner = self._set_spinner(spinner)
self._frames = self._set_frames(self._spinner, reversal)
self._interval = self._set_interval(self._spinner)
self._cycle = self._set_cycle(self._frames)
# Color Specification
self._color = self._set_color(color) if color else color
self._on_color = self._set_on_color(on_color) if on_color else on_color
self._attrs = self._set_attrs(attrs) if attrs else set()
self._color_func = self._compose_color_func()
# Other
self._text = text
self._side = self._set_side(side)
self._reversal = reversal
self._timer = timer
self._start_time = None
self._stop_time = None
# Helper flags
self._stop_spin = None
self._hide_spin = None
self._spin_thread = None
self._last_frame = None
self._stdout_lock = threading.Lock()
self._hidden_level = 0
# Signals
# In Python 2 signal.SIG* are of type int.
# In Python 3 signal.SIG* are enums.
#
# Signal = Union[enum.Enum, int]
# SigHandler = Union[enum.Enum, Callable]
self._sigmap = sigmap if sigmap else {} # Dict[Signal, SigHandler]
# Maps signals to their default handlers in order to reset
# custom handlers set by ``sigmap`` at the cleanup phase.
self._dfl_sigmap = {} # Dict[Signal, SigHandler]
#
# Dunders
#
def __repr__(self):
return "<Yaspin frames={0!s}>".format(self._frames)
def __enter__(self):
self.start()
return self
def __exit__(self, exc_type, exc_val, traceback):
# Avoid stop() execution for the 2nd time
if self._spin_thread.is_alive():
self.stop()
return False # nothing is handled
def __call__(self, fn):
@functools.wraps(fn)
def inner(*args, **kwargs):
with self:
return fn(*args, **kwargs)
return inner
def __getattr__(self, name):
# CLI spinners
if name in SPINNER_ATTRS:
from .spinners import Spinners # pylint: disable=import-outside-toplevel
sp = getattr(Spinners, name)
self.spinner = sp
# Color Attributes: "color", "on_color", "attrs"
elif name in COLOR_ATTRS:
attr_type = COLOR_MAP[name]
# Call appropriate property setters;
# _color_func is updated automatically by setters.
if attr_type == "attrs":
self.attrs = [name] # calls property setter
if attr_type in ("color", "on_color"):
setattr(self, attr_type, name) # calls property setter
# Side: "left" or "right"
elif name in ("left", "right"):
self.side = name # calls property setter
# Common error for unsupported attributes
else:
raise AttributeError(
"'{0}' object has no attribute: '{1}'".format(
self.__class__.__name__, name
)
)
return self
#
# Properties
#
@property
def spinner(self):
return self._spinner
@spinner.setter
def spinner(self, sp):
self._spinner = self._set_spinner(sp)
self._frames = self._set_frames(self._spinner, self._reversal)
self._interval = self._set_interval(self._spinner)
self._cycle = self._set_cycle(self._frames)
@property
def text(self):
return self._text
@text.setter
def text(self, txt):
self._text = txt
@property
def color(self):
return self._color
@color.setter
def color(self, value):
self._color = self._set_color(value) if value else value
self._color_func = self._compose_color_func() # update
@property
def on_color(self):
return self._on_color
@on_color.setter
def on_color(self, value):
self._on_color = self._set_on_color(value) if value else value
self._color_func = self._compose_color_func() # update
@property
def attrs(self):
return list(self._attrs)
@attrs.setter
def attrs(self, value):
new_attrs = self._set_attrs(value) if value else set()
self._attrs = self._attrs.union(new_attrs)
self._color_func = self._compose_color_func() # update
@property
def side(self):
return self._side
@side.setter
def side(self, value):
self._side = self._set_side(value)
@property
def reversal(self):
return self._reversal
@reversal.setter
def reversal(self, value):
self._reversal = value
self._frames = self._set_frames(self._spinner, self._reversal)
self._cycle = self._set_cycle(self._frames)
@property
def elapsed_time(self):
if self._start_time is None:
return 0
if self._stop_time is None:
return time.time() - self._start_time
return self._stop_time - self._start_time
#
# Public
#
def start(self):
if self._sigmap:
self._register_signal_handlers()
if sys.stdout.isatty():
self._hide_cursor()
self._start_time = time.time()
self._stop_time = None # Reset value to properly calculate subsequent spinner starts (if any) # pylint: disable=line-too-long
self._stop_spin = threading.Event()
self._hide_spin = threading.Event()
self._spin_thread = threading.Thread(target=self._spin)
self._spin_thread.start()
def stop(self):
self._stop_time = time.time()
if self._dfl_sigmap:
# Reset registered signal handlers to default ones
self._reset_signal_handlers()
if self._spin_thread:
self._stop_spin.set()
self._spin_thread.join()
sys.stdout.write("\r")
self._clear_line()
if sys.stdout.isatty():
self._show_cursor()
def hide(self):
"""Hide the spinner to allow for custom writing to the terminal."""
thr_is_alive = self._spin_thread and self._spin_thread.is_alive()
if thr_is_alive and not self._hide_spin.is_set():
with self._stdout_lock:
# set the hidden spinner flag
self._hide_spin.set()
# clear the current line
sys.stdout.write("\r")
self._clear_line()
# flush the stdout buffer so the current line
# can be rewritten to
sys.stdout.flush()
@contextlib.contextmanager
def hidden(self):
"""Hide the spinner within a block, can be nested"""
if self._hidden_level == 0:
self.hide()
self._hidden_level += 1
try:
yield
finally:
self._hidden_level -= 1
if self._hidden_level == 0:
self.show()
def show(self):
"""Show the hidden spinner."""
thr_is_alive = self._spin_thread and self._spin_thread.is_alive()
if thr_is_alive and self._hide_spin.is_set():
with self._stdout_lock:
# clear the hidden spinner flag
self._hide_spin.clear()
# clear the current line so the spinner is not appended to it
sys.stdout.write("\r")
self._clear_line()
def write(self, text):
"""Write text in the terminal without breaking the spinner."""
# similar to tqdm.write()
# https://pypi.python.org/pypi/tqdm#writing-messages
with self._stdout_lock:
sys.stdout.write("\r")
self._clear_line()
if isinstance(text, (str, bytes)):
_text = to_unicode(text)
else:
_text = str(text)
# Ensure output is Unicode
assert isinstance(_text, str)
sys.stdout.write("{0}\n".format(_text))
def ok(self, text="OK"):
"""Set Ok (success) finalizer to a spinner."""
_text = text if text else "OK"
self._freeze(_text)
def fail(self, text="FAIL"):
"""Set fail finalizer to a spinner."""
_text = text if text else "FAIL"
self._freeze(_text)
#
# Protected
#
def _freeze(self, final_text):
"""Stop spinner, compose last frame and 'freeze' it."""
text = to_unicode(final_text)
self._last_frame = self._compose_out(text, mode="last")
# Should be stopped here, otherwise prints after
# self._freeze call will mess up the spinner
self.stop()
with self._stdout_lock:
sys.stdout.write(self._last_frame)
def _spin(self):
while not self._stop_spin.is_set():
if self._hide_spin.is_set():
# Wait a bit to avoid wasting cycles
time.sleep(self._interval)
continue
# Compose output
spin_phase = next(self._cycle)
out = self._compose_out(spin_phase)
# Write
with self._stdout_lock:
sys.stdout.write(out)
self._clear_line()
sys.stdout.flush()
# Wait
self._stop_spin.wait(self._interval)
def _compose_color_func(self):
return functools.partial(
colored,
color=self._color,
on_color=self._on_color,
attrs=list(self._attrs),
)
def _compose_out(self, frame, mode=None):
# Ensure Unicode input
assert isinstance(frame, str)
assert isinstance(self._text, str)
text = self._text
# Colors
if self._color_func is not None:
frame = self._color_func(frame)
# Position
if self._side == "right":
frame, text = text, frame
if self._timer:
sec, fsec = divmod(round(100 * self.elapsed_time), 100)
text += " ({}.{:02.0f})".format(datetime.timedelta(seconds=sec), fsec)
# Mode
if not mode:
out = "\r{0} {1}".format(frame, text)
else:
out = "{0} {1}\n".format(frame, text)
# Ensure output is Unicode
assert isinstance(out, str)
return out
def _register_signal_handlers(self):
# SIGKILL cannot be caught or ignored, and the receiving
# process cannot perform any clean-up upon receiving this
# signal.
if signal.SIGKILL in self._sigmap.keys():
raise ValueError(
"Trying to set handler for SIGKILL signal. "
"SIGKILL cannot be cought or ignored in POSIX systems."
)
for sig, sig_handler in self._sigmap.items():
# A handler for a particular signal, once set, remains
# installed until it is explicitly reset. Store default
# signal handlers for subsequent reset at cleanup phase.
dfl_handler = signal.getsignal(sig)
self._dfl_sigmap[sig] = dfl_handler
# ``signal.SIG_DFL`` and ``signal.SIG_IGN`` are also valid
# signal handlers and are not callables.
if callable(sig_handler):
# ``signal.signal`` accepts handler function which is
# called with two arguments: signal number and the
# interrupted stack frame. ``functools.partial`` solves
# the problem of passing spinner instance into the handler
# function.
sig_handler = functools.partial(sig_handler, spinner=self)
signal.signal(sig, sig_handler)
def _reset_signal_handlers(self):
for sig, sig_handler in self._dfl_sigmap.items():
signal.signal(sig, sig_handler)
#
# Static
#
@staticmethod
def _set_color(value: str) -> str:
available_values = [k for k, v in COLOR_MAP.items() if v == "color"]
if value not in available_values:
raise ValueError(
"'{0}': unsupported color value. Use one of the: {1}".format(
value, ", ".join(available_values)
)
)
return value
@staticmethod
def _set_on_color(value: str) -> str:
available_values = [k for k, v in COLOR_MAP.items() if v == "on_color"]
if value not in available_values:
raise ValueError(
"'{0}': unsupported on_color value. "
"Use one of the: {1}".format(value, ", ".join(available_values))
)
return value
@staticmethod
def _set_attrs(attrs: List[str]) -> Set[str]:
available_values = [k for k, v in COLOR_MAP.items() if v == "attrs"]
for attr in attrs:
if attr not in available_values:
raise ValueError(
| |
# return hud_msg_response
# except (IndexError, requests.exceptions.ReadTimeout) as err_get_hud_msg:
# loguru.logger.debug(err_get_hud_msg)
import urllib.request as r
from tqdm.auto import tqdm
def my_hook(t):
last_b = [0]
def update_to(b=1, bsize=1, tsize=None):
if tsize not in (None, -1):
t.total = tsize
displayed = t.update((b - last_b[0]) * bsize)
last_b[0] = b
return displayed
return update_to
def get_unit():
def retrieve_wtunits():
with tqdm() as t:
reporthook = my_hook(t)
r.urlretrieve(url=wt_units_host, filename=configuration.user_units_file, reporthook=reporthook)
loguru.logger.debug('wtunits.json downloaded')
wt_units_lookup = None
wt_units_host = 'https://raw.githubusercontent.com/diVineProportion/ThunderTac/' \
'ThunderTacX/resources/wtunits.json'
configuration.user_units_file = configuration.user_settings_root.joinpath('wtunits.json')
# if wtunits.json (local) does not exist, retrieve it
if not configuration.user_units_file.exists():
retrieve_wtunits()
# TODO: finish remote to local wtunits.json sync
# # with wtunits.json, get the version of wtunits.json
with open(configuration.user_units_file, 'r', encoding='utf-8') as fo:
wt_units_lookup = json.loads(fo.read())
# local_wt_units_version = wt_units_lookup['version']
# # and compare it to aces.exe version and if they differ
# if aces_version != local_wt_units_version:
# # fetch the remote version of wtunits.json
# remote_wt_units_version = requests.get(wt_units_host).json()['version']
# # and compare to local wtunits.json
# # TODO: replace pseudo code
# # if wtunits.json (remote) version > wtunits.json (local) version, download remote version
wt_units_data = requests.get(wt_units_host).json()
wt_units_version = wt_units_data['version']
return wt_units_lookup
def nxt_sort():
if State.Client.player_obj:
loguru.logger.debug(f"[P] PLAYER OBJECT: -0x{State.Client.player_obj.upper()}")
State.Client.player_obj = False
State.Recorder.sortie_header = False
State.Recorder.discover_unit = False
State.Recorder.once_per_spawn = False
def nxt_batt():
loguru.logger.debug(f"[S] BATT FINISHED: {user_sesid}")
State.Messages.hangar = False
State.Map.information = False
State.Recorder.active = False
State.Recorder.header_placed = False
acmi2zip()
acmi2ftp()
def handler(signal_received, frame):
sys.exit(signal_received)
def area_init():
map_info.main_def()
location = map_info.get_info()
map_total_x, map_total_y = map_info.get_data()
area_latitude = map_total_x / 111302
area_longitude = map_total_y / 111320
return area_latitude, area_longitude, location
def acmi2zip():
if os.path.isfile(filename):
try:
import zlib
compression = zipfile.ZIP_DEFLATED
except (ImportError, AttributeError):
compression = zipfile.ZIP_STORED
modes = {
zipfile.ZIP_DEFLATED: 'deflated',
zipfile.ZIP_STORED: 'stored',
}
with zipfile.ZipFile(f'{filename}.zip', mode='w') as fo:
mode_name = modes[compression]
loguru.logger.debug(f'[SAVE] Compressing ACMI to ZIP.ACMI')
fo.write(f'{filename}', compress_type=compression)
def acmi2ftp():
if mission_category == 'Multiplayer Battle':
if user_sesid == 'UNKNOWN':
return
elif mission_category == 'Test Flight':
return
pathlib_file_object = pathlib.Path(filename)
if pathlib_file_object.is_file():
filename_parts = pathlib_file_object.parts
if ftp_send:
ftp = ftplib.FTP(ftp_addr, ftp_user, ftp_pass)
file = None
try:
file = open(f'{filename}.zip', 'rb')
except FileNotFoundError as err_acmi_ftp_out_file_not_found:
loguru.logger.warning(err_acmi_ftp_out_file_not_found)
except UnboundLocalError as err_acmi_ftp_out_unbound_local_error:
loguru.logger.warning(err_acmi_ftp_out_unbound_local_error)
try:
ftp.cwd(filename_parts[0])
except ftplib.error_perm as err_acmi_ftp_out_change_working_directory_1:
loguru.logger.debug(f'[FTP] Root "{filename_parts[0]}" folder does not exist')
ftp.mkd(filename_parts[0])
loguru.logger.debug(f'[FTP] Creating directory: "{filename_parts[0]}"')
ftp.cwd(filename_parts[0])
finally:
try:
ftp.cwd(filename_parts[1])
loguru.logger.debug(f'[FTP] Changing directory "{filename_parts[1]}"')
except ftplib.error_perm as err_acmi_ftp_out_change_working_directory_2:
loguru.logger.debug(err_acmi_ftp_out_change_working_directory_2)
loguru.logger.debug(f'[FTP] Sub-folder "{filename_parts[1]}" does not exist')
ftp.mkd(filename_parts[1])
loguru.logger.debug(f'[FTP] Creating sub-directory: "{filename_parts[1]}"')
ftp.cwd(filename_parts[1])
ftp.storbinary(f'STOR {pathlib_file_object.name}.zip', file)
# TODO: add url
loguru.logger.debug(f'[FTP] **PLACEHOLDER** FOR URL')
file.close()
ftp.quit()
# # MEGA
# mega = Mega()
# m = mega.login("<EMAIL>", "warthundertacview")
# folder = m.find(f'{user_sesid}')
# try:
# print('try')
# folder[0]
# except:
# print('except')
# m.create_folder(f'{user_sesid}')
# else:
# print('else')
# m.create_folder(f'{user_sesid}')
# folder = m.find(f'{user_sesid}')
# finally:
# print('finally')
# m.upload(f'{file_name}.zip', folder[0])
def parse_clog():
if (latitude and longitude) is not None:
path_war_clogdir = game_logs_path[platform.system()]
temp = f"{str(path_war_clogdir)}/*.clog"
last_clog_fileis = max((glob.glob(temp)), key=os.path.getctime)
with open(last_clog_fileis, 'rb') as f:
xor_ed = f.read()
xor_ed_byte_array = bytearray(xor_ed)
un_xor_ed = un_xor(xor_ed_byte_array)
decode_type = None
decoded = None
if configuration.players_sys == "Darwin":
pass
elif configuration.players_sys == "Linux":
import cchardet as chardet
result = chardet.detect(bytes(un_xor_ed))
decode_type = result['encoding']
elif configuration.players_sys == "Windows":
decode_type = 'ANSI'
try:
decoded = bytes(un_xor_ed).decode(decode_type)
return decoded
except UnicodeDecodeError as parse_clog_unicode_decode_error:
import cchardet as chardet
result = chardet.detect(bytes(un_xor_ed))
decode_type = result['encoding']
decoded = bytes(un_xor_ed).decode(decode_type)
return decoded
except LookupError as parse_clog_lookup_error:
print(f'ERROR 0x1D: {parse_clog_lookup_error}')
sys.exit()
class State:
class Client:
player_obj = ""
parachute = ""
class FileWrite:
discover_unit = False
class GameState:
if platform.system() == "Windows":
if war_lang == "English":
TITLE_HANG = "War Thunder"
TITLE_LOAD = "War Thunder - Loading"
TITLE_BATT = "War Thunder - In battle"
TITLE_DRIV = "War Thunder - Test Drive"
TITLE_TEST = "War Thunder - Test Flight"
TITLE_WAIT = "War Thunder - Waiting for game"
elif war_lang == "French":
TITLE_HANG = "War Thunder"
TITLE_LOAD = "War Thunder - Téléchargement en cours"
TITLE_BATT = "War Thunder - Dans la bataille"
TITLE_DRIV = "War Thunder - Test Drive"
TITLE_TEST = "War Thunder - Vol test"
TITLE_WAIT = "War Thunder - En attente du jeu"
elif platform.system() == "Linux":
if war_lang == "English":
TITLE_HANG = b"War Thunder (Vulkan, 64bit)"
TITLE_LOAD = b"War Thunder (Vulkan, 64bit) - Loading"
TITLE_BATT = b"War Thunder (Vulkan, 64bit) - In battle"
TITLE_DRIV = b"War Thunder (Vulkan, 64bit) - Test Drive"
TITLE_TEST = b"War Thunder (Vulkan, 64bit) - Test Flight"
TITLE_WAIT = b"War Thunder (Vulkan, 64bit) - Waiting for game"
elif war_lang == "French":
TITLE_HANG = "War Thunder (Vulkan, 64bit)"
TITLE_LOAD = "War Thunder (Vulkan, 64bit) - Téléchargement en cours"
TITLE_BATT = "War Thunder (Vulkan, 64bit) - Dans la bataille"
TITLE_DRIV = "War Thunder (Vulkan, 64bit) - Test Drive"
TITLE_TEST = "War Thunder (Vulkan, 64bit) - Vol test"
TITLE_WAIT = "War Thunder (Vulkan, 64bit) - En attente du jeu"
else:
TITLE_HANG = "War Thunder"
TITLE_LOAD = "War Thunder - Loading"
TITLE_BATT = "War Thunder - In battle"
TITLE_DRIV = "War Thunder - Test Drive"
TITLE_TEST = "War Thunder - Test Flight"
TITLE_WAIT = "War Thunder - Waiting for game"
class Map:
information = False
class Messages:
battle = False
hangar = False
rec_end = True
test_flight = False
trigger_chat = False
class Recorder:
active = False
header_placed = False
discover_unit = False
sortie_header = False
start_recording = True
once_per_spawn = False
class WebAPI:
BASE = f"http://{net_host}:{net_port}"
LMAP = f"{BASE}/map.img"
INFO = f"{BASE}/map_info.json"
STAT = f"{BASE}/state"
INDI = f"{BASE}/indicators"
OBJT = f"{BASE}/map_obj.json"
CHAT = f"{BASE}/gamechat"
HMSG = f"{BASE}/hudmsg"
# last_id_msg = 0
# last_id_evt = 0
# last_id_dmg = 0
ntp = ntplib.NTPClient()
unit_lookup = get_unit()
aces_version = configuration.game_version
_dict_sesid = collections.OrderedDict()
_list_teams = []
time_start = time.time()
if ttac_usr is None or ttac_usr == '':
configuration.get_user_alias()
game_logs_path = {
'Linux': pathlib.Path(cfg_root).joinpath('.game_logs/'),
'Windows': pathlib.Path(war_root).joinpath('.game_logs/')
}
# def mqtt_con(client, userdata, flags, rc):
# loguru.logger.debug(f"[Q] CONNECTED: MQTT CONNECT ON TACSERV.TK")
#
# def on_message(client, userdata, msg):
# print(f"{client}, {userdata} {msg.topic}| {msg.payload.decode()}")
#
# def on_subscribe(client, userdata, mid, granted_qos, properties=None):
# print(client, userdata, mid, granted_qos, properties)
# mqtt_client = mqtt.Client()
# mqtt_client.on_connect = mqtt_con
# mqtt_client.on_message = on_message
# mqtt_client.on_subscribe = on_subscribe
state = State.GameState
loguru.logger.info(f'[TT] ThunderTac: v{__init__.__version__}')
loguru.logger.info(f'[WT] Client i18n: {war_lang}')
while True:
# SIGINT: INIT
signal(SIGINT, handler)
# DISCOVER: WINDOW TITLE
curr_game_state = get_window_title()
# PROGRAM STATE: IN HANGAR
if curr_game_state == state.TITLE_HANG:
# STDOUT: RETURNED TO HANGAR
if not State.Messages.hangar:
loguru.logger.info("[TT] Game State: Waiting for Battle or Test Flight")
State.Messages.hangar = True
# STDOUT: RECORDING FINISHED
"""if not State.Messages.rec_end:
loguru.logger.info("[R] THUNDERTAC RECORDING HAS TERMINATED")
State.Messages.rec_end = True"""
# PROGRAM STATE: TEST FLIGHT
elif curr_game_state == State.GameState.TITLE_TEST:
if not State.Messages.test_flight:
loguru.logger.info("[TT] Game State: Joined Flight Test")
State.Messages.test_flight = True
mission_category = 'Test Flight'
# CHECK: LOCATION DATA
if not State.Map.information:
latitude, longitude, map_area = area_init()
if (latitude and longitude) is not None:
State.Map.information = True
State.Recorder.header_placed = False
State.Recorder.sortie_header = False
State.Recorder.active = True
time_rec_start = time.time()
# PROGRAM STATE: IN BATTLE
elif curr_game_state == State.GameState.TITLE_BATT:
if not State.Messages.battle:
loguru.logger.info("[TT] Game State: Joined Battle")
State.Messages.battle = True
mission_category = 'Multiplayer Battle'
# CHECK: LOCATION DATA
if not State.Map.information:
latitude, longitude, map_area = area_init()
if not map_area:
map_area = ''
State.Map.information = True
decoding_result = parse_clog()
split_lines = decoding_result.split('\n')
try:
user_sesid = get_user_session_id(split_lines, _dict_sesid)[-1]
loguru.logger.debug(f'[TT] SESSION ID: "{user_sesid}"')
except IndexError:
loguru.logger.warning(f'[TT] Failed to detect SESSION ID')
if mission_category == 'Test Flight':
user_sesid = 'N/A'
elif mission_category == 'Multiplayer Battle':
user_sesid = 'UNKNOWN'
finally:
loguru.logger.debug(f'[TT] SESSION ID: "{user_sesid}"')
try:
users_team = get_users_team(split_lines, _list_teams, ttac_usr)[-1]
loguru.logger.debug(f'[TT] TEAM ID: "{users_team}"')
except IndexError as err_main_loop_users_team_index_error:
users_team = -1
loguru.logger.warning(f'[TT] Failed to detect TEAM ID')
loguru.logger.debug(f'[TT] TEAM ID: "{users_team}"')
# mqtt_client.connect("tacserv.tk", 1883, 60, )
# mqtt_client.loop_start()
#
# # client.subscribe(f"TTAC/{user_sesid}/TIME_START")
# mqtt_client.publish(f'TTAC/{user_sesid}/players/{user_gid}',
# f"{ttac_usr} is fighting for team {users_team}.", retain=True)
if State.Recorder.start_recording:
if State.Map.information:
time_rec_start = time.time()
loguru.logger.info("[R] RECORD ACTIVE:" + str(time_rec_start))
State.Recorder.sortie_header = False
State.Recorder.active = True
# RECORDING STATE: RECORDING
while State.Recorder.active:
# try:
# hudMsg_dmg_return = get_hud_msg(0, last_id_dmg)['damage']
# if hudMsg_dmg_return:
# # for | |
[True]]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_from_labels_1q_with_phase(self):
"""Test 1-qubit from_labels method with phase."""
labels = ["-I", "iZ", "iZ", "X", "-iY"]
target = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
np.array([2, 3, 3, 0, 1]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_from_labels_2q(self):
"""Test 2-qubit from_labels method."""
labels = ["II", "YY", "XZ"]
target = PauliList.from_symplectic(
np.array([[False, False], [True, True], [True, False]]),
np.array([[False, False], [True, True], [False, True]]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_from_labels_2q_with_phase(self):
"""Test 2-qubit from_labels method."""
labels = ["iII", "iYY", "-iXZ"]
target = PauliList.from_symplectic(
np.array([[False, False], [True, True], [True, False]]),
np.array([[False, False], [True, True], [False, True]]),
np.array([3, 3, 1]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_from_labels_5q(self):
"""Test 5-qubit from_labels method."""
labels = [5 * "I", 5 * "X", 5 * "Y", 5 * "Z"]
target = PauliList.from_symplectic(
np.array([[False] * 5, [False] * 5, [True] * 5, [True] * 5]),
np.array([[False] * 5, [True] * 5, [True] * 5, [False] * 5]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_to_labels_1q(self):
"""Test 1-qubit to_labels method."""
pauli = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
)
target = ["I", "Z", "Z", "X", "Y"]
value = pauli.to_labels()
self.assertEqual(value, target)
def test_to_labels_1q_with_phase(self):
"""Test 1-qubit to_labels method with phase."""
pauli = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
np.array([1, 3, 2, 3, 1]),
)
target = ["-iI", "iZ", "-Z", "iX", "-iY"]
value = pauli.to_labels()
self.assertEqual(value, target)
def test_to_labels_1q_array(self):
"""Test 1-qubit to_labels method w/ array=True."""
pauli = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
)
target = np.array(["I", "Z", "Z", "X", "Y"])
value = pauli.to_labels(array=True)
self.assertTrue(np.all(value == target))
def test_to_labels_1q_array_with_phase(self):
"""Test 1-qubit to_labels method w/ array=True."""
pauli = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
np.array([2, 3, 0, 1, 0]),
)
target = np.array(["-I", "iZ", "Z", "-iX", "Y"])
value = pauli.to_labels(array=True)
self.assertTrue(np.all(value == target))
def test_labels_round_trip(self):
"""Test from_labels and to_labels round trip."""
target = ["III", "IXZ", "XYI", "ZZZ", "-iZIX", "-IYX"]
value = PauliList(target).to_labels()
self.assertEqual(value, target)
def test_labels_round_trip_array(self):
"""Test from_labels and to_labels round trip w/ array=True."""
labels = ["III", "IXZ", "XYI", "ZZZ", "-iZIX", "-IYX"]
target = np.array(labels)
value = PauliList(labels).to_labels(array=True)
self.assertTrue(np.all(value == target))
class TestPauliListMatrix(QiskitTestCase):
"""Tests PauliList matrix representation conversions."""
def test_to_matrix_1q(self):
"""Test 1-qubit to_matrix method."""
labels = ["X", "I", "Z", "Y"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_1q_array(self):
"""Test 1-qubit to_matrix method w/ array=True."""
labels = ["Z", "I", "Y", "X"]
target = np.array([pauli_mat(i) for i in labels])
value = PauliList(labels).to_matrix(array=True)
self.assertTrue(isinstance(value, np.ndarray))
self.assertTrue(np.all(value == target))
def test_to_matrix_1q_sparse(self):
"""Test 1-qubit to_matrix method w/ sparse=True."""
labels = ["X", "I", "Z", "Y"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_2q(self):
"""Test 2-qubit to_matrix method."""
labels = ["IX", "YI", "II", "ZZ"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_2q_array(self):
"""Test 2-qubit to_matrix method w/ array=True."""
labels = ["ZZ", "XY", "YX", "IZ"]
target = np.array([pauli_mat(i) for i in labels])
value = PauliList(labels).to_matrix(array=True)
self.assertTrue(isinstance(value, np.ndarray))
self.assertTrue(np.all(value == target))
def test_to_matrix_2q_sparse(self):
"""Test 2-qubit to_matrix method w/ sparse=True."""
labels = ["IX", "II", "ZY", "YZ"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_5q(self):
"""Test 5-qubit to_matrix method."""
labels = ["IXIXI", "YZIXI", "IIXYZ"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_5q_sparse(self):
"""Test 5-qubit to_matrix method w/ sparse=True."""
labels = ["XXXYY", "IXIZY", "ZYXIX"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_5q_with_phase(self):
"""Test 5-qubit to_matrix method with phase."""
labels = ["iIXIXI", "-YZIXI", "-iIIXYZ"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_5q_sparse_with_phase(self):
"""Test 5-qubit to_matrix method w/ sparse=True with phase."""
labels = ["iXXXYY", "-IXIZY", "-iZYXIX"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
class TestPauliListIteration(QiskitTestCase):
"""Tests for PauliList iterators class."""
def test_enumerate(self):
"""Test enumerate with PauliList."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(pauli):
self.assertEqual(i, PauliList(labels[idx]))
def test_iter(self):
"""Test iter with PauliList."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(iter(pauli)):
self.assertEqual(i, PauliList(labels[idx]))
def test_zip(self):
"""Test zip with PauliList."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for label, i in zip(labels, pauli):
self.assertEqual(i, PauliList(label))
def test_label_iter(self):
"""Test PauliList label_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(pauli.label_iter()):
self.assertEqual(i, labels[idx])
def test_matrix_iter(self):
"""Test PauliList dense matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(pauli.matrix_iter()):
self.assertTrue(np.all(i == pauli_mat(labels[idx])))
def test_matrix_iter_sparse(self):
"""Test PauliList sparse matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(pauli.matrix_iter(sparse=True)):
self.assertTrue(isinstance(i, csr_matrix))
self.assertTrue(np.all(i.toarray() == pauli_mat(labels[idx])))
@ddt
class TestPauliListOperator(QiskitTestCase):
"""Tests for PauliList base operator methods."""
@combine(j=range(1, 10))
def test_tensor(self, j):
"""Test tensor method j={j}."""
labels1 = ["XX", "YY"]
labels2 = [j * "I", j * "Z"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
value = pauli1.tensor(pauli2)
target = PauliList([l1 + l2 for l1 in labels1 for l2 in labels2])
self.assertEqual(value, target)
@combine(j=range(1, 10))
def test_tensor_with_phase(self, j):
"""Test tensor method j={j} with phase."""
labels1 = ["XX", "iYY"]
labels2 = [j * "I", "i" + j * "Z"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
value = pauli1.tensor(pauli2)
target = PauliList(["XX" + "I" * j, "iXX" + "Z" * j, "iYY" + "I" * j, "-YY" + "Z" * j])
self.assertEqual(value, target)
@combine(j=range(1, 10))
def test_expand(self, j):
"""Test expand method j={j}."""
labels1 = ["XX", "YY"]
labels2 = [j * "I", j * "Z"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
value = pauli1.expand(pauli2)
target = PauliList([j + i for j in labels2 for i in labels1])
self.assertEqual(value, target)
@combine(j=range(1, 10))
def test_expand_with_phase(self, j):
"""Test expand method j={j}."""
labels1 = ["-XX", "iYY"]
labels2 = ["i" + j * "I", "-i" + j * "Z"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
value = pauli1.expand(pauli2)
target = PauliList(
["-i" + "I" * j + "XX", "-" + "I" * j + "YY", "i" + "Z" * j + "XX", "Z" * j + "YY"]
)
self.assertEqual(value, target)
def test_compose_1q(self):
"""Test 1-qubit compose methods."""
# Test single qubit Pauli dot products
pauli = PauliList(["I", "X", "Y", "Z"])
with self.subTest(msg="compose single I"):
target = PauliList(["I", "X", "Y", "Z"])
value = pauli.compose("I")
self.assertEqual(target, value)
with self.subTest(msg="compose single X"):
target = PauliList(["X", "I", "iZ", "-iY"])
value = pauli.compose("X")
self.assertEqual(target, value)
with self.subTest(msg="compose single Y"):
target = PauliList(["Y", "-iZ", "I", "iX"])
value = pauli.compose("Y")
self.assertEqual(target, value)
with self.subTest(msg="compose single Z"):
target = PauliList(["Z", "iY", "-iX", "I"])
value = pauli.compose("Z")
self.assertEqual(target, value)
def test_dot_1q(self):
"""Test 1-qubit dot method."""
# Test single qubit Pauli dot products
pauli = PauliList(["I", "X", "Y", "Z"])
with self.subTest(msg="dot single I"):
target = PauliList(["I", "X", "Y", "Z"])
value = pauli.dot("I")
self.assertEqual(target, value)
with self.subTest(msg="dot single X"):
target = PauliList(["X", "I", "-iZ", "iY"])
value = pauli.dot("X")
self.assertEqual(target, value)
with self.subTest(msg="dot single Y"):
target = PauliList(["Y", "iZ", "I", "-iX"])
value = pauli.dot("Y")
self.assertEqual(target, value)
with self.subTest(msg="dot single Z"):
target = PauliList(["Z", "-iY", "iX", "I"])
value = pauli.dot("Z")
self.assertEqual(target, value)
def test_qargs_compose_1q(self):
"""Test 1-qubit compose method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("Z")
with self.subTest(msg="compose 1-qubit qargs=[0]"):
target = PauliList(["IIZ", "iXXY"])
value = pauli1.compose(pauli2, qargs=[0])
self.assertEqual(value, target)
with self.subTest(msg="compose 1-qubit qargs=[1]"):
target = PauliList(["IZI", "iXYX"])
value = pauli1.compose(pauli2, qargs=[1])
self.assertEqual(value, target)
with self.subTest(msg="compose 1-qubit qargs=[2]"):
target | |
<filename>seqpos/lib/python2.7/site-packages/mercurial/setdiscovery.py<gh_stars>0
# setdiscovery.py - improved discovery of common nodeset for mercurial
#
# Copyright 2010 <NAME> <<EMAIL>>
# and <NAME> <<EMAIL>>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
"""
Algorithm works in the following way. You have two repository: local and
remote. They both contains a DAG of changelists.
The goal of the discovery protocol is to find one set of node *common*,
the set of nodes shared by local and remote.
One of the issue with the original protocol was latency, it could
potentially require lots of roundtrips to discover that the local repo was a
subset of remote (which is a very common case, you usually have few changes
compared to upstream, while upstream probably had lots of development).
The new protocol only requires one interface for the remote repo: `known()`,
which given a set of changelists tells you if they are present in the DAG.
The algorithm then works as follow:
- We will be using three sets, `common`, `missing`, `unknown`. Originally
all nodes are in `unknown`.
- Take a sample from `unknown`, call `remote.known(sample)`
- For each node that remote knows, move it and all its ancestors to `common`
- For each node that remote doesn't know, move it and all its descendants
to `missing`
- Iterate until `unknown` is empty
There are a couple optimizations, first is instead of starting with a random
sample of missing, start by sending all heads, in the case where the local
repo is a subset, you computed the answer in one round trip.
Then you can do something similar to the bisecting strategy used when
finding faulty changesets. Instead of random samples, you can try picking
nodes that will maximize the number of nodes that will be
classified with it (since all ancestors or descendants will be marked as well).
"""
from __future__ import absolute_import
import collections
import random
from .i18n import _
from .node import (
nullid,
nullrev,
)
from . import (
error,
util,
)
def _updatesample(revs, heads, sample, parentfn, quicksamplesize=0):
"""update an existing sample to match the expected size
The sample is updated with revs exponentially distant from each head of the
<revs> set. (H~1, H~2, H~4, H~8, etc).
If a target size is specified, the sampling will stop once this size is
reached. Otherwise sampling will happen until roots of the <revs> set are
reached.
:revs: set of revs we want to discover (if None, assume the whole dag)
:heads: set of DAG head revs
:sample: a sample to update
:parentfn: a callable to resolve parents for a revision
:quicksamplesize: optional target size of the sample"""
dist = {}
visit = collections.deque(heads)
seen = set()
factor = 1
while visit:
curr = visit.popleft()
if curr in seen:
continue
d = dist.setdefault(curr, 1)
if d > factor:
factor *= 2
if d == factor:
sample.add(curr)
if quicksamplesize and (len(sample) >= quicksamplesize):
return
seen.add(curr)
for p in parentfn(curr):
if p != nullrev and (not revs or p in revs):
dist.setdefault(p, d + 1)
visit.append(p)
def _takequicksample(repo, headrevs, revs, size):
"""takes a quick sample of size <size>
It is meant for initial sampling and focuses on querying heads and close
ancestors of heads.
:dag: a dag object
:headrevs: set of head revisions in local DAG to consider
:revs: set of revs to discover
:size: the maximum size of the sample"""
sample = set(repo.revs('heads(%ld)', revs))
if len(sample) >= size:
return _limitsample(sample, size)
_updatesample(None, headrevs, sample, repo.changelog.parentrevs,
quicksamplesize=size)
return sample
def _takefullsample(repo, headrevs, revs, size):
sample = set(repo.revs('heads(%ld)', revs))
# update from heads
revsheads = set(repo.revs('heads(%ld)', revs))
_updatesample(revs, revsheads, sample, repo.changelog.parentrevs)
# update from roots
revsroots = set(repo.revs('roots(%ld)', revs))
# _updatesample() essentially does interaction over revisions to look up
# their children. This lookup is expensive and doing it in a loop is
# quadratic. We precompute the children for all relevant revisions and
# make the lookup in _updatesample() a simple dict lookup.
#
# Because this function can be called multiple times during discovery, we
# may still perform redundant work and there is room to optimize this by
# keeping a persistent cache of children across invocations.
children = {}
parentrevs = repo.changelog.parentrevs
for rev in repo.changelog.revs(start=min(revsroots)):
# Always ensure revision has an entry so we don't need to worry about
# missing keys.
children.setdefault(rev, [])
for prev in parentrevs(rev):
if prev == nullrev:
continue
children.setdefault(prev, []).append(rev)
_updatesample(revs, revsroots, sample, children.__getitem__)
assert sample
sample = _limitsample(sample, size)
if len(sample) < size:
more = size - len(sample)
sample.update(random.sample(list(revs - sample), more))
return sample
def _limitsample(sample, desiredlen):
"""return a random subset of sample of at most desiredlen item"""
if len(sample) > desiredlen:
sample = set(random.sample(sample, desiredlen))
return sample
def findcommonheads(ui, local, remote,
initialsamplesize=100,
fullsamplesize=200,
abortwhenunrelated=True,
ancestorsof=None):
'''Return a tuple (common, anyincoming, remoteheads) used to identify
missing nodes from or in remote.
'''
start = util.timer()
roundtrips = 0
cl = local.changelog
clnode = cl.node
clrev = cl.rev
if ancestorsof is not None:
ownheads = [clrev(n) for n in ancestorsof]
else:
ownheads = [rev for rev in cl.headrevs() if rev != nullrev]
# early exit if we know all the specified remote heads already
ui.debug("query 1; heads\n")
roundtrips += 1
sample = _limitsample(ownheads, initialsamplesize)
# indices between sample and externalized version must match
sample = list(sample)
with remote.commandexecutor() as e:
fheads = e.callcommand('heads', {})
fknown = e.callcommand('known', {
'nodes': [clnode(r) for r in sample],
})
srvheadhashes, yesno = fheads.result(), fknown.result()
if cl.tip() == nullid:
if srvheadhashes != [nullid]:
return [nullid], True, srvheadhashes
return [nullid], False, []
# start actual discovery (we note this before the next "if" for
# compatibility reasons)
ui.status(_("searching for changes\n"))
srvheads = []
for node in srvheadhashes:
if node == nullid:
continue
try:
srvheads.append(clrev(node))
# Catches unknown and filtered nodes.
except error.LookupError:
continue
if len(srvheads) == len(srvheadhashes):
ui.debug("all remote heads known locally\n")
return srvheadhashes, False, srvheadhashes
if len(sample) == len(ownheads) and all(yesno):
ui.note(_("all local heads known remotely\n"))
ownheadhashes = [clnode(r) for r in ownheads]
return ownheadhashes, True, srvheadhashes
# full blown discovery
# own nodes I know we both know
# treat remote heads (and maybe own heads) as a first implicit sample
# response
common = cl.incrementalmissingrevs(srvheads)
commoninsample = set(n for i, n in enumerate(sample) if yesno[i])
common.addbases(commoninsample)
# own nodes where I don't know if remote knows them
undecided = set(common.missingancestors(ownheads))
# own nodes I know remote lacks
missing = set()
full = False
progress = ui.makeprogress(_('searching'), unit=_('queries'))
while undecided:
if sample:
missinginsample = [n for i, n in enumerate(sample) if not yesno[i]]
if missing:
missing.update(local.revs('descendants(%ld) - descendants(%ld)',
missinginsample, missing))
else:
missing.update(local.revs('descendants(%ld)', missinginsample))
undecided.difference_update(missing)
if not undecided:
break
if full or common.hasbases():
if full:
ui.note(_("sampling from both directions\n"))
else:
ui.debug("taking initial sample\n")
samplefunc = _takefullsample
targetsize = fullsamplesize
else:
# use even cheaper initial sample
ui.debug("taking quick initial sample\n")
samplefunc = _takequicksample
targetsize = initialsamplesize
if len(undecided) < targetsize:
sample = list(undecided)
else:
sample = samplefunc(local, ownheads, undecided, targetsize)
roundtrips += 1
progress.update(roundtrips)
ui.debug("query %i; still undecided: %i, sample size is: %i\n"
% (roundtrips, len(undecided), len(sample)))
# indices between sample and externalized version must match
sample = list(sample)
with remote.commandexecutor() as e:
yesno = e.callcommand('known', {
'nodes': [clnode(r) for r in sample],
}).result()
full = True
if sample:
commoninsample = set(n for i, n in enumerate(sample) if yesno[i])
common.addbases(commoninsample)
common.removeancestorsfrom(undecided)
# heads(common) == heads(common.bases) since common represents common.bases
# and all its ancestors
# The presence of nullrev will confuse heads(). So filter it out.
result = set(local.revs('heads(%ld)', common.bases - {nullrev}))
elapsed = util.timer() - start
progress.complete()
ui.debug("%d total queries in %.4fs\n" % (roundtrips, elapsed))
msg = ('found %d common and %d unknown server heads,'
' %d roundtrips in %.4fs\n')
missing = set(result) - set(srvheads)
ui.log('discovery', msg, len(result), len(missing), roundtrips,
elapsed)
if not result and srvheadhashes != [nullid]:
if abortwhenunrelated:
raise error.Abort(_("repository is unrelated"))
else:
ui.warn(_("warning: repository is unrelated\n"))
return ({nullid}, True, srvheadhashes,)
anyincoming = (srvheadhashes != [nullid])
result = {clnode(r) for r in result}
| |
or equal to 0'
m7 = m.copy() # the new vector m1 = gradient input + gradient of phi7
# calculating the product between the diagonals and the slices of m
m7[-1] += m[-1]*2.*alpha
return m7
def phi_1(M, L, m, alpha):
'''
Returns the value for the phi1 constraint.
input
M: integer - number of vertices
L: integer - number of prisms
m: 1D array - parameter vector
alpha: float - regularization parameter
output
phi_1: float - value of phi_1 constraint
'''
P = L*(M + 2) + 1
assert m.size == P, 'The size of parameter vector must be equal to P'
assert alpha >= 0., 'alpha must be greater or equal to 0'
m1 = m.copy()
# extracting the non-zero diagonals
d0, d1, dM = diags_phi_1(M, L)
# calculating the product between the diagonals and the slices of m
m1 = m*alpha*d0
m1[:P-1] += m[1:]*alpha*d1
m1[1:] += m[:P-1]*alpha*d1
m1[:P-M+1] += m[M-1:]*alpha*dM
m1[M-1:] += m[:P-M+1]*alpha*dM
phi_1 = np.dot(m1, m)
return phi_1
def phi_2(M, L, m, alpha):
'''
Returns the value for the phi2 constraint.
input
M: integer - number of vertices
L: integer - number of prisms
m: 1D array - parameter vector
alpha: float - weight
output
phi_2: float - value of phi_2 constraint
'''
P = L*(M + 2) + 1
assert m.size == P, 'The size of parameter vector must be equal to P'
assert alpha >= 0., 'alpha must be greater or equal to 0'
# extracting the non-zero diagonals
d0, d1 = diags_phi_2(M, L)
m2 = m.copy()
# calculating the product between the diagonals and the slices of m
m2 = alpha*m*d0
m2[:P-M-2] += alpha*m[M+2:]*d1
m2[M+2:] += alpha*m[:P-M-2]*d1
phi_2 = np.dot(m2, m)
return phi_2
def phi_3(M, L, m, m0, alpha):
'''
Returns the value for the phi3 constraint.
input
M: integer - number of vertices
L: integer - number of prisms
m: 1D array - parameter vector
m0: 1D array - parameters of the outcropping body
alpha: float - weight
output
phi_3: float - value of phi_3 constraint
'''
P = L*(M + 2) + 1
assert m.size == P, 'The size of parameter vector must be equal to P'
assert m0.size == M + 2, 'The size of parameter vector must be equal to M + 2'
assert alpha >= 0., 'alpha must be greater or equal to 0'
m3 = np.zeros(M+2)
# calculating the product between the diagonals and the slices of m
m3 = (m[:M+2] - m0)*alpha
phi_3 = np.dot(m3, m3)
return phi_3
def phi_4(M, L, m, m0, alpha):
'''
Returns the value for the phi4 constraint.
input
M: integer - number of vertices
L: integer - number of prisms
m: 1D array - parameter vector
m0: 1D array - parameters of the outcropping body
alpha: float - weight
output
phi_4: float - value of phi_4 constraint
'''
P = L*(M + 2) + 1
assert m.size == P, 'The size of parameter vector must be equal to P'
assert m0.size == 2, 'The size of parameter vector must be equal to 2'
assert alpha >= 0., 'alpha must be greater or equal to 0'
m4 = np.zeros(2)
# calculating the product between the diagonals and the slices of m
m4 = (m[M:M+2] - m0)*alpha
phi_4 = np.dot(m4, m4)
return phi_4
def phi_5(M, L, m, alpha):
'''
Returns the value for the phi5 constraint.
input
M: integer - number of vertices
L: integer - number of prisms
m: 1D array - parameter vector
alpha: float - weight
output
phi_5: float - value of phi_5 constraint
'''
P = L*(M + 2) + 1
assert m.size == P, 'The size of parameter vector must be equal to P'
assert alpha >= 0., 'alpha must be greater or equal to 0'
m5 = m.copy()
# extracting the non-zero diagonals
d0, d1 = diags_phi_5(M, L)
# calculating the product between the diagonals and the slices of m
m5 = alpha*m*d0
m5[:P-M-2] += alpha*m[M+2:]*d1
m5[M+2:] += alpha*m[:P-M-2]*d1
phi_5 = np.dot(m5, m)
return phi_5
def phi_6(M, L, m, alpha):
'''
Returns the value for the phi6 constraint.
input
M: integer - number of vertices
L: integer - number of prisms
m: 1D array - parameter vector
alpha: float - weight
output
phi_6: float - value of phi_6 constraint
'''
P = L*(M + 2) + 1
assert m.size == P, 'The size of parameter vector must be equal to P'
assert alpha >= 0., 'alpha must be greater or equal to 0'
m6 = m.copy()
# extracting the non-zero diagonals
d0 = diags_phi_6(M, L)
# calculating the product between the diagonals and the slices of m
m6 = alpha*m*d0
phi_6 = np.dot(m6, m)
return phi_6
def phi_7(M, L, m, alpha):
'''
Returns the value for the phi7 constraint.
input
M: integer - number of vertices
L: integer - number of prisms
m: 1D array - parameter vector
alpha: float - weight
output
phi_7: float - value of phi_7 constraint
'''
P = L*(M + 2) + 1
assert m.size == P, 'The size of parameter vector must be equal to P'
assert alpha >= 0., 'alpha must be greater or equal to 0'
m7 = m.copy()
phi_7 = m7[-1]*m7[-1]*alpha
return phi_7
def diags_phi_1(M, L):
'''
Returns the non-zero diagonals of hessian matrix for
the smoothness constraint on adjacent radial distances
in the same prism.
input
M: integer - number of vertices
L: integer - number of prisms
output
d0, d1, dM: 1D array - diagonals from phi_1 hessian
'''
P = L*(M + 2)
# building the diagonals
d0 = np.zeros(M+2)
d0[:M] = 2.
d0 = np.resize(d0, P)
d0 = np.hstack((d0, 0.))
d1 = np.zeros(M+2)
d1[:M-1] = -1.
d1 = np.resize(d1, P-1)
d1 = np.hstack((d1, 0.))
dM = np.zeros(M+2)
dM[0] = -1.
dM = np.resize(dM, P-M+1)
dM = np.hstack((dM, 0.))
d0 = 2.*d0
d1 = 2.*d1
dM = 2.*dM
return d0, d1, dM
def norm_regul_param(M, L, th, m0, a1, a2, a3, a4, a5, a6):
'''
Returns the normalized regularization parameters of each phi.
input
M: integer - number of vertices
L: integer - number of prisms
th: float - trace of the Hessian of initial model
a1: float - weight of phi1
a2: float - weight of phi2
a3: float - weight of phi3
a4: float - weight of phi4
a5: float - weight of phi5
a6: float - weight of phi6
output
alpha1: float - phi1 normalized regularization parameter
alpha2: float - phi2 normalized regularization parameter
alpha3: float - phi3 normalized regularization parameter
alpha4: float - phi4 normalized regularization parameter
alpha5: float - phi5 normalized regularization parameter
alpha6: float - phi6 normalized regularization parameter
'''
# phi1
alpha1 = a1*(th/(2.*L*M))
# phi2
if L <= 2:
alpha2 = a2*(th/(L*M))
else:
alpha2 = a2*(th/(2.*(L-1)*M))
# phi3
m3 = np.ones(M+2)
m3 = (m3 - m0)
alpha3 = a3*(th/np.sum(m3))
# phi4
m4 = np.ones(2)
m4 = (m4 - m0[M:M+2])
alpha4 = a4*(th/np.sum(m4))
# phi5
if L == 2:
alpha5 = a5*(th/(2.*L))
else:
alpha5 = a5*(th/(2.*(L-1)))
# phi6
alpha6 = a6*(th/(L*M))
alpha1 = th*a1
alpha2 = th*a2
alpha3 = th*a3
alpha4 = th*a4
alpha5 = th*a5
alpha6 = th*a6
return alpha1, alpha2, alpha3, alpha4, alpha5, alpha6
def diags_phi_2(M, L):
'''
Returns the non-zero diagonals of hessian matrix for
the smoothness constraint on adjacent radial distances
in the adjacent prisms.
input
M: integer - number of vertices
L: integer - number of prisms
output
d0, d1: 1D array - diagonals from phi_2 hessian
'''
assert L >= 2, 'The number of prisms must be greater than 1'
P = L*(M + 2)
# building the diagonals
d0 = np.zeros(M+2)
if L <= 2:
d0[:M] = 1.
d0 = np.resize(d0, P)
d0 = np.hstack((d0, 0.))
else:
d0[:M] = 2.
d0 = np.resize(d0, P)
d0[:M] -= 1.
d0[-M-2:-2] -= 1.
d0 = np.hstack((d0, 0.))
d1 = np.zeros(M+2)
d1[:M] = -1.
d1 = | |
#!/usr/bin/env python
# coding: utf-8
from getpass import getuser
# Settings of the annotation process
############
# How many frames does a batch scan.
# This excludes the very last frame, since we start at 0.
batchsize = 100
# Show every tickskip-th frame for annotation.
tickskip = 5
# Skip so many batches after each. Example: 3 means batch, skip, skip, skip, batch, ...
batchskip = 3
# Everything further away than this is dropped.
# This is because many lasers put NaN to some number, e.g. 29.999
laser_cutoff = 14
# Where to load the laser csv data and images from.
# TODO: Describe better!
basedir = "/work/" + getuser() + "/strands/wheelchair/dumped/"
# Where to save the detections to.
# TODO: Describe better!
savedir = "/media/" + getuser() + "/NSA1/strands/wheelchair/"
# The field-of-view of the laser you're using.
# From https://github.com/lucasb-eyer/strands_karl/blob/5a2dd60/launch/karl_robot.launch#L25
# TODO: change to min/max for supporting non-zero-centered lasers.
laserFoV = 225
# The field-of-view of the supportive camera you're using.
# From https://www.asus.com/3D-Sensor/Xtion_PRO_LIVE/specifications/
# TODO: change to min/max for supporting non-zero-centered cameras.
cameraFoV = 58
# The size of the camera is needed for pre-generating the image-axes in the plot for efficiency.
camsize = (480, 640)
# Radius of the circle around the cursor, in data-units.
# From https://thesegamesiplay.files.wordpress.com/2015/03/wheelchair.jpg
circrad = 1.22/2
# TODO: make the types of labels configurable? Although, does it even matter?
# End of settings
############
import sys
import os
import json
import time
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.widgets import Cursor, AxesWidget
try:
import cv2
def imread(fname):
img = cv2.imread(fname)
if img is not None:
img = img[:,:,::-1] # BGR to RGB
return img
except ImportError:
# Python 2/3 compatibility
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
from matplotlib.image import imread as mpl_imread
def imread(fname):
try:
return mpl_imread(fname)
except FileNotFoundError:
return None
laserFoV = np.radians(laserFoV)
cameraFoV = np.radians(cameraFoV)
if len(sys.argv) < 2:
print("Usage: {} relative/path/to_file.bag".format(sys.argv[0]))
print()
print("relative to {}".format(basedir))
print("To perform a dry run without saving results use --dry-run or -n.")
print("To change into person annotation mode use --person or -p.")
sys.exit(1)
# Very crude, not robust argv handling.
name = None
dryrun = False
person_mode = False
for arg in sys.argv[1:]:
if arg in ("--dry-run", "-n"):
dryrun = True
elif arg in ("--person", "-p"):
person_mode = True
else:
if name is None:
name = arg
else:
print("Cannot parse arguments, please only specify a single path to the data, and/or flags for dry run or person only annotations.")
sys.exit(1)
def mkdirs(fname):
""" Make directories necessary for creating `fname`. """
dname = os.path.dirname(fname)
if not os.path.isdir(dname):
os.makedirs(dname)
# **TODO**: put into common toolbox repo.
def xy_to_rphi(x, y):
# Note: axes rotated by 90 by intent, so that 0 is top.
return np.hypot(x, y), np.arctan2(-x, y)
def rphi_to_xy(r, phi):
return r * -np.sin(phi), r * np.cos(phi)
def scan_to_xy(scan, thresh=None):
s = np.array(scan, copy=True)
if thresh is not None:
s[s > thresh] = np.nan
angles = np.linspace(-laserFoV/2, laserFoV/2, len(scan))
return rphi_to_xy(scan, angles)
def imload(name, *seqs):
for s in seqs:
fname = "{}{}_dir/{}.jpg".format(basedir, name, int(s))
im = imread(fname)
if im is not None:
return im
print("WARNING: Couldn't find any of " + ' ; '.join(map(str, map(int, seqs))))
return np.zeros(camsize + (3,), dtype=np.uint8)
class Anno1602:
def __init__(self, batches, scans, seqs, laser_thresh=laser_cutoff, circrad=circrad, xlim=None, ylim=None, dryrun=False, person_mode=False):
self.batches = batches
self.scans = scans
self.seqs = seqs
self.b = 0
self.i = 0
self.laser_thresh = laser_thresh
self.circrad = circrad
self.xlim = xlim
self.ylim = ylim
self.dryrun = dryrun
self.person_mode = person_mode
# Build the figure and the axes.
self.fig = plt.figure(figsize=(10,10))
gs = mpl.gridspec.GridSpec(3, 2, width_ratios=(3, 1))
self.axlaser = plt.subplot(gs[:,0])
axprev, axpres, axnext = plt.subplot(gs[0,1]), plt.subplot(gs[1,1]), plt.subplot(gs[2,1])
self.imprev = axprev.imshow(np.random.randint(255, size=camsize + (3,)), interpolation='nearest', animated=True)
self.impres = axpres.imshow(np.random.randint(255, size=camsize + (3,)), interpolation='nearest', animated=True)
self.imnext = axnext.imshow(np.random.randint(255, size=camsize + (3,)), interpolation='nearest', animated=True)
axprev.axis('off')
axpres.axis('off')
axnext.axis('off')
gs.tight_layout(self.fig) # Make better use of the space we have.
self.circ = MouseCircle(self.axlaser, radius=self.circrad, linewidth=1, fill=False)
# Configure interaction
self.fig.canvas.mpl_connect('button_press_event', self.click)
self.fig.canvas.mpl_connect('scroll_event', self.scroll)
self.fig.canvas.mpl_connect('key_press_event', self.key)
# Labels!!
self.wheelchairs = [[None for i in b] for b in batches]
self.walkingaids = [[None for i in b] for b in batches]
self.persons = [[None for i in b] for b in batches]
self.load()
# The pause is needed for the OSX backend.
plt.pause(0.0001)
self.replot()
def save(self):
if self.dryrun:
return
mkdirs(savedir + name)
def _doit(f, data):
for ib, batch in enumerate(data):
if batch is not None:
for i, seq in enumerate(batch):
if seq is not None:
f.write('{},['.format(self.seqs[self.batches[ib][i]]))
f.write(','.join('[{},{}]'.format(*xy_to_rphi(x,y)) for x,y in seq))
f.write(']\n')
if self.person_mode:
with open(savedir + name + ".wp", "w+") as f:
_doit(f, self.persons)
else:
with open(savedir + name + ".wc", "w+") as f:
_doit(f, self.wheelchairs)
with open(savedir + name + ".wa", "w+") as f:
_doit(f, self.walkingaids)
def load(self):
def _doit(f, whereto):
# loading a file can be done here and should "just" be reading it
# line-by-line, de-json-ing the second half of `,` and recording it in
# a dict with the sequence number which is the first half of `,`.
data = {}
for line in f:
seq, tail = line.split(',', 1)
data[int(seq)] = [rphi_to_xy(r, phi) for r,phi in json.loads(tail)]
# Then, in second pass, go through b/i and check for `seqs[batches[b][i]]`
# in that dict, and use that.
for ib, batch in enumerate(whereto):
for i, _ in enumerate(batch):
batch[i] = data.get(self.seqs[self.batches[ib][i]], None)
try:
with open(savedir + name + ".wc", "r") as f:
_doit(f, self.wheelchairs)
with open(savedir + name + ".wa", "r") as f:
_doit(f, self.walkingaids)
with open(savedir + name + ".wp", "r") as f:
_doit(f, self.persons)
except FileNotFoundError:
pass # That's ok, just means no annotations yet.
def replot(self, newbatch=True):
batch = self.batches[self.b]
# This doesn't really belong here, but meh, it needs to happen as soon as a new batch is opened, so here.
# We want to save a batch, even empty, as soon as it has been seen.
if newbatch:
for i, _ in enumerate(self.batches[self.b]):
if self.wheelchairs[self.b][i] is None:
self.wheelchairs[self.b][i] = []
if self.walkingaids[self.b][i] is None:
self.walkingaids[self.b][i] = []
if self.persons[self.b][i] is None:
self.persons[self.b][i] = []
self.axlaser.clear()
self.axlaser.scatter(*scan_to_xy(self.scans[batch[self.i]], self.laser_thresh), s=10, color='#E24A33', alpha=0.5, lw=0)
# Camera frustum to help orientation.
self.axlaser.plot([0, -self.laser_thresh*np.sin(cameraFoV/2)], [0, self.laser_thresh*np.cos(cameraFoV/2)], 'k:')
self.axlaser.plot([0, self.laser_thresh*np.sin(cameraFoV/2)], [0, self.laser_thresh*np.cos(cameraFoV/2)], 'k:')
# Jitter size a little so we can easily see multiple click mistakes.
for x,y in self.wheelchairs[self.b][self.i] or []:
self.axlaser.scatter(x, y, marker='+', s=np.random.uniform(40,60), color='#348ABD')
for x,y in self.walkingaids[self.b][self.i] or []:
self.axlaser.scatter(x, y, marker='x', s=np.random.uniform(40,60), color='#988ED5')
for x,y in self.persons[self.b][self.i] or []:
self.axlaser.scatter(x, y, marker='o', s=np.random.uniform(15,100), color='#50B948', facecolors='none')
# Fix aspect ratio and visible region.
if self.xlim is not None:
self.axlaser.set_xlim(*self.xlim)
if self.ylim is not None:
self.axlaser.set_ylim(*self.ylim)
self.axlaser.set_aspect('equal', adjustable='box') # Force axes to have equal scale.
b = self.seqs[batch[self.i]]
self.impres.set_data(imload(name, b, b-1, b+1, b-2, b+2))
if newbatch:
a = self.seqs[batch[0]]
self.imprev.set_data(imload(name, a, a+1, a+2, a+tickskip, a+batchsize//10, a+batchsize//5, a+batchsize//4))
c = self.seqs[batch[-1]]
self.imnext.set_data(imload(name, c, c-1, c-2, c-tickskip, c-batchsize//10, c-batchsize//5, c-batchsize//4))
self.fig.suptitle("{}: Batch {}/{} frame {}, seq {}".format(name, self.b+1, len(self.batches), self.i*tickskip, self.seqs[batch[self.i]]))
self.fig.canvas.draw()
self.circ._update()
def click(self, e):
if self._ignore(e):
return
# In some rare cases, there is no xdata or ydata (not sure when exactly)
# so we skip them instea of adding them to the list and causing bugs later on!
if e.xdata is None or e.ydata is None:
return
if self.person_mode:
if e.button == 1:
self.persons[self.b][self.i].append((e.xdata, e.ydata))
elif e.button == 2:
self._clear(e.xdata, e.ydata)
else:
if e.button == 1:
self.wheelchairs[self.b][self.i].append((e.xdata, e.ydata))
elif e.button == 3:
self.walkingaids[self.b][self.i].append((e.xdata, e.ydata))
elif e.button == 2:
self._clear(e.xdata, e.ydata)
self.replot(newbatch=False)
def scroll(self, e):
if self._ignore(e):
return
if e.button == 'down':
for _ in range(int(-e.step)):
self._nexti()
elif e.button == 'up':
for _ in range(int(e.step)):
self._previ()
self.replot(newbatch=False)
def key(self, e):
if self._ignore(e):
return
newbatch = False
if e.key in ("left", "a"):
self._nexti()
elif e.key in ("right", "d"):
self._previ()
elif e.key in ("down", "s", "pagedown"):
self._prevb()
newbatch = True
elif e.key in ("up", "w", "pageup"):
self._nextb()
newbatch = True
elif e.key == "c":
self._clear(e.xdata, e.ydata)
else:
print(e.key)
self.replot(newbatch=newbatch)
def _nexti(self):
self.i = max(0, self.i-1)
def _previ(self):
self.i = min(len(self.batches[self.b])-1, self.i+1)
def _nextb(self):
self.save()
self.b += 1
self.i = 0
# We decided to close after the last batch.
if self.b == len(self.batches):
self.b -= 1 # Because it gets redrawn once before closed...
plt.close(self.fig)
| |
<filename>dibs/src/dibs_main.py
import math
import string
import tempfile
import sys
import re
import os, os.path
import time
import smtplib
from dibs_mod_commands import getstatusoutput
import dibs_constants
import dibs_options
import dibs_database
import dibs_logger
import dibs_daemon
import dibs_crypto
import dibs_msg
import dibs_link
import dibs_contract
from ffield import file_ecc
from dibs_utils import *
from dibs_exceptions import *
class DIBS:
"The main class which handles all dibs operations."
# The StoreFileForPeer, ProbeFileForPeer, and other methods
# in in CmdHandler must come before the definition of the
# __init__ method so that these names are defined when
# we define the CmdHandler dictionary.
def StoreFileForPeer(self,dibsM,peer):
if (len(dibsM.payload) > \
self.database.RemainingQuotaForPeerOnOurMachine(peer)):
raise MessageExceedsQuota, (dibsM,\
self.database.QuotaForPeer(peer))
else:
self.database.RememberStoringPieceForPeerOnOurMachine(dibsM,peer)
fileName = self.database.GetNameForPeerFile(dibsM.pieceName,peer)
WriteToFile(dibsM.payload,fileName)
def ClearDBForPeer(self,dibsM,peer):
self.database.ForgetPeersPieces(peer)
def UpdatePeerForgettingUs(self,dibsM,peer):
"""
A peer just told us he forgot our data.
"""
filesAffected = self.database.PeerForgotUs(peer)
if (filesAffected):
MailDataToUser('Peer ' + peer + ' forgot our files.\n' +
'The following files were affected and should'
+ ' probably be recovered or unstored:\n'
+ `filesAffected`,
dibs_options.dibsAdmin,dibs_options.dibsAdmin,
dibs_options.smtpServer)
def UnstoreFileForPeer(self,dMsg,peer):
"""
Remove the piece indicated in the dMsg for peer.
"""
pieceName = dMsg.pieceName
fileName = self.database.GetNameForPeerFile(dMsg.pieceName,peer)
dibs_logger.Logger.PrintAndLog('Trying to unstore piece ' + pieceName +
' requires unstoring file ' +
fileName + '.\n',
dibs_logger.LOG_DEBUG)
if (not os.path.exists(fileName)):
raise RemoteFileNonExistent, pieceName
pieceSize = os.path.getsize(fileName)
# exception will be raised here if the cmdTime for the unstore is
# before the time for the store.
self.database.UnstorePieceForPeerOnOurMachine(
peer,pieceName,pieceSize,dMsg.cmdTime)
dibs_logger.Logger.PrintAndLog('going to remove ' +
fileName + '.\n',dibs_logger.LOG_DEBUG)
os.remove(fileName)
def RecoverAllForPeer(self,dMsg,peer):
dibs_logger.Logger.PrintAndLog('Starting to send back all data to ' +
'peer '+`peer`+' for recover all.',
dibs_logger.LOG_INFO)
for pieceName in self.database.GetPiecesForPeer(peer):
fileName = self.database.GetNameForPeerFile(pieceName,peer)
fd = open(fileName,'rU')
(hdr,body) = dibs_msg.CreateRecoverResponseHeaderAndBody(
pieceName,peer,fd.read())
fd.close()
self.SendDataToPeer(hdr + body,peer)
dibs_logger.Logger.PrintAndLog('Finished sending back all data to ' +
'peer '+`peer`+' for recover all.',
dibs_logger.LOG_INFO)
(hdr,body) = dibs_msg.CreateRecoverAllFinishedHdrAndBdy(peer)
self.SendDataToPeer(hdr + body,peer)
def RecoverFileForPeer(self,dMsg,peer):
"""
Send piece indicated in the dMsg back to peer.
"""
pieceName = dMsg.pieceName
fileName = self.database.GetNameForPeerFile(dMsg.pieceName,peer)
dibs_logger.Logger.PrintAndLog('Sending piece ' + pieceName +
' stored in file ' +
fileName + ' back to peer.\n',
dibs_logger.LOG_DEBUG)
fd = open(fileName,'rU')
(hdr,body) = dibs_msg.CreateRecoverResponseHeaderAndBody(
pieceName,peer,fd.read())
fd.close()
self.SendDataToPeer(hdr + body,peer)
def HandleRecoverResponseFromPeer(self,dMsg,peer):
pieceName = dMsg.pieceName
(file,pieceNum,dir,name)=self.GetRecoveryNamesAndNumbers(pieceName)
if (not os.path.exists(dir)):
os.makedirs(dir)
if (self.database.StillNeedToRecover(file)):
dirPlusName = PathJoin(dir,name)
tempName = dirPlusName + '.tmp'
dibs_logger.Logger.PrintAndLog('Storing piece ' + pieceName +
' in file ' + dirPlusName +
' for recovery.\n',
dibs_logger.LOG_DEBUG)
fd = open(tempName,'wU')
fd.write(dMsg.payload)
fd.close()
dibs_crypto.DecryptFileToFile(tempName,dirPlusName)
os.remove(tempName)
done = self.database.RememberPieceOfFileRecovered(file,pieceNum,
dirPlusName)
if (done):
self.FinishRecoveryByCombiningPieces(file)
else:
dibs_logger.Logger.PrintAndLog('Ignoring piece ' + pieceName +
' of file ' + file
+ ' because recovery complete.',
dibs_logger.LOG_DEBUG)
def HandleRecoverAllResponseFromPeer(self,dMsg,peer):
pieceName = dMsg.pieceName
(file,pieceNum,dir,name)=self.GetRecoveryNamesAndNumbers(pieceName)
if (self.database.StillNeedToRecover(file)):
dirPlusName = PathJoin(dir,name)
tempName = dirPlusName + '.tmp'
dibs_logger.Logger.PrintAndLog('Storing piece ' + pieceName +
' in file ' + dirPlusName +
' for recovery.\n',
dibs_logger.LOG_DEBUG)
fd = open(tempName,'wU')
fd.write(dMsg.payload)
fd.close()
dibs_crypto.DecryptFileToFile(tempName,dirPlusName)
os.remove(tempName)
done = self.database.RememberPieceOfFileRecovered(file,pieceNum)
if (done):
self.FinishRecoveryByCombiningPieces(file)
else:
dibs_logger.Logger.PrintAndLog('Ignoring piece ' + pieceName +
' of file ' + file
+ ' because recovery complete.',
dibs_logger.LOG_DEBUG)
def HandleRecoverAllFinishedFromPeer(self,dMsg,peer):
self.database.PeerDoneRespondingToRecoverAllRequest(peer)
def ProbeFile(self,file):
"""
Takes a file name and sends all peers storing pieces of that file
a probe request.
"""
file = os.path.abspath(file)
piecesAndPeers = self.database.GetPeersAndPiecesForFile(file)
pair = None
for pair in piecesAndPeers:
(hdr, body) = dibs_msg.CreateProbeRequestHeaderAndBody(pair[0],
pair[1])
self.SendDataToPeer(hdr+body,pair[1])
if (pair == None):
raise DIBSException, ('No pieces and peers available for file '
+ file + '.\n')
self.database.RememberAttemptingToProbeFile(file)
def RespondToProbeForPeer(self,dMsg,peer):
"""
Send piece indicated in the dMsg back to peer.
"""
pieceName = dMsg.pieceName
fileName = self.database.GetNameForPeerFile(dMsg.pieceName,peer)
dibs_logger.Logger.PrintAndLog('Sending piece ' + pieceName +
' stored in file ' +
fileName +
' back to peer in response to probe.\n',
dibs_logger.LOG_DEBUG)
fd = open(fileName,'rU')
(hdr,body) = dibs_msg.CreateProbeResponseHeaderAndBody(
pieceName,peer,fd.read())
fd.close()
self.SendDataToPeer(hdr + body,peer)
def HandleProbeResponseFromPeer(self,dMsg,peer):
"""
This function process a probe response from the peer. Currently
the probe message looks very similar to a recover response message.
This function extracts the data from the message and calls the
RememberPieceOfFileProbed to do the heavy lifting.
Note that when we compute the hash of the message payload, we
compute the hash of the *encrypted* payload and do *not*
decrypt the payload. This is because the hash stored in
our database is a hash of the *encrypted* payload.
"""
pieceName = dMsg.pieceName
(file,pieceNum,dir,name)=self.GetRecoveryNamesAndNumbers(pieceName)
hash = HashStringNoB2A(dMsg.payload)
probeMatches = self.database.RememberPieceOfFileProbed(
file,pieceNum,pieceName,hash)
if (not probeMatches):
# The following line tends to fill up the logfile to fast
dibs_logger.Logger.PrintAndLog(
'in probing piece:\n' + pieceName + '\ngot failed match\n' +
dMsg.payload,dibs_logger.LOG_DEBUG)
def __init__(self,database):
"""
Initialize DIBS object.
"""
self.CmdHandler = {
dibs_constants.forgetYouCmdName : 'UpdatePeerForgettingUs',
dibs_constants.clearCmdName : 'ClearDBForPeer',
dibs_constants.storeCmdName : 'StoreFileForPeer',
dibs_constants.probeCmdName : 'RespondToProbeForPeer',
dibs_constants.probeResponseCmdName :
'HandleProbeResponseFromPeer',
dibs_constants.unstoreCmdName : 'UnstoreFileForPeer',
dibs_constants.recoverCmdName : 'RecoverFileForPeer',
dibs_constants.recoverResponseCmdName :
'HandleRecoverResponseFromPeer',
dibs_constants.recoverAllCmdName : 'RecoverAllForPeer',
dibs_constants.doneRecoverAllCmdName :
'HandleRecoverAllFinishedFromPeer',
dibs_constants.proposalCmdName : 'HandlePeerContractProposal',
dibs_constants.proposalResponseCmdName :
'HandlePeerProposalResponse'
}
self.database = database
def SendMessage(self,file,peer):
"""
Take a full message in file and try to send it to peer. If
we are unable to deliver and the message is too old send a
complaint via email.
This function differs from the SendDataToPeer in that
SendMessage is designed to deliver an existing file using
either active or passive mode. SendDataToPeer takes a
message, creates the appropriate file and arranges for the
message to be delivered appropriately. Developers who want
a message delivered should probably use SendDataToPeer and
the only caller of SendMessage should be SendMessageCmd.
"""
(host,port,talk) = self.database.GetCommunicationPrefsForPeer(peer)
if (talk == 'active'):
c = dibs_daemon.DIBSClient(peer,host,port)
if (c.Ok()):
c.TransmitGive([file])
elif (talk != 'passive'):
raise DIBSException, ('Can not send_message "' + file +
'" to ' + peer + ' with talk type ' + talk)
self.ComplainIfMessageTooOld(file)
def SendOutgoingMessages(self):
"""
Go through outgoing directories for each peer and send off
any messages we can.
"""
topDir = dibs_options.outgoingQueueDir
for subdir in os.listdir(topDir):
dibs_logger.Logger.PrintAndLog(
'Looking in ' + subdir + ' for outgoing messages.\n',
dibs_logger.LOG_DEBUG)
if (self.database.PeerKnownP(subdir)):
fullSubdir = PathJoin(topDir,subdir)
(host,port,
talk) = self.database.GetCommunicationPrefsForPeer(subdir)
if (talk == 'active'):
c = dibs_daemon.DIBSClient(subdir,host,port)
if (c.Ok()):
files = []
for file in os.listdir(fullSubdir):
files.append(PathJoin(fullSubdir,file))
if (len(files) > 0):
c.TransmitGive(files)
else:
dibs_logger.Logger.PrintAndLog(
'Not sending messages in \n' + `fullSubdir` +
'\nbecause talk mode is ' + `talk` + '.',
dibs_logger.LOG_DEBUG)
else:
dibs_logger.Logger.PrintAndLog(
'WARNING: Directory ' + subdir +
' not associated with any peers.',dibs_logger.LOG_WARNING)
def ComplainIfMessageTooOld(self,file):
diff = time.time() - GetModTime(file)
if (diff > dibs_options.maxMsgAge):
raise DIBSException, ('Could not deliver msg ' + file +
' after ' + `float(diff)/float(86400)` +
' days.')
def ProcessMessage(self,msgFile):
"""
Take a full mail message as input, veryify the signature, and take
the appropriate action such as storing the file, answering the probe,
etc.
"""
dibsM = dibs_msg.DIBSMsg(msgFile)
# The following line tends to fill up the logfile to fast
#dibs_logger.Logger.PrintAndLog('parsed msg ' + dibsM.__str__(),
# dibs_logger.LOG_DEBUG)
if (dibsM.args.has_key(dibs_constants.publicKeyNameArgName) and
dibsM.args.has_key(dibs_constants.publicKeyArgName)):
dibs_crypto.ImportPublicKeyIfNecessary(
dibsM.args[dibs_constants.publicKeyNameArgName],
dibsM.args[dibs_constants.publicKeyArgName])
dibsSender = self.GetDIBSSender(msgFile)
cmdString = ('self.' + self.CmdHandler[dibsM.cmd] +
'(dibsM,dibsSender)')
dibs_logger.Logger.PrintAndLog('In ProcessMessage executing: ' +
cmdString,dibs_logger.LOG_DEBUG)
eval(cmdString)
def RecoverFile(self,file):
"""
Takes a file name which we are storing remotely and
asks any peers storing it to send us the stored pieces.
Also makes an entry in the recovery database so that
once all pieces have been received the file will be
automatically recovered.
"""
file = os.path.abspath(file)
piecesAndPeers = self.database.GetPeersAndPiecesForFile(file)
pair = None
for pair in piecesAndPeers:
(hdr, body) = dibs_msg.CreateRecoverRequestHeaderAndBody(
pair[0],pair[1])
self.SendDataToPeer(hdr+body,pair[1])
if (pair == None):
raise DIBSException, ('No pieces and peers available for file '
+ file + '.\n')
(file,pieceNum,dir,name) = self.GetRecoveryNamesAndNumbers(pair[0])
dibs_logger.Logger.PrintAndLog('Using dir ' + dir + ' for recovery.',
dibs_logger.LOG_DEBUG)
if (not os.path.exists(dir)):
os.makedirs(dir)
self.database.RememberAttemptingToRecoverFile(file)
dibs_logger.Logger.PrintAndLog('Starting recovery of file '
+ `file` + '.',
dibs_logger.LOG_DEBUG,
dibs_logger.LOG_INFO)
def RecoverAll(self):
"""
Asks all peers to send us back any pieces they are storing.
First we send recover all requests to every peer.
Then we make an entry in the database for every peer
saying that we are in recover all mode. The peers
should start sending back what they are storing for us.
When we get the first piece for a file we should create
a recovery | |
# 'details' hash (which would have a last line of
# '}')
return last_error.error_message()
else:
return traceback.format_exc().splitlines()[-1].strip()
def _calculate_retry_delay(response, num_attempts):
'''
Returns the time in seconds that we should wait.
:param num_attempts: number of attempts that have been made to the
resource, including the most recent failed one
:type num_attempts: int
'''
if response is not None and response.status == 503 and 'retry-after' in response.headers:
try:
return int(response.headers['retry-after'])
except ValueError:
# In RFC 2616, retry-after can be formatted as absolute time
# instead of seconds to wait. We don't bother to parse that,
# but the apiserver doesn't generate such responses anyway.
pass
if num_attempts <= 1:
return 1
num_attempts = min(num_attempts, 7)
return randint(2 ** (num_attempts - 2), 2 ** (num_attempts - 1))
# Truncate the message, if the error injection flag is on, and other
# conditions hold. This causes a BadRequest 400 HTTP code, which is
# subsequentally retried.
#
# Note: the minimal upload size for S3 is 5MB. In theory, you are
# supposed to get an "EntityTooSmall" error from S3, which has a 400
# code. However, I have not observed such responses in practice.
# http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html
def _maybe_truncate_request(url, data):
MIN_UPLOAD_LEN = 16 * 1024
if _INJECT_ERROR:
if (randint(0, 9) == 0) and "upload" in url and len(data) > MIN_UPLOAD_LEN:
logger.info("truncating upload data to length=%d", MIN_UPLOAD_LEN)
return data[0:MIN_UPLOAD_LEN]
return data
def _raise_error_for_testing(try_index=None, method='GET'):
if _INJECT_ERROR and method == 'GET' and randint(0, 9) == 0:
error_thrown = randint(0, 1)
if error_thrown == 0 and try_index is None:
raise exceptions.DXIncompleteReadsError()
# Raise exception to test urllib3 error in downloads
elif error_thrown == 1 and try_index is not None and try_index < 3:
raise exceptions.UrllibInternalError()
def _debug_print_request(debug_level, seq_num, time_started, method, url, headers, jsonify_data, data):
if debug_level >= 2:
if not jsonify_data:
if len(data) == 0:
formatted_data = '""'
else:
formatted_data = "<file data of length " + str(len(data)) + ">"
else:
try:
if _DEBUG >= 3:
formatted_data = json.dumps(data, indent=2)
else:
formatted_data = json.dumps(data)
except (UnicodeDecodeError, TypeError):
formatted_data = "<binary data>"
printable_headers = ''
if 'Range' in headers:
printable_headers = " " + json.dumps({"Range": headers["Range"]})
print("%s [%f] %s %s%s => %s\n" % (YELLOW(BOLD(">%d" % seq_num)),
time_started,
BLUE(method),
url,
printable_headers,
formatted_data),
file=sys.stderr,
end="")
elif debug_level > 0:
print("%s [%f] %s %s => %s\n" % (YELLOW(BOLD(">%d" % seq_num)),
time_started,
BLUE(method),
url,
Repr().repr(data)),
file=sys.stderr,
end="")
def _debug_print_response(debug_level, seq_num, time_started, req_id, response_status, response_was_json, method,
url, content):
if debug_level > 0:
if response_was_json:
if debug_level >= 3:
content_to_print = "\n " + json.dumps(content, indent=2).replace("\n", "\n ")
elif debug_level == 2:
content_to_print = json.dumps(content)
else:
content_to_print = Repr().repr(content)
else:
content_to_print = "(%d bytes)" % len(content) if len(content) > 0 else ''
t = int((time.time() - time_started) * 1000)
code_format = GREEN if (200 <= response_status < 300) else RED
print(" " + YELLOW(BOLD("<%d" % seq_num)),
"[%f]" % time_started,
BLUE(method),
req_id,
url,
"<=",
code_format(str(response_status)),
WHITE(BOLD("(%dms)" % t)),
content_to_print,
file=sys.stderr)
def _test_tls_version():
tls12_check_script = os.path.join(os.getenv("DNANEXUS_HOME"), "build", "tls12check.py")
if not os.path.exists(tls12_check_script):
return
try:
subprocess.check_output(['python', tls12_check_script])
except subprocess.CalledProcessError as e:
if e.returncode == 1:
print (e.output)
raise exceptions.InvalidTLSProtocol
def DXHTTPRequest(resource, data, method='POST', headers=None, auth=True,
timeout=DEFAULT_TIMEOUT,
use_compression=None, jsonify_data=True, want_full_response=False,
decode_response_body=True, prepend_srv=True, session_handler=None,
max_retries=DEFAULT_RETRIES, always_retry=False,
**kwargs):
'''
:param resource: API server route, e.g. "/record/new". If *prepend_srv* is False, a fully qualified URL is expected. If this argument is a callable, it will be called just before each request attempt, and expected to return a tuple (URL, headers). Headers returned by the callback are updated with *headers* (including headers set by this method).
:type resource: string
:param data: Content of the request body
:type data: list or dict, if *jsonify_data* is True; or string or file-like object, otherwise
:param headers: Names and values of HTTP headers to submit with the request (in addition to those needed for authentication, compression, or other options specified with the call).
:type headers: dict
:param auth:
Controls the ``Authentication`` header or other means of authentication supplied with the request. If ``True``
(default), a token is obtained from the ``DX_SECURITY_CONTEXT``. If the value evaluates to false, no action is
taken to prepare authentication for the request. Otherwise, the value is assumed to be callable, and called with
three arguments (method, url, headers) and expected to prepare the authentication headers by reference.
:type auth: tuple, object, True (default), or None
:param timeout: HTTP request timeout, in seconds
:type timeout: float
:param config: *config* value to pass through to :meth:`requests.request`
:type config: dict
:param use_compression: Deprecated
:type use_compression: string or None
:param jsonify_data: If True, *data* is converted from a Python list or dict to a JSON string
:type jsonify_data: boolean
:param want_full_response: If True, the full :class:`requests.Response` object is returned (otherwise, only the content of the response body is returned)
:type want_full_response: boolean
:param decode_response_body: If True (and *want_full_response* is False), the response body is decoded and, if it is a JSON string, deserialized. Otherwise, the response body is uncompressed if transport compression is on, and returned raw.
:type decode_response_body: boolean
:param prepend_srv: If True, prepends the API server location to the URL
:type prepend_srv: boolean
:param session_handler: Deprecated.
:param max_retries: Maximum number of retries to perform for a request. A "failed" request is retried if any of the following is true:
- A response is received from the server, and the content length received does not match the "Content-Length" header.
- A response is received from the server, and the response has an HTTP status code in 5xx range.
- A response is received from the server, the "Content-Length" header is not set, and the response JSON cannot be parsed.
- No response is received from the server, and either *always_retry* is True or the request *method* is "GET".
:type max_retries: int
:param always_retry: If True, indicates that it is safe to retry a request on failure
- Note: It is not guaranteed that the request will *always* be retried on failure; rather, this is an indication to the function that it would be safe to do so.
:type always_retry: boolean
:returns: Response from API server in the format indicated by *want_full_response* and *decode_response_body*.
:raises: :exc:`exceptions.DXAPIError` or a subclass if the server returned a non-200 status code; :exc:`requests.exceptions.HTTPError` if an invalid response was received from the server; or :exc:`requests.exceptions.ConnectionError` if a connection cannot be established.
Wrapper around :meth:`requests.request()` that makes an HTTP
request, inserting authentication headers and (by default)
converting *data* to JSON.
.. note:: Bindings methods that make API calls make the underlying
HTTP request(s) using :func:`DXHTTPRequest`, and most of them
will pass any unrecognized keyword arguments you have supplied
through to :func:`DXHTTPRequest`.
'''
if headers is None:
headers = {}
global _UPGRADE_NOTIFY
seq_num = _get_sequence_number()
url = APISERVER + resource if prepend_srv else resource
method = method.upper() # Convert method name to uppercase, to ease string comparisons later
if auth is True:
auth = AUTH_HELPER
if auth:
auth(_RequestForAuth(method, url, headers))
pool_args = {arg: kwargs.pop(arg, None) for arg in ("verify", "cert_file", "key_file")}
test_retry = kwargs.pop("_test_retry_http_request", False)
# data is a sequence/buffer or a dict
# serialized_data is a sequence/buffer
if jsonify_data:
serialized_data = json.dumps(data)
if 'Content-Type' not in headers and method == 'POST':
headers['Content-Type'] = 'application/json'
else:
serialized_data = data
# If the input is a buffer, its data gets consumed by
# requests.request (moving the read position). Record the initial
# buffer position so that we can return to it if the request fails
# and needs to be retried.
rewind_input_buffer_offset = None
if hasattr(data, 'seek') and hasattr(data, 'tell'):
rewind_input_buffer_offset = data.tell()
# Maintain two separate counters for the number of tries...
try_index = 0 # excluding 503 errors. The number of tries as given here
# cannot exceed (max_retries + 1).
try_index_including_503 = 0 # including 503 errors. This number is used to
# do exponential backoff.
retried_responses = []
_url = None
while True:
success, time_started = True, None
response = None
req_id = None
try:
time_started | |
"""
webcolors.py by <NAME>.
http://pypi.python.org/pypi/webcolors/
License :: OSI Approved :: BSD License
v.1.4
Utility functions for working with the color names and color value
formats defined by the HTML and CSS specifications for use in
documents on the Web.
What this module supports
-------------------------
This module supports the following methods of specifying sRGB colors,
and conversions between them:
* Six-digit hexadecimal.
* Three-digit hexadecimal.
* Integer ``rgb()`` triplet.
* Percentage ``rgb()`` triplet.
* Varying selections of predefined color names.
This module does not support ``hsl()`` triplets, nor does it support
opacity/alpha-channel information via ``rgba()`` or ``hsla()``.
If you need to convert between RGB-specified colors and HSL-specified
colors, or colors specified via other means, consult `the colorsys
module`_ in the Python standard library, which can perform conversions
amongst several common color systems.
.. _the colorsys module: http://docs.python.org/library/colorsys.html
Normalization and conventions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For colors specified via hexadecimal values, this module will accept
input in the following formats:
* A hash mark (#) followed by three hexadecimal digits, where digits
A-F may be upper- or lower-case.
* A hash mark (#) followed by six hexadecimal digits, where digits A-F
may be upper- or lower-case.
For output which consists of a color specified via hexadecimal values,
and for functions which perform intermediate conversion to hexadecimal
before returning a result in another format, this module always
normalizes such values to the following format:
* A hash mark (#) followed by six hexadecimal digits, with digits A-F
forced to lower-case.
The function :func:`normalize_hex` in this module can be used to
perform this normalization manually if desired.
For colors specified via predefined names, this module will accept
input in the following formats:
* An entirely lower-case name, such as ``aliceblue``.
* A name using CamelCase, such as ``AliceBlue``.
For output which consists of a color specified via a predefined name,
and for functions which perform intermediate conversion to a
predefined name before returning a result in another format, this
module always normalizes such values to be entirely lower-case.
For colors specified via ``rgb()`` triplets, values contained in the
triplets will be normalized via clipping in accordance with CSS:
* Integer values less than 0 will be normalized to 0, and percentage
values less than 0% will be normalized to 0%.
* Integer values greater than 255 will be normalized to 255, and
percentage values greater than 100% will be normalized to 100%.
The functions :func:`normalize_integer_triplet` and
:func:`normalize_percent_triplet` in this module can be used to
perform this normalization manually if desired.
For purposes of identifying the specification from which to draw the
selection of defined color names, this module recognizes the following
identifiers:
``html4``
The HTML 4 named colors.
``css2``
The CSS 2 named colors.
``css21``
The CSS 2.1 named colors.
``css3``
The CSS 3/SVG named colors.
The CSS 1 specification is not represented here, as it merely
"suggested" a set of color names, and declined to provide values for
them.
Mappings of color names
-----------------------
For each set of defined color names -- HTML 4, CSS 2, CSS 2.1 and CSS
3 -- this module exports two mappings: one of normalized color names
to normalized hexadecimal values, and one of normalized hexadecimal
values to normalized color names. These eight mappings are as follows:
``html4_names_to_hex``
Mapping of normalized HTML 4 color names to normalized hexadecimal
values.
``html4_hex_to_names``
Mapping of normalized hexadecimal values to normalized HTML 4
color names.
``css2_names_to_hex``
Mapping of normalized CSS 2 color names to normalized hexadecimal
values. Because CSS 2 defines the same set of named colors as HTML
4, this is merely an alias for ``html4_names_to_hex``.
``css2_hex_to_names``
Mapping of normalized hexadecimal values to normalized CSS 2 color
nams. For the reasons described above, this is merely an alias for
``html4_hex_to_names``.
``css21_names_to_hex``
Mapping of normalized CSS 2.1 color names to normalized
hexadecimal values. This is identical to ``html4_names_to_hex``,
except for one addition: ``orange``.
``css21_hex_to_names``
Mapping of normalized hexadecimal values to normalized CSS 2.1
color names. As above, this is identical to ``html4_hex_to_names``
except for the addition of ``orange``.
``css3_names_to_hex``
Mapping of normalized CSS3 color names to normalized hexadecimal
values.
``css3_hex_to_names``
Mapping of normalized hexadecimal values to normalized CSS3 color
names.
"""
import math
import re
def _reversedict(d):
"""
Internal helper for generating reverse mappings; given a
dictionary, returns a new dictionary with keys and values swapped.
"""
return dict(list(zip(list(d.values()), list(d.keys()))))
HEX_COLOR_RE = re.compile(r'^#([a-fA-F0-9]{3}|[a-fA-F0-9]{6})$')
SUPPORTED_SPECIFICATIONS = ('html4', 'css2', 'css21', 'css3')
# Mappings of color names to normalized hexadecimal color values.
#################################################################
html4_names_to_hex = {'aqua': '#00ffff',
'black': '#000000',
'blue': '#0000ff',
'fuchsia': '#ff00ff',
'green': '#008000',
'grey': '#808080',
'lime': '#00ff00',
'maroon': '#800000',
'navy': '#000080',
'olive': '#808000',
'purple': '#800080',
'red': '#ff0000',
'silver': '#c0c0c0',
'teal': '#008080',
'white': '#ffffff',
'yellow': '#ffff00'}
css2_names_to_hex = html4_names_to_hex
css21_names_to_hex = dict(html4_names_to_hex, orange='#ffa500')
css3_names_to_hex = {'aliceblue': '#f0f8ff',
'antiquewhite': '#faebd7',
'aqua': '#00ffff',
'aquamarine': '#7fffd4',
'azure': '#f0ffff',
'beige': '#f5f5dc',
'bisque': '#ffe4c4',
'black': '#000000',
'blanchedalmond': '#ffebcd',
'blue': '#0000ff',
'blueviolet': '#8a2be2',
'brown': '#a52a2a',
'burlywood': '#deb887',
'cadetblue': '#5f9ea0',
'chartreuse': '#7fff00',
'chocolate': '#d2691e',
'coral': '#ff7f50',
'cornflowerblue': '#6495ed',
'cornsilk': '#fff8dc',
'crimson': '#dc143c',
'cyan': '#00ffff',
'darkblue': '#00008b',
'darkcyan': '#008b8b',
'darkgoldenrod': '#b8860b',
'darkgray': '#a9a9a9',
'darkgrey': '#a9a9a9',
'darkgreen': '#006400',
'darkkhaki': '#bdb76b',
'darkmagenta': '#8b008b',
'darkolivegreen': '#556b2f',
'darkorange': '#ff8c00',
'darkorchid': '#9932cc',
'darkred': '#8b0000',
'darksalmon': '#e9967a',
'darkseagreen': '#8fbc8f',
'darkslateblue': '#483d8b',
'darkslategray': '#2f4f4f',
'darkslategrey': '#2f4f4f',
'darkturquoise': '#00ced1',
'darkviolet': '#9400d3',
'deeppink': '#ff1493',
'deepskyblue': '#00bfff',
'dimgray': '#696969',
'dimgrey': '#696969',
'dodgerblue': '#1e90ff',
'firebrick': '#b22222',
'floralwhite': '#fffaf0',
'forestgreen': '#228b22',
'fuchsia': '#ff00ff',
'gainsboro': '#dcdcdc',
'ghostwhite': '#f8f8ff',
'gold': '#ffd700',
'goldenrod': '#daa520',
'gray': '#808080',
'grey': '#808080',
'green': '#008000',
'greenyellow': '#adff2f',
'honeydew': '#f0fff0',
'hotpink': '#ff69b4',
'indianred': '#cd5c5c',
'indigo': '#4b0082',
'ivory': '#fffff0',
'khaki': '#f0e68c',
'lavender': '#e6e6fa',
'lavenderblush': '#fff0f5',
'lawngreen': '#7cfc00',
'lemonchiffon': '#fffacd',
'lightblue': '#add8e6',
'lightcoral': '#f08080',
'lightcyan': '#e0ffff',
'lightgoldenrodyellow': '#fafad2',
'lightgray': '#d3d3d3',
'lightgrey': '#d3d3d3',
'lightgreen': '#90ee90',
'lightpink': '#ffb6c1',
'lightsalmon': '#ffa07a',
'lightseagreen': '#20b2aa',
'lightskyblue': '#87cefa',
'lightslategray': '#778899',
'lightslategrey': '#778899',
'lightsteelblue': '#b0c4de',
'lightyellow': '#ffffe0',
'lime': '#00ff00',
'limegreen': '#32cd32',
'linen': '#faf0e6',
'magenta': '#ff00ff',
'maroon': '#800000',
'mediumaquamarine': '#66cdaa',
'mediumblue': '#0000cd',
'mediumorchid': '#ba55d3',
'mediumpurple': '#9370d8',
'mediumseagreen': '#3cb371',
'mediumslateblue': '#7b68ee',
'mediumspringgreen': '#00fa9a',
'mediumturquoise': '#48d1cc',
'mediumvioletred': '#c71585',
'midnightblue': '#191970',
'mintcream': '#f5fffa',
'mistyrose': '#ffe4e1',
'moccasin': '#ffe4b5',
'navajowhite': '#ffdead',
'navy': '#000080',
'oldlace': '#fdf5e6',
'olive': '#808000',
'olivedrab': '#6b8e23',
'orange': '#ffa500',
'orangered': '#ff4500',
'orchid': '#da70d6',
'palegoldenrod': '#eee8aa',
'palegreen': '#98fb98',
'paleturquoise': '#afeeee',
'palevioletred': '#d87093',
'papayawhip': '#ffefd5',
'peachpuff': '#ffdab9',
'peru': '#cd853f',
'pink': '#ffc0cb',
'plum': '#dda0dd',
'powderblue': '#b0e0e6',
'purple': '#800080',
'red': '#ff0000',
'rosybrown': '#bc8f8f',
'royalblue': '#4169e1',
'saddlebrown': '#8b4513',
'salmon': '#fa8072',
'sandybrown': '#f4a460',
'seagreen': '#2e8b57',
'seashell': '#fff5ee',
'sienna': '#a0522d',
'silver': '#c0c0c0',
'skyblue': '#87ceeb',
'slateblue': '#6a5acd',
'slategray': '#708090',
'slategrey': '#708090',
'snow': '#fffafa',
'springgreen': '#00ff7f',
'steelblue': '#4682b4',
'tan': '#d2b48c',
'teal': '#008080',
'thistle': '#d8bfd8',
'tomato': '#ff6347',
'turquoise': '#40e0d0',
'violet': '#ee82ee',
'wheat': '#f5deb3',
'white': '#ffffff',
'whitesmoke': '#f5f5f5',
'yellow': '#ffff00',
'yellowgreen': '#9acd32'}
# Mappings of normalized hexadecimal color values to color names.
#################################################################
html4_hex_to_names = _reversedict(html4_names_to_hex)
css2_hex_to_names = html4_hex_to_names
css21_hex_to_names = _reversedict(css21_names_to_hex)
css3_hex_to_names = _reversedict(css3_names_to_hex)
# Normalization routines.
#################################################################
def normalize_hex(hex_value):
"""
Normalize a hexadecimal color value to the following form and
return the result::
#[a-f0-9]{6}
In other words, the following transformations are applied as
needed:
* If the value contains only three hexadecimal digits, it is
expanded to six.
* The value is normalized to lower-case.
If the supplied value cannot be interpreted as a hexadecimal color
value, ``ValueError`` is raised.
Examples:
>>> normalize_hex('#0099cc')
'#0099cc'
>>> normalize_hex('#0099CC')
'#0099cc'
>>> normalize_hex('#09c')
'#0099cc'
>>> normalize_hex('#09C')
'#0099cc'
>>> normalize_hex('0099cc')
Traceback (most recent call last):
...
ValueError: '0099cc' is not a valid hexadecimal color value.
"""
try:
hex_digits = HEX_COLOR_RE.match(hex_value).groups()[0]
except AttributeError:
raise ValueError("'%s' is not a valid hexadecimal color value." % hex_value)
if len(hex_digits) == 3:
hex_digits = ''.join([2 * s for s in hex_digits])
return '#%s' % hex_digits.lower()
def normalize_integer_triplet(rgb_triplet):
"""
Normalize an integer ``rgb()`` triplet so that all values are
within the range 0-255 inclusive.
Examples:
>>> normalize_integer_triplet((128, 128, 128))
(128, 128, 128)
>>> normalize_integer_triplet((0, 0, 0))
(0, 0, 0)
>>> normalize_integer_triplet((255, 255, 255))
(255, 255, 255)
>>> normalize_integer_triplet((270, -20, 128))
(255, 0, 128)
"""
return tuple([_normalize_integer_rgb(value) for value in rgb_triplet])
def _normalize_integer_rgb(value):
"""
Normalize ``value`` for use in an integer ``rgb()`` triplet, as follows:
* If ``value`` is less than 0, convert to 0.
* If ``value`` is greater than 255, convert to 255.
Examples:
>>> _normalize_integer_rgb(0)
0
>>> _normalize_integer_rgb(255)
255
>>> _normalize_integer_rgb(128)
128
>>> _normalize_integer_rgb(-20)
0
>>> _normalize_integer_rgb(270)
255
"""
if 0 <= value <= 255:
return value
if value < 0:
return 0
if value > 255:
return 255
def normalize_percent_triplet(rgb_triplet):
"""
Normalize a percentage ``rgb()`` triplet to that all values are
within the range 0%-100% inclusive.
Examples:
>>> normalize_percent_triplet(('50%', | |
try:
curr_attachment_data = curr_attachment_data['m:Attachments']
except Exception as e:
error_code, error_msg = self._get_error_message_from_exception(e)
error_text = EWSONPREM_EXCEPTION_ERR_MESSAGE.format(error_code, error_msg)
self.debug_print("Could not parse the attachments response", error_text)
continue
curr_attachment_data['emailGuid'] = str(uuid.uuid4())
ret_val, data = self._extract_ext_properties(curr_attachment_data, internet_message_id, email_guid)
if data:
email_headers_ret.append(data)
ret_val, email_headers_info, attach_meta_info = self._extract_ext_properties_from_attachments(curr_attachment_data)
if email_headers_info:
email_headers_ret.extend(email_headers_info)
if attach_meta_info:
attach_meta_info_ret.extend(attach_meta_info)
else:
# This is a file attachment, we most probably already have the info from the resp_json
# But update it with the call to the xml_get_attachments_data(..) There might be more info
# that has to be updated
curr_attach_meta_info = self._get_attachment_meta_info(curr_attachment_data['m:Items'], 't:FileAttachment',
internet_message_id, email_guid)
if curr_attach_meta_info:
# find the attachment in the list and update it
matched_meta_info = list(filter(lambda x: x.get('attachmentId', 'foo1') == curr_attach_meta_info.get('attachmentId', 'foo2'),
attach_meta_info_ret))
matched_meta_info[0].update(curr_attach_meta_info)
return (phantom.APP_SUCCESS, email_headers_ret, attach_meta_info_ret)
def _extract_email_headers(self, email_headers):
header_parser = HeaderParser()
email_part = header_parser.parsestr(email_headers)
email_headers = list(email_part.items())
headers = {}
charset = 'utf-8'
try:
[headers.update({x[0]: self._get_string(x[1], charset)}) for x in email_headers]
except Exception as e:
error_code, error_msg = self._get_error_message_from_exception(e)
err = "Error occurred while converting the header tuple into a dictionary"
self.debug_print("{}. {}. {}".format(err, error_code, error_msg))
# Handle received seperately
try:
received_headers = list()
received_headers = [self._get_string(x[1], charset) for x in email_headers if x[0].lower() == 'received']
except Exception as e:
error_code, error_msg = self._get_error_message_from_exception(e)
err = "Error occurred while handling the received header tuple separately"
self.debug_print("{}. {}. {}".format(err, error_code, error_msg))
if received_headers:
headers['Received'] = received_headers
return headers
def _extract_ext_properties(self, resp_json, parent_internet_message_id=None, parent_guid=None): # noqa
if 'm:Items' not in resp_json:
k = next(iter(resp_json.keys()))
resp_json['m:Items'] = resp_json.pop(k)
headers = dict()
extended_properties = list()
data = None
# Get the Extended Properties
try:
for key in EWSONPREM_MAIL_TYPES:
if key in resp_json['m:Items']:
data = resp_json['m:Items'][key]
extended_properties = data['t:ExtendedProperty']
except Exception:
pass
if extended_properties:
if not isinstance(extended_properties, list):
extended_properties = [extended_properties]
for curr_ext_property in extended_properties:
property_tag = curr_ext_property.get('t:ExtendedFieldURI', {}).get('@PropertyTag')
value = curr_ext_property.get('t:Value')
if not property_tag:
continue
if property_tag.lower() in [ews_soap.EXTENDED_PROPERTY_HEADERS.lower(), ews_soap.EXTENDED_PROPERTY_HEADERS_RESPONSE.lower()]:
email_headers = self._extract_email_headers(value)
if email_headers is not None:
headers.update(email_headers)
continue
if property_tag == ews_soap.EXTENDED_PROPERTY_BODY_TEXT:
headers.update({'bodyText': value})
# now parse the body in the main resp_json
try:
body_text = data['t:Body']['#text']
except Exception:
body_text = None
try:
body_type = data['t:Body']['@BodyType']
except Exception:
body_type = None
if body_text is not None:
if body_type is not None:
body_key = "body{0}".format(body_type.title().replace(' ', ''))
headers.update({body_key: body_text})
# if in the response json we find html body then it will not create body text,
# so, we have to create body text headers
if 'bodyText' not in headers:
# try to find body text if it retrived in the response json
try:
self.debug_print("Extracting body text from t:TextBody key from the response")
body_text = data['t:TextBody']['#text']
except Exception:
body_text = None
# if body text not found into the response json
# then, try to create body text from fetched body HTML using Beautiful soup parser
if body_text is None and 'bodyHtml' in headers:
self.debug_print("Extracting body text from bodyHtml key from the headers")
try:
soup = BeautifulSoup(headers.get('bodyHtml'), "html.parser")
if soup.body and soup.body.text:
body_text = soup.body.text
else:
body_text = soup.text
split_lines = body_text.split('\n')
split_lines = [x.strip() for x in split_lines if x.strip()]
body_text = '\n'.join(split_lines)
except Exception:
body_text = None
if body_text is not None:
headers['bodyText'] = body_text
# In some cases the message id is not part of the headers, in this case
# copy the message id from the envelope to the header
headers_ci = CaseInsensitiveDict(headers)
message_id = headers_ci.get('message-id')
if message_id is None:
try:
message_id = data['t:InternetMessageId']
headers['Message-ID'] = message_id
except Exception:
pass
if parent_internet_message_id is not None:
headers['parentInternetMessageId'] = parent_internet_message_id
if parent_guid is not None:
headers['parentGuid'] = parent_guid
headers['emailGuid'] = resp_json['emailGuid']
self.emailGuid = headers['emailGuid']
if 'parentGuid' in headers:
self.parentGuid = headers['parentGuid']
return (phantom.APP_SUCCESS, headers)
def _parse_email(self, resp_json, email_id, target_container_id):
try:
mime_content = next(iter(resp_json['m:Items'].values()))['t:MimeContent']['#text']
except Exception:
return (phantom.APP_ERROR, "Email MimeContent missing in response.")
try:
rfc822_email = base64.b64decode(mime_content)
if not self._python_version == 2:
rfc822_email = UnicodeDammit(rfc822_email).unicode_markup
except Exception as e:
error_code, error_msg = self._get_error_message_from_exception(e)
error_text = EWSONPREM_EXCEPTION_ERR_MESSAGE.format(error_code, error_msg)
self.debug_print("Unable to decode Email Mime Content. {0}".format(error_text))
return (phantom.APP_ERROR, "Unable to decode Email Mime Content")
epoch = self._get_email_epoch(resp_json)
email_header_list = list()
attach_meta_info_list = list()
resp_json['emailGuid'] = str(uuid.uuid4())
ret_val, data = self._extract_ext_properties(resp_json)
if data:
email_header_list.append(data)
ret_val, attach_email_headers, attach_meta_info = self._extract_ext_properties_from_attachments(resp_json)
if attach_email_headers:
email_header_list.extend(attach_email_headers)
if attach_meta_info:
attach_meta_info_list.extend(attach_meta_info)
process_email = ProcessEmail()
return process_email.process_email(self, rfc822_email, email_id, self.get_config(), epoch, target_container_id,
email_headers=email_header_list, attachments_data=attach_meta_info_list)
def _process_email_id(self, email_id, target_container_id=None):
data = ews_soap.xml_get_emails_data([email_id], self._version)
action_result = ActionResult()
ret_val, resp_json = self._make_rest_call(action_result, data, self._check_getitem_response)
# Process errors
if phantom.is_fail(ret_val):
message = "Error while getting email data for id {0}. Error: {1}".format(email_id, action_result.get_message())
self.debug_print(message)
self.send_progress(message)
return phantom.APP_ERROR
ret_val, message = self._parse_email(resp_json, email_id, target_container_id)
if phantom.is_fail(ret_val):
return phantom.APP_ERROR
return phantom.APP_SUCCESS
def _get_email_infos_to_process(self, offset, max_emails, action_result, restriction=None, field_uri="LastModifiedTime"):
config = self.get_config()
# get the user
poll_user = config.get(EWS_JSON_POLL_USER, config[phantom.APP_JSON_USERNAME])
if not poll_user:
return (action_result.set_status(phantom.APP_ERROR, "Polling User Email not specified, cannot continue"), None)
self._target_user = poll_user
folder_path = self._handle_py_ver_compat_for_input_str(config.get(EWS_JSON_POLL_FOLDER, 'Inbox'))
is_public_folder = config.get(EWS_JSON_IS_PUBLIC_FOLDER, False)
ret_val, folder_info = self._get_folder_info(poll_user, folder_path, action_result, is_public_folder)
if phantom.is_fail(ret_val):
return (action_result.get_status(), None)
manner = config[EWS_JSON_INGEST_MANNER]
folder_id = folder_info['id']
order = "Ascending"
if manner == EWS_INGEST_LATEST_EMAILS:
order = "Descending"
data = ews_soap.xml_get_email_ids(
poll_user,
order=order,
offset=offset,
max_emails=max_emails,
folder_id=folder_id,
restriction=restriction,
field_uri=field_uri
)
ret_val, resp_json = self._make_rest_call(action_result, data, self._check_find_response)
# Process errors
if phantom.is_fail(ret_val):
# Dump error messages in the log
self.debug_print(action_result.get_message())
# return error
return (action_result.get_status(), None)
resp_json = resp_json.get('m:RootFolder')
if not resp_json:
return (action_result.set_status(phantom.APP_ERROR, 'Result does not contain required RootFolder key'), None)
resp_items = resp_json.get('t:Items')
if resp_items is None:
self.debug_print("items is None")
return (action_result.set_status(phantom.APP_SUCCESS, 'Result does not contain items key. Possibly no emails in folder'), None)
items = []
for key, value in list(resp_items.items()):
if isinstance(value, dict):
items.append(value)
elif isinstance(value, list):
items.extend(value)
else:
self.debug_print("Skipping the {} key with value {} as it is not in the expected format".format(key, value))
email_infos = [{'id': x['t:ItemId']['@Id'], 'last_modified_time': x['t:LastModifiedTime'],
'created_time': x['t:DateTimeCreated']} for x in items]
return (phantom.APP_SUCCESS, email_infos)
def _pprint_email_id(self, email_id):
return "{0}.........{1}".format(email_id[:20], email_id[-20:])
def _process_email_ids(self, email_ids, action_result):
if email_ids is None:
return action_result.set_status(phantom.APP_ERROR, "Did not get access to email IDs")
self.save_progress("Got {0} email{1}".format(len(email_ids), '' if len(email_ids) == 1 else 's'))
for i, email_id in enumerate(email_ids):
self.send_progress("Querying email # {0} with id: {1}".format(i + 1, self._pprint_email_id(email_id)))
try:
self._process_email_id(email_id)
except Exception as e:
error_code, error_msg = self._get_error_message_from_exception(e)
error_text = EWSONPREM_EXCEPTION_ERR_MESSAGE.format(error_code, error_msg)
self.debug_print("Error occurred in _process_email_id # {0} with Message ID: {1}. {2}".format(i, email_id, error_text))
return action_result.set_status(phantom.APP_SUCCESS)
def _poll_now(self, param):
# Get the maximum number of emails that we can pull
config = self.get_config()
action_result = self.add_action_result(ActionResult(dict(param)))
# Get the maximum number of emails that we can pull, same as container count
max_emails = param[phantom.APP_JSON_CONTAINER_COUNT]
ret_val, max_emails = self._validate_integer(action_result, max_emails, "container_count")
if phantom.is_fail(ret_val):
return action_result.get_status()
self.save_progress("Will be ingesting all possible artifacts (ignoring max artifacts value) for POLL NOW")
email_id = param.get(phantom.APP_JSON_CONTAINER_ID)
email_ids = [email_id]
# get the user
poll_user = config.get(EWS_JSON_POLL_USER, config[phantom.APP_JSON_USERNAME])
if not poll_user:
return (action_result.set_status(phantom.APP_ERROR, "Polling User Email not specified, cannot continue"), None)
self._target_user = poll_user
if not email_id:
self.save_progress("POLL NOW Getting {0} '{1}' email ids".format(max_emails, config[EWS_JSON_INGEST_MANNER]))
sort_on = "DateTimeCreated" if config.get(EWS_JSON_INGEST_TIME, "") == "created time" else "LastModifiedTime"
ret_val, email_infos = self._get_email_infos_to_process(0, max_emails, action_result, field_uri=sort_on)
if phantom.is_fail(ret_val):
return action_result.get_status()
if not email_infos:
return action_result.set_status(phantom.APP_SUCCESS)
email_ids = [x['id'] for x in email_infos]
else:
self.save_progress("POLL NOW Getting the single email id")
return self._process_email_ids(email_ids, action_result)
def _get_restriction(self, field_uri="LastModifiedTime", emails_after="last_email_format"):
"""
Args:
field_uri (str, optional): [Sorting field for the email data]
emails_after (str, optional): [Key to fetch latest ingestion date from the state file]
Returns:
[Restriction]: [Restriction to be used in the soap call]
"""
config = self.get_config()
emails_after_key = 'last_ingested_format' if config[EWS_JSON_INGEST_MANNER] == EWS_INGEST_LATEST_EMAILS else emails_after
date_time_string = self._state.get(emails_after_key)
if not date_time_string:
return None
return ews_soap.xml_get_restriction(date_time_string, field_uri=field_uri)
def _on_poll(self, param):
action_result = self.add_action_result(ActionResult(dict(param)))
# on poll action that is supposed to be scheduled
if self.is_poll_now():
self.debug_print("DEBUGGER: Starting polling now")
return self._poll_now(param)
config = self.get_config()
total_ingested = 0
if self._state.get('first_run', True):
# set the config to _not_ first run
self._state['first_run'] = False
max_emails = config[EWS_JSON_FIRST_RUN_MAX_EMAILS]
ret_val, max_emails = self._validate_integer(action_result, max_emails, EWS_JSON_FIRST_RUN_MAX_EMAILS)
if phantom.is_fail(ret_val):
return action_result.get_status()
run_limit = config[EWS_JSON_FIRST_RUN_MAX_EMAILS]
ret_val, run_limit = self._validate_integer(action_result, | |
%d %B %Y"))
msgDialog.set_title("Attenzione")
msgDialog.run()
msgDialog.destroy()
ordineDialog = ordini.OrdineDialog(self, idOrdine, mode)
ordineDialog.run()
self.refreshOrder(idOrdine, model, iterator)
# Visualizza Ordine
def viewOrder(self, widget, arg1=None, arg2=None):
model, iterator = self.ordiniTreeview.get_selection().get_selected()
if iterator:
idOrdine = model.get_value(iterator, self.ID)
ordineDialog = ordini.OrdineDialog(self, idOrdine, ordini.VIEW_MODE)
ordineDialog.run()
# Stampa ordine suppletivo su modulo U88-Fax (urgente o straordinario)
def printU88FaxSuppletivo(self, widget):
model, iterator = self.ordiniTreeview.get_selection().get_selected()
if iterator:
tipo = model.get_value(iterator, self.SUPPLETIVO)
if (tipo != ordini.ORDINARIO):
data = model.get_value(iterator, self.DATA_SUPPLETIVO)
_id = model.get_value(iterator, self.ID)
try:
conn = prefs.getConn()
cursor = prefs.getCursor(conn)
cursor.execute("select r.ID, r.Ordine from rigaOrdineSuppletivo r where ID_Ordine = ? and r.Ordine > 0", (_id,))
orderList = cursor.fetchall()
stampe.printU88Fax(self, orderList, tipo, data)
except sqlite3.Error as e:
utility.gtkErrorMsg(e, self)
finally:
if cursor:
cursor.close()
if conn:
conn.close()
# Stampa ordine su modulo U88-Fax
def printU88Fax(self, widget):
model, iterator = self.ordiniTreeview.get_selection().get_selected()
if iterator:
_id = model.get_value(iterator, self.ID)
stato = model.get_value(iterator, self.STATO)
if (stato == ordini.IN_CORSO):
try:
conn = prefs.getConn()
cursor = prefs.getCursor(conn)
cursor.execute("select r.ID, r.Ordine from rigaOrdineTabacchi r where ID_Ordine = ? and r.Ordine > 0", (_id,))
orderList = cursor.fetchall()
u88Dialog = U88Dialog(self, model.get_value(iterator, self.CONSEGNA))
result = u88Dialog.run()
if result:
stampe.printU88Fax(self, orderList, result[0], result[1])
except sqlite3.Error as e:
utility.gtkErrorMsg(e, self)
finally:
if cursor:
cursor.close()
if conn:
conn.close()
else:
msgDialog = Gtk.MessageDialog(parent=self, modal=True, message_type=Gtk.MessageType.WARNING,
buttons=Gtk.ButtonsType.OK, text="Devi selezionare un ordine.")
msgDialog.format_secondary_text("Non è stato stampato il modulo U88-Fax.")
msgDialog.set_title("Attenzione")
msgDialog.run()
msgDialog.destroy()
# Stampa Inventario e valorizzazione Articoli
def printInventario(self, widget):
model, iterator = self.ordiniTreeview.get_selection().get_selected()
if iterator:
idOrdine = model.get_value(iterator, self.ID)
data = model.get_value(iterator, self.DATA)
inventarioReport = stampe.InventarioReport(self, idOrdine, data)
fileObj = inventarioReport.build()
if fileObj:
inventarioReport.show(fileObj)
else:
msgDialog = Gtk.MessageDialog(parent=self, modal=True, message_type=Gtk.MessageType.WARNING,
buttons=Gtk.ButtonsType.OK, text="Non ci sono articoli da mostrare")
msgDialog.set_title("Attenzione")
msgDialog.run()
msgDialog.destroy()
# Applicazione principale
class MainApplication(Gtk.Application):
# Main initialization routine
def __init__(self, application_id, flags):
super().__init__(application_id=application_id, flags=flags)
self.mainWindow = None
def do_startup(self):
Gtk.Application.do_startup(self)
# Legge le preferenze e nel caso non ci fossero (prima esecuzione) propone conf. dimostrativa o init.
try:
# Se non trova un Database
if not prefs.checkDB():
msgDialog = Gtk.MessageDialog(message_type=Gtk.MessageType.WARNING, buttons=Gtk.ButtonsType.YES_NO, text="DB non trovato. Creo una configurazione dimostrativa?")
msgDialog.format_secondary_text("Altrimenti, sarà creato un DB vuoto.")
msgDialog.set_title("Attenzione")
response = msgDialog.run()
msgDialog.destroy()
if (response == Gtk.ResponseType.NO):
conn = None
try:
conn = sqlite3.connect(prefs.DB_PATHNAME)
conn.execute("pragma foreign_keys=off;")
# Table: ordineTabacchi
conn.execute("CREATE TABLE ordineTabacchi (ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Data DATETIME NOT NULL, LastPos INTEGER NOT NULL DEFAULT (0), DataSuppletivo DATE DEFAULT NULL, Stato INTEGER NOT NULL DEFAULT (0), Levata DATE DEFAULT NULL, Suppletivo BOOLEAN NOT NULL DEFAULT (0), UNIQUE (Data), UNIQUE (Levata));")
# Table: rigaOrdineSuppletivo
conn.execute("CREATE TABLE rigaOrdineSuppletivo (ID varchar (8) NOT NULL, Descrizione varchar (50) NOT NULL, ID_Ordine integer NOT NULL, Ordine float NOT NULL DEFAULT '0', PRIMARY KEY (ID, ID_Ordine), CONSTRAINT fk_riga_suppletivo FOREIGN KEY (ID_Ordine) REFERENCES ordineTabacchi (ID));")
# Table: rigaOrdineTabacchi
conn.execute("CREATE TABLE rigaOrdineTabacchi (ID TEXT (8) NOT NULL, Descrizione TEXT (50) NOT NULL, ID_Ordine INTEGER NOT NULL, Ordine REAL NOT NULL DEFAULT (0), Prezzo REAL NOT NULL DEFAULT (0), Giacenza REAL NOT NULL DEFAULT (0), Consumo REAL NOT NULL DEFAULT (0), PRIMARY KEY (ID, ID_Ordine), CONSTRAINT fk_riga_ordine FOREIGN KEY (ID_Ordine) REFERENCES ordineTabacchi (ID));")
# Table: tabacchi
conn.execute("CREATE TABLE tabacchi (ID TEXT (8) NOT NULL, Descrizione TEXT (50) NOT NULL DEFAULT NULL, UnitaMin REAL NOT NULL DEFAULT (0), PrezzoKg REAL NOT NULL DEFAULT (0), Tipo TEXT (50) NOT NULL, InMagazzino BOOLEAN NOT NULL DEFAULT (0), LivelloMin REAL NOT NULL DEFAULT (0), Decorrenza DATE NOT NULL DEFAULT ('0000-00-00'), PezziUnitaMin INTEGER NOT NULL DEFAULT (0), Barcode TEXT (20) NOT NULL, PRIMARY KEY (ID));")
# Table: verificaOrdine
conn.execute("CREATE TABLE verificaOrdine (ID VARCHAR (8) NOT NULL, ID_ordine INTEGER NOT NULL, Carico REAL NOT NULL DEFAULT (0), Peso REAL NOT NULL DEFAULT (0), Eliminato BOOLEAN NOT NULL DEFAULT (0), PRIMARY KEY (ID, ID_ordine), CONSTRAINT fk_verificaOrdine_OrdineTabacchi FOREIGN KEY (ID_ordine) REFERENCES ordineTabacchi (ID) ON DELETE NO ACTION ON UPDATE NO ACTION);")
# Index: idx_rigaOrdineSuppletivo_fk_riga_suppletivo
conn.execute("CREATE INDEX idx_rigaOrdineSuppletivo_fk_riga_suppletivo ON rigaOrdineSuppletivo (ID_Ordine);")
# Index: idx_rigaOrdineTabacchi_fk_riga_ordine
conn.execute("CREATE INDEX idx_rigaOrdineTabacchi_fk_riga_ordine ON rigaOrdineTabacchi (ID_Ordine);")
# Index: idx_tabacchi_k_inmagazzino
conn.execute("CREATE INDEX idx_tabacchi_k_inmagazzino ON tabacchi (InMagazzino);")
# Index: idx_tabacchi_k_tipo
conn.execute("CREATE INDEX idx_tabacchi_k_tipo ON tabacchi (Tipo);")
# Index: idx_verificaOrdine_fk_verificaOrdine_OrdineTabacchi
conn.execute("CREATE INDEX idx_verificaOrdine_fk_verificaOrdine_OrdineTabacchi ON verificaOrdine (ID_ordine);")
conn.commit()
except sqlite3.Error as e:
if conn:
conn.rollback()
raise e
finally:
if conn:
conn.close()
elif (response == Gtk.ResponseType.YES):
src = config.BASE_PATH / 'demo/tabacchi.sqlite'
dest = prefs.DB_PATHNAME
dest.write_bytes(src.read_bytes())
src = config.BASE_PATH / 'demo/preferences.cfg'
src_str = src.read_text()
dest_str = src_str.replace('./demo/', f"{config.BASE_PATH / 'demo'}{os.sep}")
dest = config.CONF_PATHNAME
dest.write_text(dest_str)
else:
sys.exit(1)
prefs.load()
except Exception as e:
utility.gtkErrorMsg(e, None)
sys.exit(1)
action = Gio.SimpleAction.new("about", None)
action.connect("activate", self.on_about)
self.add_action(action)
action = Gio.SimpleAction.new("preferences", None)
action.connect("activate", self.gestionePreferenze)
self.add_action(action)
action = Gio.SimpleAction.new("importa", None)
action.connect("activate", self.importLogistaDoc)
self.add_action(action)
action = Gio.SimpleAction.new("ricalcola", None)
action.connect("activate", self.ricalcolaConsumi)
self.add_action(action)
action = Gio.SimpleAction.new("statistiche", None)
action.connect("activate", self.globalStats)
self.add_action(action)
action = Gio.SimpleAction.new("etichette", None)
action.connect("activate", self.printLabels)
self.add_action(action)
action = Gio.SimpleAction.new("articoli", None)
action.connect("activate", self.printElencoArticoli)
self.add_action(action)
action = Gio.SimpleAction.new("excel", None)
action.connect("activate", self.generaExcel)
self.add_action(action)
action = Gio.SimpleAction.new("ordine_excel", None)
action.connect("activate", self.generaOrdineExcel)
self.add_action(action)
action = Gio.SimpleAction.new("quit", None)
action.connect("activate", self.on_quit)
self.add_action(action)
def do_activate(self):
if not self.mainWindow:
self.mainWindow = MainWindow(application=self, title=config.__desc__)
self.mainWindow.connect("delete-event", self.on_quit)
self.mainWindow.set_size_request(600, 500)
self.mainWindow.set_position(Gtk.WindowPosition.CENTER)
self.mainWindow.show_all()
self.mainWindow.checkUpdatePianoLevata()
def on_about(self, action, param):
aboutDialog = Gtk.AboutDialog(transient_for=self.mainWindow, modal=True)
aboutDialog.set_program_name(config.__desc__)
aboutDialog.set_version(config.__version__)
aboutDialog.set_copyright(config.__copyright__)
with open(config.BASE_PATH.parent / 'LICENSE', mode='r') as f:
license = f.read()
aboutDialog.set_license(license)
aboutDialog.set_logo(self.mainWindow.logo)
aboutDialog.present()
# Impostazioni preferenze
def gestionePreferenze(self, action, param):
preferencesDialog = preferencesTabacchi.PreferencesDialog(self.mainWindow)
response = preferencesDialog.run()
if response == Gtk.ResponseType.OK:
self.mainWindow.pianoLevataToolbutton.set_sensitive(prefs.pianoConsegneDaSito)
# Ricalcola i consumi
def ricalcolaConsumi(self, action, param):
thread = RicalcolaConsumiThread()
progressDialog = utility.ProgressDialog(self.mainWindow, "Ricalcolo vendite in corso..",
"In base agli acquisti e alle rimanenze.", "Ricalcolo vendite", thread)
progressDialog.start()
# Statistiche generali
def globalStats(self, action, param):
statsDialog = stats.GlobalStatsDialog(self.mainWindow)
statsDialog.run()
# Genera file Excel per inventario e valorizzazione Magazzino tabacchi
def generaExcel(self, action, param):
HEADER_STYLE = 'font: height 200, bold on; align: vert centre, horiz center; borders: bottom thin;'
CURRENCY_STYLE = xlwt.easyxf('font: height 200; align: vert centre, horiz right;', num_format_str=u'[$\u20ac-1] #,##0.00')
CURRENCY_STYLE_BOLD = xlwt.easyxf('font: height 260, bold on; align: vert centre, horiz right;', num_format_str=u'[$\u20ac-1] #,##0.00')
NUM_STYLE_ED = xlwt.easyxf('protection: cell_locked false; font: height 260; align: vert centre, horiz right;', num_format_str='0')
NUM_STYLE = xlwt.easyxf('font: height 260; align: vert centre, horiz right;', num_format_str='0')
STR_STYLE = xlwt.easyxf('font: height 200; align: vert centre, horiz left;')
STR_STYLE_BOLD_SMALL = xlwt.easyxf('font: height 200, bold on, underline single; align: vert centre, horiz centre;')
QUERY = "SELECT ID, Descrizione, unitaMin, pezziUnitaMin, prezzoKG, tipo FROM tabacchi WHERE InMagazzino ORDER BY Tipo desc,Descrizione"
SHEET_NAME = "tabacchi"
write_book = xlwt.Workbook(encoding='UTF-8')
cur_sheet = write_book.add_sheet(SHEET_NAME)
cur_sheet.protect = True # Il foglio e' tutto protetto per default
cur_sheet.password = <PASSWORD>
cur_sheet.col(2).set_style(CURRENCY_STYLE)
cur_sheet.col(3).set_style(CURRENCY_STYLE)
cur_sheet.col(6).set_style(CURRENCY_STYLE)
cur_sheet.col(0).width = 256 * 8
cur_sheet.col(1).width = 256 * 52
cur_sheet.col(2).width = 256 * 18
cur_sheet.col(3).width = 256 * 16
cur_sheet.col(4).width = 256 * 16
cur_sheet.col(5).width = 256 * 16
cur_sheet.col(6).width = 256 * 16
cur_sheet.col(7).width = 256 * 19
cur_sheet.write(0, 0, "Codice", xlwt.easyxf(HEADER_STYLE))
cur_sheet.write(0, 1, "Descrizione", xlwt.easyxf(HEADER_STYLE))
cur_sheet.write(0, 2, "Pacchetti x conf.", xlwt.easyxf(HEADER_STYLE))
cur_sheet.write(0, 3, "Prezzo pacchetto", xlwt.easyxf(HEADER_STYLE))
cur_sheet.write(0, 4, "Confezioni", xlwt.easyxf(HEADER_STYLE))
cur_sheet.write(0, 5, "Pacchetti", xlwt.easyxf(HEADER_STYLE))
cur_sheet.write(0, 6, "Valore", xlwt.easyxf(HEADER_STYLE))
cursor = None
conn = None
try:
conn = prefs.getConn()
cursor = conn.cursor()
cursor.execute(QUERY)
result_set = cursor.fetchall()
y = 0
for row in result_set:
y += 1
cur_sheet.row(y).height = 320
cur_sheet.write(y, 0, row["ID"], STR_STYLE)
cur_sheet.write(y, 1, row["Descrizione"], STR_STYLE)
pzUnitaMin = row["pezziUnitaMin"]
cur_sheet.write(y, 2, pzUnitaMin, NUM_STYLE)
prezzo = row["prezzoKG"] * row["unitaMin"]
if pzUnitaMin > 0:
cur_sheet.write(y, 3, prezzo / pzUnitaMin, CURRENCY_STYLE)
else:
cur_sheet.write(y, 3, 0, CURRENCY_STYLE)
cur_sheet.write(y, 4, 0, NUM_STYLE_ED)
cur_sheet.write(y, 5, 0, NUM_STYLE_ED)
cur_sheet.write(y, 6, xlwt.Formula('C{0}*E{0}*D{0}+F{0}*D{0}'.format(y + 1)), CURRENCY_STYLE)
except sqlite3.Error as e:
utility.gtkErrorMsg(e, self)
finally:
if cursor:
cursor.close()
if conn:
conn.close()
if y > 0:
y += 1
cur_sheet.row(y + 2).height = 320
cur_sheet.row(y + 3).height = 320
cur_sheet.write(y + 2, 6, " TOTALE ", STR_STYLE_BOLD_SMALL)
cur_sheet.write(y + 3, 6, xlwt.Formula('SUM(G2:G{0})'.format(y)), CURRENCY_STYLE_BOLD)
cur_sheet.write(y + 5, 6, " Aggio (10%) ", STR_STYLE_BOLD_SMALL)
cur_sheet.write(y + 6, 6, xlwt.Formula('G{0}*0.10'.format(y + 4)), CURRENCY_STYLE_BOLD)
cur_sheet.write(y + 8, 6, " TOTALE NETTO ", STR_STYLE_BOLD_SMALL)
cur_sheet.write(y + 9, 6, xlwt.Formula('G{0}*0.90'.format(y + 4)), CURRENCY_STYLE_BOLD)
tmpFile = tempfile.NamedTemporaryFile(delete=False, suffix='.xls')
tmpFile.close()
write_book.save(tmpFile.name)
# Libera le risorse
del write_book
# Apre il file
Gio.Subprocess.new(["gio", "open", tmpFile.name], Gio.SubprocessFlags.STDOUT_PIPE | Gio.SubprocessFlags.STDERR_MERGE)
# Genera file Excel come modello ordine
| |
<gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
# Copyright (c) 2019. <NAME>, <NAME>, <NAME>, #
# <NAME>. All rights reserved. #
# Copyrights licensed under the CC BY 4.0 License. #
# See the accompanying LICENSE file for terms. #
# #
# Date: 8-11-2019 #
# Author: <NAME> #
# E-mail: <EMAIL> #
# Website: vincenzolomonaco.com #
################################################################################
"""
General useful functions for machine learning with Pytorch.
"""
# Python 2-3 compatible
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import numpy as np
import torch
from models.batch_renorm import BatchRenorm2D
from .common import pad_data, shuffle_in_unison, check_ext_mem, check_ram_usage
def train_net(optimizer, model, criterion, mb_size, x, y, t,
train_ep, preproc=None, use_cuda=True, mask=None):
"""
Train a Pytorch model from pre-loaded tensors.
Args:
optimizer (object): the pytorch optimizer.
model (object): the pytorch model to train.
criterion (func): loss function.
mb_size (int): mini-batch size.
x (tensor): train data.
y (tensor): train labels.
t (int): task label.
train_ep (int): number of training epochs.
preproc (func): test iterations.
use_cuda (bool): if we want to use gpu or cpu.
mask (bool): if we want to maks out some classes from the results.
Returns:
ave_loss (float): average loss across the train set.
acc (float): average accuracy over training.
stats (dict): dictionary of several stats collected.
"""
cur_ep = 0
cur_train_t = t
stats = {"ram": [], "disk": []}
if preproc:
x = preproc(x)
(train_x, train_y), it_x_ep = pad_data(
[x, y], mb_size
)
shuffle_in_unison(
[train_x, train_y], 0, in_place=True
)
model = maybe_cuda(model, use_cuda=use_cuda)
acc = None
ave_loss = 0
train_x = torch.from_numpy(train_x).type(torch.FloatTensor)
train_y = torch.from_numpy(train_y).type(torch.LongTensor)
model.train()
for ep in range(train_ep):
stats['disk'].append(check_ext_mem("cl_ext_mem"))
stats['ram'].append(check_ram_usage())
print("training ep: ", ep)
correct_cnt, ave_loss = 0, 0
for it in range(it_x_ep):
start = it * mb_size
end = (it + 1) * mb_size
optimizer.zero_grad()
x_mb = maybe_cuda(train_x[start:end], use_cuda=use_cuda)
y_mb = maybe_cuda(train_y[start:end], use_cuda=use_cuda)
logits = model(x_mb)
_, pred_label = torch.max(logits, 1)
correct_cnt += (pred_label == y_mb).sum()
loss = criterion(logits, y_mb)
ave_loss += loss.item()
loss.backward()
optimizer.step()
acc = correct_cnt.item() / \
((it + 1) * y_mb.size(0))
ave_loss /= ((it + 1) * y_mb.size(0))
if it % 100 == 0:
print(
'==>>> it: {}, avg. loss: {:.6f}, '
'running train acc: {:.3f}'
.format(it, ave_loss, acc)
)
cur_ep += 1
return ave_loss, acc, stats
def preprocess_imgs(img_batch, scale=True, norm=True, channel_first=True):
"""
Here we get a batch of PIL imgs and we return them normalized as for
the pytorch pre-trained models.
Args:
img_batch (tensor): batch of images.
scale (bool): if we want to scale the images between 0 an 1.
channel_first (bool): if the channel dimension is before of after
the other dimensions (width and height).
norm (bool): if we want to normalize them.
Returns:
tensor: pre-processed batch.
"""
if scale:
# convert to float in [0, 1]
img_batch = img_batch / 255
if norm:
# normalize
img_batch[:, :, :, 0] = ((img_batch[:, :, :, 0] - 0.485) / 0.229)
img_batch[:, :, :, 1] = ((img_batch[:, :, :, 1] - 0.456) / 0.224)
img_batch[:, :, :, 2] = ((img_batch[:, :, :, 2] - 0.406) / 0.225)
if channel_first:
# Swap channel dimension to fit the caffe format (c, w, h)
img_batch = np.transpose(img_batch, (0, 3, 1, 2))
return img_batch
def maybe_cuda(what, use_cuda=True, **kw):
"""
Moves `what` to CUDA and returns it, if `use_cuda` and it's available.
Args:
what (object): any object to move to eventually gpu
use_cuda (bool): if we want to use gpu or cpu.
Returns
object: the same object but eventually moved to gpu.
"""
if use_cuda is not False and torch.cuda.is_available():
what = what.cuda()
return what
def test_multitask(
model, test_set, mb_size, preproc=None, use_cuda=True, multi_heads=[],
last_layer_name="output", verbose=True):
"""
Test a model considering that the test set is composed of multiple tests
one for each task.
Args:
model (nn.Module): the pytorch model to test.
test_set (list): list of (x,y,t) test tuples.
mb_size (int): mini-batch size.
preproc (func): image preprocess function.
use_cuda (bool): if we want to use gpu or cpu.
multi_heads (list): ordered list of "heads" to be used for each
task.
Returns:
stats (float): collected stasts of the test including average and
per class accuracies.
"""
model.eval()
acc_x_task = []
stats = {'accs': [], 'acc': []}
preds = []
for (x, y), t in test_set:
if preproc:
x = preproc(x)
if multi_heads != [] and len(multi_heads) > t:
# we can use the stored head
if verbose:
print("Using head: ", t)
with torch.no_grad():
if last_layer_name == "output":
model.output.weight.copy_(multi_heads[t].weight)
else:
model.fc.weight.copy_(multi_heads[t].weight)
model.fc.bias.copy_(multi_heads[t].bias)
model = maybe_cuda(model, use_cuda=use_cuda)
acc = None
test_x = torch.from_numpy(x).type(torch.FloatTensor)
test_y = torch.from_numpy(y).type(torch.LongTensor)
correct_cnt, ave_loss = 0, 0
with torch.no_grad():
iters = test_y.size(0) // mb_size + 1
for it in range(iters):
start = it * mb_size
end = (it + 1) * mb_size
x_mb = maybe_cuda(test_x[start:end], use_cuda=use_cuda)
y_mb = maybe_cuda(test_y[start:end], use_cuda=use_cuda)
logits = model(x_mb)
_, pred_label = torch.max(logits, 1)
correct_cnt += (pred_label == y_mb).sum()
preds += list(pred_label.data.cpu().numpy())
# print(pred_label)
# print(y_mb)
acc = correct_cnt.item() / test_y.shape[0]
if verbose:
print('TEST Acc. Task {}==>>> acc: {:.3f}'.format(t, acc))
acc_x_task.append(acc)
stats['accs'].append(acc)
stats['acc'].append(np.mean(acc_x_task))
if verbose:
print("------------------------------------------")
print("Avg. acc:", stats['acc'])
print("------------------------------------------")
# reset the head for the next batch
if multi_heads:
if verbose:
print("classifier reset...")
with torch.no_grad():
if last_layer_name == "output":
model.output.weight.fill_(0)
else:
model.fc.weight.fill_(0)
model.fc.bias.fill_(0)
return stats, preds
def replace_bn_with_brn(
m, name="", momentum=0.1, r_d_max_inc_step=0.0001, r_max=1.0,
d_max=0.0, max_r_max=3.0, max_d_max=5.0):
for child_name, child in m.named_children():
if isinstance(child, torch.nn.BatchNorm2d):
setattr(m, child_name, BatchRenorm2D(
child.num_features,
gamma=child.weight,
beta=child.bias,
running_mean=child.running_mean,
running_var=child.running_var,
eps=child.eps,
momentum=momentum,
r_d_max_inc_step=r_d_max_inc_step,
r_max=r_max,
d_max=d_max,
max_r_max=max_r_max,
max_d_max=max_d_max
))
else:
replace_bn_with_brn(child, child_name, momentum, r_d_max_inc_step, r_max, d_max,
max_r_max, max_d_max)
def change_brn_pars(
m, name="", momentum=0.1, r_d_max_inc_step=0.0001, r_max=1.0,
d_max=0.0):
for target_name, target_attr in m.named_children():
if isinstance(target_attr, BatchRenorm2D):
target_attr.momentum = torch.tensor(momentum, requires_grad=False)
target_attr.r_max = torch.tensor(r_max, requires_grad=False)
target_attr.d_max = torch.tensor(d_max, requires_grad=False)
target_attr.r_d_max_inc_step = r_d_max_inc_step
else:
change_brn_pars(target_attr, target_name, momentum, r_d_max_inc_step, r_max, d_max)
def consolidate_weights(model, cur_clas):
""" Mean-shift for the target layer weights"""
with torch.no_grad():
globavg = np.average(model.output.weight.detach()
.cpu().numpy()[cur_clas])
for c in cur_clas:
w = model.output.weight.detach().cpu().numpy()[c]
if c in cur_clas:
new_w = w - globavg
if c in model.saved_weights.keys():
wpast_j = np.sqrt(model.past_j[c] / model.cur_j[c])
model.saved_weights[c] = (model.saved_weights[c] * wpast_j
+ new_w) / (wpast_j + 1)
else:
model.saved_weights[c] = new_w
def set_consolidate_weights(model):
""" set trained weights """
with torch.no_grad():
for c, w in model.saved_weights.items():
model.output.weight[c].copy_(
torch.from_numpy(model.saved_weights[c])
)
def reset_weights(model, cur_clas):
""" reset weights"""
with torch.no_grad():
model.output.weight.fill_(0.0)
for c, w in model.saved_weights.items():
if c in cur_clas:
model.output.weight[c].copy_(
torch.from_numpy(model.saved_weights[c])
)
def examples_per_class(train_y):
count = {i:0 for i in range(50)}
for y in train_y:
count[int(y)] +=1
return count
def set_brn_to_train(m, name=""):
for target_name, target_attr in m.named_children():
if isinstance(target_attr, BatchRenorm2D):
target_attr.train()
else:
set_brn_to_train(target_attr, target_name)
def set_brn_to_eval(m, name=""):
for target_name, target_attr in m.named_children():
if isinstance(target_attr, BatchRenorm2D):
target_attr.eval()
else:
set_brn_to_eval(target_attr, target_name)
def set_bn_to(m, name="", phase="train"):
for target_name, target_attr in m.named_children():
if isinstance(target_attr, torch.nn.BatchNorm2d):
if phase == "train":
target_attr.train()
else:
target_attr.eval()
else:
set_bn_to(target_attr, target_name, phase)
def freeze_up_to(model, freeze_below_layer, only_conv=False):
for name, param in model.named_parameters():
# tells whether we want to use gradients for a given parameter
if only_conv:
if "conv" in name:
param.requires_grad = False
print("Freezing parameter " + name)
else:
param.requires_grad = False
print("Freezing parameter " + name)
if name == freeze_below_layer:
break
def create_syn_data(model):
size = 0
print('Creating Syn data for Optimal params and their Fisher info')
for name, param in model.named_parameters():
if "bn" not in name and "output" not in name:
print(name, param.flatten().size(0))
size += param.flatten().size(0)
# The first array returned is a 2D array: the first component contains
# the params at loss minimum, the second the parameter importance
# The second array is a dictionary with the synData
synData = {}
synData['old_theta'] = torch.zeros(size, dtype=torch.float32)
synData['new_theta'] = torch.zeros(size, dtype=torch.float32)
synData['grad'] = torch.zeros(size, dtype=torch.float32)
synData['trajectory'] = torch.zeros(size, dtype=torch.float32)
synData['cum_trajectory'] = torch.zeros(size, dtype=torch.float32)
return torch.zeros((2, size), dtype=torch.float32), synData
def extract_weights(model, target):
with torch.no_grad():
weights_vector= None
for name, param in model.named_parameters():
if "bn" not in name and "output" not in name:
# print(name, param.flatten())
if weights_vector is None:
weights_vector = param.flatten()
else:
weights_vector = torch.cat(
(weights_vector, param.flatten()), 0)
target[...] = weights_vector.cpu()
def extract_grad(model, target):
# Store the gradients into target
with torch.no_grad():
grad_vector= None
for name, param in model.named_parameters():
if "bn" not in name and "output" not in name:
# print(name, param.flatten())
if grad_vector is None:
grad_vector = param.grad.flatten()
else:
| |
from gssapi.raw import creds as rcreds
from gssapi.raw import named_tuples as tuples
from gssapi._utils import import_gssapi_extension, _encode_dict
from gssapi import names
rcred_imp_exp = import_gssapi_extension('cred_imp_exp')
rcred_s4u = import_gssapi_extension('s4u')
rcred_cred_store = import_gssapi_extension('cred_store')
rcred_rfc5588 = import_gssapi_extension('rfc5588')
class Credentials(rcreds.Creds):
"""GSSAPI Credentials
This class represents a set of GSSAPI credentials which may
be used with and/or returned by other GSSAPI methods.
It inherits from the low-level GSSAPI :class:`~gssapi.raw.creds.Creds`
class, and thus may used with both low-level and high-level API methods.
If your implementation of GSSAPI supports the credentials import-export
extension, you may pickle and unpickle this object.
The constructor either acquires or imports a set of GSSAPI
credentials.
If the `base` argument is used, an existing
:class:`~gssapi.raw.creds.Cred` object from the low-level API is
converted into a high-level object.
If the `token` argument is used, the credentials
are imported using the token, if the credentials import-export
extension is supported (:requires-ext:`cred_imp_exp`).
Otherwise, the credentials are acquired as per the
:meth:`acquire` method.
Raises:
BadMechanismError
BadNameTypeError
BadNameError
ExpiredCredentialsError
MissingCredentialsError
"""
__slots__ = ()
def __new__(cls, base=None, token=None, name=None, lifetime=None,
mechs=None, usage='both', store=None):
# TODO(directxman12): this is missing support for password
# (non-RFC method)
if base is not None:
base_creds = base
elif token is not None:
if rcred_imp_exp is None:
raise NotImplementedError("Your GSSAPI implementation does "
"not have support for importing and "
"exporting creditials")
base_creds = rcred_imp_exp.import_cred(token)
else:
res = cls.acquire(name, lifetime, mechs, usage,
store=store)
base_creds = res.creds
return super(Credentials, cls).__new__(cls, base_creds)
@property
def name(self):
"""Get the name associated with these credentials"""
return self.inquire(name=True, lifetime=False,
usage=False, mechs=False).name
@property
def lifetime(self):
"""Get the remaining lifetime of these credentials"""
return self.inquire(name=False, lifetime=True,
usage=False, mechs=False).lifetime
@property
def mechs(self):
"""Get the mechanisms for these credentials"""
return self.inquire(name=False, lifetime=False,
usage=False, mechs=True).mechs
@property
def usage(self):
"""Get the usage (initiate, accept, or both) of these credentials"""
return self.inquire(name=False, lifetime=False,
usage=True, mechs=False).usage
@classmethod
def acquire(cls, name=None, lifetime=None, mechs=None, usage='both',
store=None):
"""Acquire GSSAPI credentials
This method acquires credentials. If the `store` argument is
used, the credentials will be acquired from the given
credential store (if supported). Otherwise, the credentials are
acquired from the default store.
The credential store information is a dictionary containing
mechanisms-specific keys and values pointing to a credential store
or stores.
Using a non-default store requires support for the credentials store
extension.
Args:
name (Name): the name associated with the credentials,
or None for the default name
lifetime (int): the desired lifetime of the credentials, or None
for indefinite
mechs (list): the desired :class:`MechType`s to be used with the
credentials, or None for the default set
usage (str): the usage for the credentials -- either 'both',
'initiate', or 'accept'
store (dict): the credential store information pointing to the
credential store from which to acquire the credentials,
or None for the default store (:requires-ext:`cred_store`)
Returns:
AcquireCredResult: the acquired credentials and information about
them
Raises:
BadMechanismError
BadNameTypeError
BadNameError
ExpiredCredentialsError
MissingCredentialsError
"""
if store is None:
res = rcreds.acquire_cred(name, lifetime,
mechs, usage)
else:
if rcred_cred_store is None:
raise NotImplementedError("Your GSSAPI implementation does "
"not have support for manipulating "
"credential stores")
store = _encode_dict(store)
res = rcred_cred_store.acquire_cred_from(store, name,
lifetime, mechs,
usage)
return tuples.AcquireCredResult(cls(base=res.creds), res.mechs,
res.lifetime)
def store(self, store=None, usage='both', mech=None,
overwrite=False, set_default=False):
"""Store these credentials into the given store
This method stores the current credentials into the specified
credentials store. If the default store is used, support for
:rfc:`5588` is required. Otherwise, support for the credentials
store extension is required.
:requires-ext:`rfc5588` or :requires-ext:`cred_store`
Args:
store (dict): the store into which to store the credentials,
or None for the default store.
usage (str): the usage to store the credentials with -- either
'both', 'initiate', or 'accept'
mech (OID): the :class:`MechType` to associate with the
stored credentials
overwrite (bool): whether or not to overwrite existing credentials
stored with the same name, etc
set_default (bool): whether or not to set these credentials as
the default credentials for the given store.
Returns:
StoreCredResult: the results of the credential storing operation
Raises:
GSSError
ExpiredCredentialsError
MissingCredentialsError
OperationUnavailableError
DuplicateCredentialsElementError
"""
if store is None:
if rcred_rfc5588 is None:
raise NotImplementedError("Your GSSAPI implementation does "
"not have support for RFC 5588")
return rcred_rfc5588.store_cred(self, usage, mech,
overwrite, set_default)
else:
if rcred_cred_store is None:
raise NotImplementedError("Your GSSAPI implementation does "
"not have support for manipulating "
"credential stores directly")
store = _encode_dict(store)
return rcred_cred_store.store_cred_into(store, self, usage, mech,
overwrite, set_default)
def impersonate(self, name=None, lifetime=None, mechs=None,
usage='initiate'):
"""Impersonate a name using the current credentials
This method acquires credentials by impersonating another
name using the current credentials.
:requires-ext:`s4u`
Args:
name (Name): the name to impersonate
lifetime (int): the desired lifetime of the new credentials,
or None for indefinite
mechs (list): the desired :class:`MechType`s for the new
credentials
usage (str): the desired usage for the new credentials -- either
'both', 'initiate', or 'accept'. Note that some mechanisms
may only support 'initiate'.
Returns:
Credentials: the new credentials impersonating the given name
"""
if rcred_s4u is None:
raise NotImplementedError("Your GSSAPI implementation does not "
"have support for S4U")
res = rcred_s4u.acquire_cred_impersonate_name(self, name,
lifetime, mechs,
usage)
return type(self)(base=res.creds)
def inquire(self, name=True, lifetime=True, usage=True, mechs=True):
"""Inspect these credentials for information
This method inspects these credentials for information about them.
Args:
name (bool): get the name associated with the credentials
lifetime (bool): get the remaining lifetime for the credentials
usage (bool): get the usage for the credentials
mechs (bool): get the mechanisms associated with the credentials
Returns:
InquireCredResult: the information about the credentials,
with None used when the corresponding argument was False
Raises:
MissingCredentialsError
InvalidCredentialsError
ExpiredCredentialsError
"""
res = rcreds.inquire_cred(self, name, lifetime, usage, mechs)
if res.name is not None:
res_name = names.Name(res.name)
else:
res_name = None
return tuples.InquireCredResult(res_name, res.lifetime,
res.usage, res.mechs)
def inquire_by_mech(self, mech, name=True, init_lifetime=True,
accept_lifetime=True, usage=True):
"""Inspect these credentials for per-mechanism information
This method inspects these credentials for per-mechanism information
about them.
Args:
mech (OID): the mechanism for which to retrive the information
name (bool): get the name associated with the credentials
init_lifetime (bool): get the remaining initiate lifetime for
the credentials
accept_lifetime (bool): get the remaining accept lifetime for
the credentials
usage (bool): get the usage for the credentials
Returns:
InquireCredByMechResult: the information about the credentials,
with None used when the corresponding argument was False
"""
res = rcreds.inquire_cred_by_mech(self, mech, name, init_lifetime,
accept_lifetime, usage)
if res.name is not None:
res_name = names.Name(res.name)
else:
res_name = None
return tuples.InquireCredByMechResult(res_name,
res.init_lifetime,
res.accept_lifetime,
res.usage)
def add(self, name, mech, usage='both',
init_lifetime=None, accept_lifetime=None, impersonator=None,
store=None):
"""Acquire more credentials to add to the current set
This method works like :meth:`acquire`, except that it adds the
acquired credentials for a single mechanism to a copy of the current
set, instead of creating a new set for multiple mechanisms.
Unlike :meth:`acquire`, you cannot pass None desired name or
mechanism.
If the `impersonator` argument is used, the credentials will
impersonate the given name using the impersonator credentials
(:requires-ext:`s4u`).
If the `store` argument is used, the credentials will be acquired
from the given credential store (:requires-ext:`cred_store`).
Otherwise, the credentials are acquired from the default store.
The credential store information is a dictionary containing
mechanisms-specific keys and values pointing to a credential store
or stores.
Note that the `store` argument is not compatible with the
`impersonator` argument.
Args:
name (Name): the name associated with the
credentials
mech (OID): the desired :class:`MechType` to be used with the
credentials
usage (str): the usage for the credentials -- either 'both',
'initiate', or 'accept'
init_lifetime (int): the desired initiate lifetime of the
credentials, or None for indefinite
accept_lifetime (int): the desired accept lifetime of the
credentials, or None for indefinite
impersonator (Credentials): the credentials to use to impersonate
the given name, or None to not acquire normally
(:requires-ext:`s4u`)
store (dict): the credential store information pointing to the
credential store from which to acquire the credentials,
or None for the default store (:requires-ext:`cred_store`)
Returns:
Credentials: the credentials set containing the current credentials
and the newly acquired ones.
Raises:
BadMechanismError
BadNameTypeError
BadNameError
DuplicateCredentialsElementError
ExpiredCredentialsError
MissingCredentialsError
"""
if store | |
a side effect, builds the _merge_indices specs for generating the merged data.
@see hxl.filters.AbstractBaseFilter.filter_columns
"""
new_columns = list(self.source.columns)
"""The new column list to return."""
merge_column_index = len(self.source.columns)
"""Target index for merging into the output dataset"""
# Check every pattern
for pattern in self.merge_tags:
# Check the pattern against every column
for index, column in enumerate(self.merge_source.columns):
seen_replacement = False
"""We can replace inline exactly once for every pattern."""
if pattern.match(column):
# Replace inside existing columns, if conditions are met
if self.replace and not seen_replacement and pattern.find_column(self.source.columns):
# TODO: check for closest match
# TODO: allow for multiple replacements per pattern
self._merge_indices.append([index, pattern.find_column_index(self.source.columns), self.overwrite])
seen_replacement = True
# Replace into a new column on the right
else:
new_columns.append(column)
self._merge_indices.append([index, merge_column_index, True])
merge_column_index += 1
return new_columns
def filter_row(self, row):
"""Set up a merged data row, replacing existing values if requested.
Uses the _merge_indices map created by filter_columns.
@param row: the data row to filter.
@returns: a list of filtered values for the row.
@see hxl.filters.AbstractStreamingFilter.filter_row
"""
# First, check if we already have the merge map, and read it if not
if self._merge_values is None:
self._merge_values = self._read_merge()
# Make an initial array of the correct length
values = copy.copy(row.values)
values += ([''] * (len(self.columns) - len(row.values)))
# Look up the merge values, based on the keys
for key in self._make_keys(row):
merge_values = self._merge_values.get(key)
if merge_values:
for i, spec in enumerate(self._merge_indices):
if spec[2] or hxl.datatypes.is_empty(values[spec[1]]):
values[spec[1]] = merge_values[i]
return values
def _make_keys(self, row):
"""Return all possible key-value combinations for the row as tuples.
@param row: the row from which to generate the key
"""
candidate_values = []
for pattern in self.keys:
candidate_values.append(hxl.datatypes.normalise_string(value) for value in row.get_all(pattern, default=''))
return [tuple(value) for value in list_product(candidate_values)]
def _read_merge(self):
"""Read the second (merging) dataset into memory.
Stores only the values necessary for the merge.
Uses *last* matching row for each key (top to bottom).
@returns: a map of merge values
"""
self.columns # make sure we've created the _merge_indices map
merge_values = {}
"""Map of keys to merge values from the merge source."""
for row in self.merge_source:
if hxl.model.RowQuery.match_list(row, self.queries):
values = []
# Save only the values we need
for spec in self._merge_indices:
try:
values.append(row.values[spec[0]])
except IndexError:
values.append('')
# Generate a key tuple and add to the map
for key in self._make_keys(row):
merge_values[key] = values
return merge_values
@staticmethod
def _load(source, spec):
"""Create a merge filter from a dict spec.
@param source: the upstream data source
@param spec: the JSON-like filter specification
@returns: a L{MergeDataFilter} object
"""
return MergeDataFilter(
source=source,
merge_source=req_arg(spec, 'merge_source'),
keys=req_arg(spec, 'keys'),
tags=req_arg(spec, 'tags'),
replace=opt_arg(spec, 'replace', False),
overwrite=opt_arg(spec, 'overwrite', False),
queries=opt_arg(spec, 'queries', [])
)
class RenameFilter(AbstractStreamingFilter):
"""
Composable filter class to rename columns in a HXL dataset.
This is the class supporting the hxlrename command-line utility.
Usage:
<pre>
hxl.data(url).rename_columns('#foo:New header#bar')
</pre>
"""
def __init__(self, source, rename=[]):
"""
Constructor
@param source: the Dataset for the data.
@param rename_map: map of tags to rename
"""
super().__init__(source)
if isinstance(rename, six.string_types):
rename = [rename]
self.rename = [RenameFilter.parse_rename(spec) for spec in rename]
def filter_columns(self):
"""Rename requested columns."""
return [self._rename_column(column) for column in self.source.columns]
def filter_row(self, row):
"""@returns: a deep copy of the row's values"""
return copy.copy(row.values)
def _rename_column(self, column):
"""@returns: a copy of the column object, with a new name if needed"""
for spec in self.rename:
norm = hxl.datatypes.normalise_string
if spec[0].match(column) and (not spec[2] or norm(spec[2]) == norm(column.header)):
new_column = copy.deepcopy(spec[1])
if new_column.header is None:
new_column.header = column.header
return new_column
return copy.deepcopy(column)
RENAME_PATTERN = r'^\s*(?:([^#]*)#)?({token}(?:\s*[+-]{token})*)\s*:\s*(?:([^#]*)#)?({token}(?:\s*[+]{token})*)\s*$'.format(
token=hxl.datatypes.TOKEN_PATTERN
)
"""Regular expression for parsing a rename pattern"""
@staticmethod
def parse_rename(s):
"""Parse a rename specification from the parameters.
@param s: the specification to parse
@returns: a tuple with the old pattern to match and new column spec
@exception HXLFilterException: if the spec is not parseable
"""
if isinstance(s, six.string_types):
result = re.match(RenameFilter.RENAME_PATTERN, s)
if result:
header = result.group(1)
pattern = hxl.model.TagPattern.parse(result.group(2))
column = hxl.model.Column.parse('#' + result.group(4), header=result.group(3), use_exception=True)
return (pattern, column, header)
else:
raise HXLFilterException("Bad rename expression: " + s)
else:
return s
@staticmethod
def _load(source, spec):
"""Create a rename filter from a dict spec.
@param source: the upstream data source
@param spec: the JSON-like filter specification
@returns: a L{RenameFilter} object
"""
return RenameFilter(
source=source,
rename=req_arg(spec, 'specs')
)
class JSONPathFilter(AbstractStreamingFilter):
"""Extract values from a JSON string expression using JSONPath
See http://goessner.net/articles/JsonPath/
Optionally restrict to specific columns and/or rows
"""
def __init__(self, source, path, patterns=None, queries=[], use_json=True):
"""Constructor
@param source: the upstream data source
@param path: a JSONPath expression for extracting data
@param patterns: a tag pattern or list of patterns for the columns to use (default to all)
@param queries: a predicate or list of predicates for the rows to consider.
@param use_json: if True, serialise multiple values as JSON (default); otherwise, separate with " | "
"""
super().__init__(source)
self.path = jsonpath_ng.ext.parse(path)
self.patterns = hxl.model.TagPattern.parse_list(patterns)
self.queries = self._setup_queries(queries)
self.use_json = use_json
self._indices = None
def filter_row(self, row):
if self._indices is None:
self._indices = self._get_indices(self.patterns)
values = list(row.values)
if hxl.model.RowQuery.match_list(row, self.queries):
for i in self._indices:
try:
expr = json.loads(values[i])
results = [match.value for match in self.path.find(expr)]
if len(results) == 0:
values[i] = ''
elif len(results) == 1:
values[i] = hxl.datatypes.flatten(results[0], self.use_json)
else:
values[i] = hxl.datatypes.flatten(results, self.use_json)
except (ValueError, TypeError,) as e:
logger.exception(e)
logger.warning("Skipping invalid JSON expression '%s'", values[i])
return values
@staticmethod
def _load(source, spec):
"""Create a JSONPath filter from a dict spec.
@param source: the upstream data source
@param spec: the JSON-like filter specification
@returns: a L{RenameFilter} object
"""
return JSONPathFilter(
source=source,
path=req_arg(spec, 'path'),
patterns=opt_arg(spec, 'patterns'),
queries=opt_arg(spec, 'queries')
)
class FillDataFilter(AbstractStreamingFilter):
"""Fill empty cells in a dataset.
By default, fill all empty cells with the closest non-empty value in a previous row.
Optionally restrict to specific columns and/or rows.
"""
def __init__(self, source, patterns=None, queries=[]):
"""Constructor
@param source: the source dataset
@param patterns: a tag pattern or list of patterns for the columns to fill (default to all)
@param queries: restrict filling to rows matching one of these queries (default: fill all rows).
"""
super().__init__(source)
self.patterns = hxl.model.TagPattern.parse_list(patterns)
self.queries = self._setup_queries(queries)
self._saved = {}
self._indices = None
def filter_row(self, row):
"""@returns: row values with some empty values possibly filled in"""
values = list(row.values)
# Fill if there are no row queries, or this row matches one
if self._indices is None:
self._indices = self._get_indices(self.patterns)
for i in self._indices:
if values[i]:
self._saved[i] = values[i]
elif (not self.queries) or (hxl.model.RowQuery.match_list(row, self.queries)):
values[i] = self._saved[i] if self._saved.get(i) else ''
return values
@staticmethod
def _load(source, spec):
"""Create a fill-data filter from a dict spec.
@param source: the upstream data source
@param spec: the JSON-like filter specification
@returns: a L{FillDataFilter} object
"""
return FillDataFilter(
source=source,
patterns=opt_arg(spec, 'patterns'),
queries=opt_arg(spec, 'queries'),
)
class ReplaceDataFilter(AbstractStreamingFilter):
"""
Composable filter class to replace values in a HXL dataset.
This is the class supporting the hxlreplace console script.
Usage:
<pre>
hxl.data(url).replace_data('foo', 'bar', '#activity')
</pre>
"""
def __init__(self, source, replacements, queries=[]):
"""
Constructor
@param source: the HXL data source
@param original: a string or regular expression to replace (string must match the whole value, not just part)
@param replacements: list of replacement objects
@param queries: optional list of filter queries for rows where replacements should be applied.
"""
super(ReplaceDataFilter, self).__init__(source)
self.replacements = replacements
if isinstance(self.replacements, ReplaceDataFilter.Replacement):
self.replacements = [self.replacements]
self.queries = self._setup_queries(queries)
def filter_row(self, row):
"""@returns: the row values with replacements"""
if hxl.model.RowQuery.match_list(row, self.queries):
values = copy.copy(row.values)
for index, value in enumerate(values):
for replacement in self.replacements:
value = replacement.sub(row.columns[index], value)
values[index] = value
return values
else:
return row.values
class Replacement:
"""Replacement specification."""
def __init__(self, original, replacement, patterns=None, is_regex=False):
"""
@param original: a string (case- and space-insensitive) or regular expression (sensitive) to replace
@param replacement: the replacement string or regular expression substitution
@param patterns: (optional) a list of tag patterns to limit the replacement to specific columns
@param is_regex: (optional) True to use regular-expression processing (defaults to False)
"""
self.original = original
if | |
new data cube with the same dimensions. The dimension properties (name, type, labels, reference
system and resolution) remain unchanged, except for the resolution and dimension labels of the given
temporal dimension. The specified temporal dimension has the following dimension labels (`YYYY` = four-
digit year, `MM` = two-digit month, `DD` two-digit day of month): * `hour`: `YYYY-MM-DD-00` - `YYYY-MM-
DD-23` * `day`: `YYYY-001` - `YYYY-365` * `week`: `YYYY-01` - `YYYY-52` * `dekad`: `YYYY-00` - `YYYY-36` *
`month`: `YYYY-01` - `YYYY-12` * `season`: `YYYY-djf` (December - February), `YYYY-mam` (March - May),
`YYYY-jja` (June - August), `YYYY-son` (September - November). * `tropical-season`: `YYYY-ndjfma` (November
- April), `YYYY-mjjaso` (May - October). * `year`: `YYYY` * `decade`: `YYY0` * `decade-ad`: `YYY1`
"""
return _process('aggregate_temporal_period', data=data, period=period, reducer=reducer, dimension=dimension, context=context)
def all(data, ignore_nodata=UNSET) -> ProcessBuilder:
"""
Are all of the values true?
:param data: A set of boolean values.
:param ignore_nodata: Indicates whether no-data values are ignored or not and ignores them by default.
:return: Boolean result of the logical operation.
"""
return _process('all', data=data, ignore_nodata=ignore_nodata)
def and_(x, y) -> ProcessBuilder:
"""
Logical AND
:param x: A boolean value.
:param y: A boolean value.
:return: Boolean result of the logical AND.
"""
return _process('and', x=x, y=y)
def anomaly(data, normals, period) -> ProcessBuilder:
"""
Compute anomalies
:param data: A data cube with exactly one temporal dimension and the following dimension labels for the
given period (`YYYY` = four-digit year, `MM` = two-digit month, `DD` two-digit day of month): * `hour`:
`YYYY-MM-DD-00` - `YYYY-MM-DD-23` * `day`: `YYYY-001` - `YYYY-365` * `week`: `YYYY-01` - `YYYY-52` *
`dekad`: `YYYY-00` - `YYYY-36` * `month`: `YYYY-01` - `YYYY-12` * `season`: `YYYY-djf` (December -
February), `YYYY-mam` (March - May), `YYYY-jja` (June - August), `YYYY-son` (September - November). *
`tropical-season`: `YYYY-ndjfma` (November - April), `YYYY-mjjaso` (May - October). * `year`: `YYYY` *
`decade`: `YYY0` * `decade-ad`: `YYY1` * `single-period` / `climatology-period`: Any
``aggregate_temporal_period()`` can compute such a data cube.
:param normals: A data cube with normals, e.g. daily, monthly or yearly values computed from a process such
as ``climatological_normal()``. Must contain exactly one temporal dimension with the following dimension
labels for the given period: * `hour`: `00` - `23` * `day`: `001` - `365` * `week`: `01` - `52` * `dekad`:
`00` - `36` * `month`: `01` - `12` * `season`: `djf` (December - February), `mam` (March - May), `jja`
(June - August), `son` (September - November) * `tropical-season`: `ndjfma` (November - April), `mjjaso`
(May - October) * `year`: Four-digit year numbers * `decade`: Four-digit year numbers, the last digit being
a `0` * `decade-ad`: Four-digit year numbers, the last digit being a `1` * `single-period` / `climatology-
period`: A single dimension label with any name is expected.
:param period: Specifies the time intervals available in the normals data cube. The following options are
available: * `hour`: Hour of the day * `day`: Day of the year * `week`: Week of the year * `dekad`: Ten
day periods, counted per year with three periods per month (day 1 - 10, 11 - 20 and 21 - end of month). The
third dekad of the month can range from 8 to 11 days. For example, the fourth dekad is Feb, 1 - Feb, 10
each year. * `month`: Month of the year * `season`: Three month periods of the calendar seasons (December -
February, March - May, June - August, September - November). * `tropical-season`: Six month periods of the
tropical seasons (November - April, May - October). * `year`: Proleptic years * `decade`: Ten year periods
([0-to-9 decade](https://en.wikipedia.org/wiki/Decade#0-to-9_decade)), from a year ending in a 0 to the
next year ending in a 9. * `decade-ad`: Ten year periods ([1-to-0
decade](https://en.wikipedia.org/wiki/Decade#1-to-0_decade)) better aligned with the anno Domini (AD)
calendar era, from a year ending in a 1 to the next year ending in a 0. * `single-period` / `climatology-
period`: A single period of arbitrary length
:return: A data cube with the same dimensions. The dimension properties (name, type, labels, reference
system and resolution) remain unchanged.
"""
return _process('anomaly', data=data, normals=normals, period=period)
def any(data, ignore_nodata=UNSET) -> ProcessBuilder:
"""
Is at least one value true?
:param data: A set of boolean values.
:param ignore_nodata: Indicates whether no-data values are ignored or not and ignores them by default.
:return: Boolean result of the logical operation.
"""
return _process('any', data=data, ignore_nodata=ignore_nodata)
def apply(data, process, context=UNSET) -> ProcessBuilder:
"""
Apply a process to each pixel
:param data: A data cube.
:param process: A process that accepts and returns a single value and is applied on each individual value
in the data cube. The process may consist of multiple sub-processes and could, for example, consist of
processes such as ``abs()`` or ``linear_scale_range()``.
:param context: Additional data to be passed to the process.
:return: A data cube with the newly computed values and the same dimensions. The dimension properties
(name, type, labels, reference system and resolution) remain unchanged.
"""
return _process('apply', data=data, process=process, context=context)
def apply_dimension(data, process, dimension, target_dimension=UNSET, context=UNSET) -> ProcessBuilder:
"""
Apply a process to pixels along a dimension
:param data: A data cube.
:param process: Process to be applied on all pixel values. The specified process needs to accept an array
and must return an array with at least one element. A process may consist of multiple sub-processes.
:param dimension: The name of the source dimension to apply the process on. Fails with a
`DimensionNotAvailable` exception if the specified dimension does not exist.
:param target_dimension: The name of the target dimension or `null` (the default) to use the source
dimension specified in the parameter `dimension`. By specifying a target dimension, the source dimension
is removed. The target dimension with the specified name and the type `other` (see ``add_dimension()``) is
created, if it doesn't exist yet.
:param context: Additional data to be passed to the process.
:return: A data cube with the newly computed values. All dimensions stay the same, except for the
dimensions specified in corresponding parameters. There are three cases how the dimensions can change: 1.
The source dimension is the target dimension: - The (number of) dimensions remain unchanged as the
source dimension is the target dimension. - The source dimension properties name and type remain
unchanged. - The dimension labels, the reference system and the resolution are preserved only if the
number of pixel values in the source dimension is equal to the number of values computed by the process.
Otherwise, all other dimension properties change as defined in the list below. 2. The source dimension is
not the target dimension and the latter exists: - The number of dimensions decreases by one as the
source dimension is dropped. - The target dimension properties name and type remain unchanged. All other
dimension properties change as defined in the list below. 3. The source dimension is not the target
dimension and the latter does not exist: - The number of dimensions remain unchanged, but the source
dimension is replaced with the target dimension. - The target dimension has the specified name and the
type other. All other dimension properties are set as defined in the list below. Unless otherwise stated
above, for the given (target) dimension the following applies: - the number of dimension labels is equal
to the number of values computed by the process, - the dimension labels are incrementing integers starting
from zero, - the resolution changes, and - the reference system is undefined.
"""
return _process('apply_dimension', data=data, process=process, dimension=dimension, target_dimension=target_dimension, context=context)
def apply_kernel(data, kernel, factor=UNSET, border=UNSET, replace_invalid=UNSET) -> ProcessBuilder:
"""
Apply a spatial convolution with a kernel
:param data: A data cube.
:param kernel: Kernel as a two-dimensional array of weights. The inner level of the nested array aligns
with the `x` axis and the outer level aligns with the `y` axis. Each level of the kernel must | |
<filename>similarity.py
'''
Table of Contents
Functions and Interdependencies:
proj
orthogonalize
- proj
OLS
EV
pairwise_similarity
best_permutation
- pairwise_similarity
self_similarity_pairwise
- best_permutation
'''
import numpy as np
from numpy.linalg import norm, qr
from scipy.stats import zscore
import scipy.optimize
import copy
import sklearn.decomposition
from opt_einsum import contract
from numba import njit, prange, jit
import torch
from time import time
def proj(v1, v2):
'''
Projects one or more vectors (columns of v1) onto one or more vectors (v2)
RH 2021
Args:
v1 (ndarray):
vector set 1. Either a single vector or a 2-D array where the columns
are the vectors
v2 (ndarray):
vector set 2. Either a single vector or a 2-D array where the columns
are the vectors
Returns:
proj_vec (ndarray):
vector set 1 projected onto vector set 2.
shape: (v1.shape[0], v1.shape[1], v2.shape[1])
proj_score (ndarray or scalar):
projection scores. shape: (v1.shape[1], v2.shape[1])
'''
if v1.ndim < 2:
v1 = v1[:,None]
if v2.ndim < 2:
v2 = v2[:,None]
u = v2 / norm(v2, axis=0)
proj_score = v1.T @ u
# this einsum can probably be optimized better
# proj_vec = np.einsum('ik,jk->ijk', u, proj_score)
proj_vec = contract('ik,jk->ijk', u, proj_score)
return proj_vec , proj_score
def vector_angle(v1, v2, deg_or_rad='deg'):
'''
Calculates the angle between two vectors.
RH 2021
Args:
v1 (ndarray):
vector 1
v2 (ndarray):
vector 2
deg_or_rad (str):
'deg' for degrees, 'rad' for radians
Returns:
angle (scalar):
angle between v1 and v2
'''
if type(v1) is np.ndarray:
arccos = np.arccos
norm = np.linalg.norm
rad2deg = np.rad2deg
elif type(v1) is torch.Tensor:
arccos = torch.acos
norm = torch.linalg.norm
rad2deg = torch.rad2deg
if deg_or_rad == 'rad':
return arccos((v1@v2) / (norm(v1) * norm(v2)))
if deg_or_rad == 'deg':
return rad2deg(arccos((v1@v2) / (norm(v1) * norm(v2))))
def orthogonalize(v1, v2):
'''
Orthogonalizes one or more vectors (columns of v1) relative to another set
of vectors (v2). Subtracts the projection of v1 onto v2 off of v1.
Update: I found a scenario under which numerical instability can cause and
overestimation in the EVR (and how much gets orthogonalized away). Be
careful when v2 >> v1 in magnitude and/or rank. Use OLS + EV instead for
those cases.
RH 2021
Args:
v1 (ndarray):
vector set 1. Either a single vector or a 2-D array where the columns
are the vectors
v2 (ndarray):
vector set 2. Either a single vector or a 2-D array where the columns
are the vectors
Returns:
v1_orth (ndarray):
vector set 1 with the projections onto vector set 2 subtracted off.
Same size as v1.
v2_PCs (ndarray):
PCA is performed on v2 to orthogonalize it, so these are the PCs
EVR (ndarray):
Explained Variance Ratio for each column of v1.
Amount of variance that all the vectors in v2 can explain for each
vector in v1.
When v1 is z-scored, EVR is equivalent to pearsons R^2;
as in pairwise_similarity(OLS(v2, v1)[1] , v1)**2
EVR_total (scalar):
total amount of variance explained in v1 by v2
'''
if v1.ndim < 2:
v1 = v1[:,None]
if v2.ndim < 2:
v2 = v2[:,None]
# I'm pretty sure using PCA is fine for this, but it might be a good idea
# to look into QR decompositions, basic SVD, and whether mean subtracting
# actually matters to the outcome. Pretty sure this is fine though.
decomp = sklearn.decomposition.PCA(n_components=v2.shape[1])
v2_PCs = decomp.fit_transform(v2)
# Serial orthogonalization. I think doing it serially isn't necessary
# since we are orthogonalizing the v2 vectors. This method might have
# some numerical instability issues given it's similarity to a
# Gram-Schmidt process, but maybe less because v2 is orthogonal.
# I'll leave optimization to a future me.
v1_orth = copy.deepcopy(v1)
for ii in range(v2.shape[1]):
proj_vec = proj(v1_orth , v2_PCs[:,ii])[0]
v1_orth = np.squeeze(v1_orth) - np.squeeze(proj_vec)
EVR = 1 - (np.var(v1_orth, axis=0) / np.var(v1, axis=0))
EVR_total = 1 - ( np.sum(np.var(v1_orth,axis=0),axis=0) / np.sum(np.var(v1,axis=0),axis=0) )
return v1_orth, v2_PCs, EVR, EVR_total
@njit
def pair_orth_helper(v1, v2):
"""
Helper function for main pairwise_orthogonalization
function. Performs the pairwise orthogonalization
by subtracting off v2 from v1. Uses numba to speed
up the computation.
v1 = v1 - proj(v1 onto v2)
RH 2021
Args:
v1 (ndarray):
Vector set 1. Columns are vectors.
v2 (ndarray):
Vector set 2. Columns are vectors.
Returns:
v1_orth (ndarray):
v1 - proj(v1 onto v2)
"""
return v1 - (np.diag(np.dot(v1.T, v2)) / np.diag(np.dot(v2.T, v2))) * v2
def pairwise_orthogonalization(v1, v2, center:bool=False):
"""
Orthogonalizes columns of v2 off of the columns of v1
and returns the orthogonalized v1 and the explained
variance ratio of v2 off of v1.
v1: y_true, v2: y_pred
Since it's just pairwise, there should not be any
numerical instability issues.
RH 2021
Args:
v1 (ndarray):
y_true
Vector set 1. Either a single vector or a 2-D
array where the columns are the vectors.
v2 (ndarray):
y_pred
Vector set 2. Either a single vector or a 2-D
array where the columns are the vectors.
center (bool):
Whether to center the vectors.
Centering prevents negative EVR values.
Returns:
v1_orth (ndarray):
Vector set 1 with the projections onto vector
set 2 subtracted off.
Same size as v1.
EVR (ndarray):
Explained Variance Ratio for each column of v1.
Amount of variance that all the vectors in v2
can explain for each vector in v1.
EVR_total_weighted (scalar):
Average amount of variance explained in v1 by v2
weighted by the variance of each column of v1.
EVR_total_unweighted (scalar):
Average amount of variance explained in v1 by v2
"""
assert v1.ndim == v2.ndim
if v1.ndim==1:
v1 = v1[:,None]
v2 = v2[:,None]
assert v1.shape[1] == v2.shape[1]
assert v1.shape[0] == v2.shape[0]
if center:
v1 = v1 - np.mean(v1, axis=0)
v2 = v2 - np.mean(v2, axis=0)
v1_orth = pair_orth_helper(v1, v2)
v1_var = np.var(v1, axis=0)
EVR = 1 - (np.var(v1_orth, axis=0) / v1_var)
EVR_total_weighted = np.sum(v1_var * EVR) / np.sum(v1_var)
EVR_total_unweighted = np.mean(EVR)
return v1_orth, EVR, EVR_total_weighted, EVR_total_unweighted
@torch.jit.script
def pairwise_orthogonalization_torch(v1, v2, center:bool=False):
"""
Orthogonalizes columns of v2 off of the columns of v1
and returns the orthogonalized v1 and the explained
variance ratio of v2 off of v1.
v1: y_true, v2: y_pred
Since it's just pairwise, there should not be any
numerical instability issues.
Same as pairwise_orthogonalization, but with
torch.jit.script instead of njit.
RH 2021
Args:
v1 (ndarray):
y_true
Vector set 1. Either a single vector or a 2-D
array where the columns are the vectors.
v2 (ndarray):
y_pred
Vector set 2. Either a single vector or a 2-D
array where the columns are the vectors.
center (bool):
Whether to center the vectors.
Centering prevents negative EVR values.
Returns:
v1_orth (ndarray):
Vector set 1 with the projections onto vector
set 2 subtracted off.
Same size as v1.
EVR (ndarray):
Explained Variance Ratio for each column of v1.
Amount of variance that all the vectors in v2
can explain for each vector in v1.
EVR_total_weighted (scalar):
Average amount of variance explained in v1 by v2
weighted by the variance of each column of v1.
EVR_total_unweighted (scalar):
Average amount of variance explained in v1 by v2
"""
assert v1.ndim == v2.ndim
if v1.ndim==1:
v1 = v1[:,None]
v2 = v2[:,None]
assert v1.shape[1] == v2.shape[1]
assert v1.shape[0] == v2.shape[0]
if center:
v1 = v1 - torch.mean(v1, dim=0)
v2 = v2 - torch.mean(v2, dim=0)
# v1_orth = v1 - (torch.diag(torch.matmul(v1.T, v2)) / torch.diag(torch.matmul(v2.T, v2)))*v2
v1_orth = v1 - (torch.sum(v1 * v2, dim=0) / torch.sum(v2 * v2, dim=0) )*v2
v1_var = torch.var(v1, dim=0)
EVR = 1 - (torch.var(v1_orth, dim=0) / v1_var)
EVR_total_weighted = torch.sum(v1_var * EVR) / torch.sum(v1_var)
EVR_total_unweighted = torch.mean(EVR)
return v1_orth.squeeze(), EVR, EVR_total_weighted, EVR_total_unweighted
def OLS(X,y):
'''
Ordinary Least Squares regression.
This method works great and is fast under most conditions.
It tends to do poorly when X.shape[1] is small or too big
(overfitting can occur). Using OLS + EV is probably
better than the 'orthogonalize' function.
RH 2021
Args:
X (ndarray):
array where columns are | |
arraylen; index++) {
if (!(data1[index] %(compare_ops)s data2[index])) {
return 0;
}
}
return 1;
}
#endif
/*--------------------------------------------------------------------------- */
"""
# The actual compare operations using SIMD operations for ARMv8 NEON 64 bit.
ops_simdsupport_armv8 = """
/*--------------------------------------------------------------------------- */
/* ARMv8 AARCH64 64 bit SIMD.
The following series of functions reflect the different parameter options possible.
arraylen = The length of the data arrays.
data1 = The first data array.
data2 = The second data array.
param = The parameter to be applied to each array element.
*/
// param_arr_num
#if defined(AF_HASSIMD_ARM_AARCH64)
char %(funclabel)s_%(funcmodifier)s_1_simd(Py_ssize_t arraylen, %(arraytype)s *data1, %(arraytype)s param) {
// array index counter.
Py_ssize_t index;
// SIMD related variables.
Py_ssize_t alignedlength;
unsigned int y;
%(simdattr)s datasliceleft, datasliceright;
%(simdrsltattr)s resultslice;
%(arraytype)s compvals[%(simdwidth)s];
uint64x2_t veccombine;
uint64_t highresult, lowresult;
// Initialise the comparison values.
for (y = 0; y < %(simdwidth)s; y++) {
compvals[y] = param;
}
datasliceright = %(vldinstr)s( compvals);
// Calculate array lengths for arrays whose lengths which are not even
// multipes of the SIMD slice length.
alignedlength = arraylen - (arraylen %% %(simdwidth)s);
// Perform the main operation using SIMD instructions.
for (index = 0; index < alignedlength; index += %(simdwidth)s) {
datasliceleft = %(vldinstr)s( &data1[index]);
// The actual SIMD operation.
resultslice = %(SIMD_ARM_comp)s(datasliceleft, datasliceright);
// Combine the result to two 64 bit vectors.
veccombine = %(veccombine)s(resultslice);
// Get the high and low lanes of the combined vector.
lowresult = vgetq_lane_u64(veccombine, 0);
highresult = vgetq_lane_u64(veccombine, 1);
// Compare the results of the SIMD operation.
if ((lowresult != %(resultmask)s) || (highresult != %(resultmask)s)) {
return 0;
}
}
// Get the max value within the left over elements at the end of the array.
for (index = alignedlength; index < arraylen; index++) {
if (!(data1[index] %(compare_ops)s param)) {
return 0;
}
}
return 1;
}
// param_num_arr
char %(funclabel)s_%(funcmodifier)s_3_simd(Py_ssize_t arraylen, %(arraytype)s param, %(arraytype)s *data2) {
// array index counter.
Py_ssize_t index;
// SIMD related variables.
Py_ssize_t alignedlength;
unsigned int y;
%(simdattr)s datasliceleft, datasliceright;
%(simdrsltattr)s resultslice;
%(arraytype)s compvals[%(simdwidth)s];
uint64x2_t veccombine;
uint64_t highresult, lowresult;
// Initialise the comparison values.
for (y = 0; y < %(simdwidth)s; y++) {
compvals[y] = param;
}
datasliceleft = %(vldinstr)s( compvals);
// Calculate array lengths for arrays whose lengths which are not even
// multipes of the SIMD slice length.
alignedlength = arraylen - (arraylen %% %(simdwidth)s);
// Perform the main operation using SIMD instructions.
for (index = 0; index < alignedlength; index += %(simdwidth)s) {
datasliceright = %(vldinstr)s( &data2[index]);
// The actual SIMD operation.
resultslice = %(SIMD_ARM_comp)s(datasliceleft, datasliceright);
// Combine the result to two 64 bit vectors.
veccombine = %(veccombine)s(resultslice);
// Get the high and low lanes of the combined vector.
lowresult = vgetq_lane_u64(veccombine, 0);
highresult = vgetq_lane_u64(veccombine, 1);
// Compare the results of the SIMD operation.
if ((lowresult != %(resultmask)s) || (highresult != %(resultmask)s)) {
return 0;
}
}
// Get the max value within the left over elements at the end of the array.
for (index = alignedlength; index < arraylen; index++) {
if (!(param %(compare_ops)s data2[index])) {
return 0;
}
}
return 1;
}
// param_arr_arr
char %(funclabel)s_%(funcmodifier)s_5_simd(Py_ssize_t arraylen, %(arraytype)s *data1, %(arraytype)s *data2) {
// array index counter.
Py_ssize_t index;
// SIMD related variables.
Py_ssize_t alignedlength;
%(simdattr)s datasliceleft, datasliceright;
%(simdrsltattr)s resultslice;
uint64x2_t veccombine;
uint64_t highresult, lowresult;
// Calculate array lengths for arrays whose lengths which are not even
// multipes of the SIMD slice length.
alignedlength = arraylen - (arraylen %% %(simdwidth)s);
// Perform the main operation using SIMD instructions.
for (index = 0; index < alignedlength; index += %(simdwidth)s) {
datasliceleft = %(vldinstr)s( &data1[index]);
datasliceright = %(vldinstr)s( &data2[index]);
// The actual SIMD operation.
resultslice = %(SIMD_ARM_comp)s(datasliceleft, datasliceright);
// Combine the result to two 64 bit vectors.
veccombine = %(veccombine)s(resultslice);
// Get the high and low lanes of the combined vector.
lowresult = vgetq_lane_u64(veccombine, 0);
highresult = vgetq_lane_u64(veccombine, 1);
// Compare the results of the SIMD operation.
if ((lowresult != %(resultmask)s) || (highresult != %(resultmask)s)) {
return 0;
}
}
// Get the max value within the left over elements at the end of the array.
for (index = alignedlength; index < arraylen; index++) {
if (!(data1[index] %(compare_ops)s data2[index])) {
return 0;
}
}
return 1;
}
#endif
/*--------------------------------------------------------------------------- */
"""
# ==============================================================================
# This is the set of function calls used to call each operator function.
compcall = """
// %(funcmodifier)s
case '%(arraycode)s' : {
switch (arraydata.paramcat) {
case param_arr_num : {
resultcode = %(funclabel)s_%(funcmodifier)s_1(arraydata.arraylength, arraydata.nosimd, arraydata.array1.%(arraycode)s, arraydata.param.%(arraycode)s);
break;
}
case param_num_arr : {
resultcode = %(funclabel)s_%(funcmodifier)s_3(arraydata.arraylength, arraydata.nosimd, arraydata.param.%(arraycode)s, arraydata.array2.%(arraycode)s);
break;
}
case param_arr_arr : {
resultcode = %(funclabel)s_%(funcmodifier)s_5(arraydata.arraylength, arraydata.nosimd, arraydata.array1.%(arraycode)s, arraydata.array2.%(arraycode)s);
break;
}
}
break;
}
"""
# ==============================================================================
# Calls to parameter parseing and the implementing functions.
comp_params = """
/*--------------------------------------------------------------------------- */
/* The wrapper to the underlying C function */
static PyObject *py_%(funclabel)s(PyObject *self, PyObject *args, PyObject *keywds) {
// The error code returned by the function.
char resultcode = 0;
// This is used to hold the parsed parameters.
struct args_params_comp arraydata = ARGSINIT_COMP;
// -----------------------------------------------------
// Get the parameters passed from Python.
arraydata = getparams_comp(self, args, keywds, "%(funclabel)s");
// If there was an error, we count on the parameter parsing function to
// release the buffers if this was necessary.
if (arraydata.error) {
return NULL;
}
// Call the C function.
switch(arraydata.arraytype) {
%(opscall)s
// Wrong array type code.
default: {
releasebuffers_comp(arraydata);
ErrMsgTypeExpectFloat();
return NULL;
break;
}
}
// Release the buffers.
releasebuffers_comp(arraydata);
// Return whether compare was OK.
if (resultcode) {
Py_RETURN_TRUE;
} else {
Py_RETURN_FALSE;
}
}
/*--------------------------------------------------------------------------- */
/* The module doc string */
PyDoc_STRVAR(%(funclabel)s__doc__,
"%(funclabel)s \\n\\
_____________________________ \\n\\
\\n\\
Calculate %(funclabel)s over the values in an array. \\n\\
\\n\\
====================== ============================================== \\n\\
Equivalent to: all([x %(compare_ops)s param for x in array1]) \\n\\
or all([param %(compare_ops)s x for x in array1]) \\n\\
or all([x %(compare_ops)s y for x,y in zip(array1, array2)]) \\n\\
====================== ============================================== \\n\\
\\n\\
====================== ============================================== \\n\\
Array types supported: %(supportedarrays)s \\n\\
====================== ============================================== \\n\\
\\n\\
Call formats: \\n\\
\\n\\
result = %(funclabel)s(array1, param) \\n\\
result = %(funclabel)s(param, array1) \\n\\
result = %(funclabel)s(array1, array2) \\n\\
result = %(funclabel)s(array1, param, maxlen=y) \\n\\
result = %(funclabel)s(array1, param, nosimd=False) \\n\\
\\n\\
* array1 - The first input data array to be examined. If no output \\n\\
array is provided the results will overwrite the input data. \\n\\
* param - A non-array numeric parameter. \\n\\
* array2 - A second input data array. Each element in this array is \\n\\
applied to the corresponding element in the first array. \\n\\
* maxlen - Limit the length of the array used. This must be a valid \\n\\
positive integer. If a zero or negative length, or a value which is \\n\\
greater than the actual length of the array is specified, this \\n\\
parameter is ignored. \\n\\
* nosimd - If True, SIMD acceleration is disabled if present. \\n\\
The default is False (SIMD acceleration is enabled if present). \\n\\
* result - A boolean value corresponding to the result of all the \\n\\
comparison operations. If all comparison operations result in true, \\n\\
the return value will be true. If any of them result in false, the \\n\\
return value will be false. \\n\\
");
/*--------------------------------------------------------------------------- */
/* A list of all the methods defined by this module.
"%(funclabel)s" is the name seen inside of Python.
"py_%(funclabel)s" is the name of the C function handling the Python call.
"METH_VARGS" tells Python how to call the handler.
The {NULL, NULL} entry indicates the end of the method definitions. */
static PyMethodDef %(funclabel)s_methods[] = {
{"%(funclabel)s", (PyCFunction)py_%(funclabel)s, METH_VARARGS | METH_KEYWORDS, %(funclabel)s__doc__},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef %(funclabel)smodule = {
PyModuleDef_HEAD_INIT,
"%(funclabel)s",
NULL,
-1,
%(funclabel)s_methods
};
PyMODINIT_FUNC PyInit_%(funclabel)s(void)
{
return PyModule_Create(&%(funclabel)smodule);
};
/*--------------------------------------------------------------------------- */
"""
# ==============================================================================
# SIMD call, version 1.
SIMD_calltemplate_1 = '''\n%(simdplatform)s
// SIMD version.
if (!nosimd && (arraylen >= (%(simdwidth)s * 2))) {
return %(funclabel)s_%(funcmodifier)s_1_simd(arraylen, data1, param);
}
#endif\n'''
# SIMD call, version 3.
SIMD_calltemplate_3 = '''\n%(simdplatform)s
// SIMD version.
if (!nosimd && (arraylen >= (%(simdwidth)s * 2))) {
return %(funclabel)s_%(funcmodifier)s_3_simd(arraylen, param, data2);
}
#endif\n'''
# SIMD call, version 5.
SIMD_calltemplate_5 = '''\n%(simdplatform)s
// SIMD version.
if (!nosimd && (arraylen >= (%(simdwidth)s * 2))) {
return %(funclabel)s_%(funcmodifier)s_5_simd(arraylen, data1, data2);
}
#endif\n'''
# ==============================================================================
# ==============================================================================
# SIMD code for x86. These handle the comparison operations. This must be
# done in a round about way for x86 due to the way it works on that platform.
# This set covers unsigned integer operations only.
# param_arr_num
SIMD_x86_uint_arr_num = {
'eq' : '''// Compare the slices.
resultslice = %(veqinstr)s(datasliceleft, datasliceright);
// Check the results of the SIMD operation.
if (!(__builtin_ia32_pmovmskb128((v16qi) resultslice) == 0xffff)) {
return 0;
}''',
'ge' : '''// Find the minimum values.
compslice = %(vmininstr)s(datasliceleft, datasliceright);
// If this is different from our compare parameter, then the test
// has failed.
resultslice = %(veqinstr)s(compslice, datasliceright);
// Check the results of the SIMD operation.
if ((__builtin_ia32_pmovmskb128((v16qi) resultslice) != 0xffff)) {
return 0;
}''',
'gt' : '''// Make sure they're not equal.
resultslice = %(veqinstr)s(datasliceleft, datasliceright);
if (!(__builtin_ia32_pmovmskb128((v16qi) resultslice) == 0x0000)) {
return 0;
}
// Find the minimum values.
compslice = %(vmininstr)s(datasliceleft, datasliceright);
// If this is different from our compare parameter, then the test
// has failed.
resultslice = %(veqinstr)s(compslice, datasliceright);
// Check the results of the SIMD operation.
if ((__builtin_ia32_pmovmskb128((v16qi) resultslice) != 0xffff)) {
return 0;
}''',
'le' : '''// Find the maximum values.
compslice = %(vmaxinstr)s(datasliceleft, datasliceright);
// If this is different from our compare parameter, then the test
// has failed.
resultslice = | |
<reponame>JonathanGailliez/azure-sdk-for-python
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
import uuid
from msrest.pipeline import ClientRawResponse
from .. import models
class DiagnosticsOperations(object):
"""DiagnosticsOperations operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
:ivar api_version: API Version. Constant value: "2018-02-01".
"""
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.api_version = "2018-02-01"
self.config = config
def list_hosting_environment_detector_responses(
self, resource_group_name, name, custom_headers=None, raw=False, **operation_config):
"""List Hosting Environment Detector Responses.
List Hosting Environment Detector Responses.
:param resource_group_name: Name of the resource group to which the
resource belongs.
:type resource_group_name: str
:param name: Site Name
:type name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of DetectorResponse
:rtype:
~azure.mgmt.web.models.DetectorResponsePaged[~azure.mgmt.web.models.DetectorResponse]
:raises:
:class:`DefaultErrorResponseException<azure.mgmt.web.models.DefaultErrorResponseException>`
"""
def internal_paging(next_link=None, raw=False):
if not next_link:
# Construct URL
url = self.list_hosting_environment_detector_responses.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+[^\.]$'),
'name': self._serialize.url("name", name, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
else:
url = next_link
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.DefaultErrorResponseException(self._deserialize, response)
return response
# Deserialize response
deserialized = models.DetectorResponsePaged(internal_paging, self._deserialize.dependencies)
if raw:
header_dict = {}
client_raw_response = models.DetectorResponsePaged(internal_paging, self._deserialize.dependencies, header_dict)
return client_raw_response
return deserialized
list_hosting_environment_detector_responses.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/detectors'}
def get_hosting_environment_detector_response(
self, resource_group_name, name, detector_name, start_time=None, end_time=None, time_grain=None, custom_headers=None, raw=False, **operation_config):
"""Get Hosting Environment Detector Response.
Get Hosting Environment Detector Response.
:param resource_group_name: Name of the resource group to which the
resource belongs.
:type resource_group_name: str
:param name: App Service Environment Name
:type name: str
:param detector_name: Detector Resource Name
:type detector_name: str
:param start_time: Start Time
:type start_time: datetime
:param end_time: End Time
:type end_time: datetime
:param time_grain: Time Grain
:type time_grain: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: DetectorResponse or ClientRawResponse if raw=true
:rtype: ~azure.mgmt.web.models.DetectorResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`DefaultErrorResponseException<azure.mgmt.web.models.DefaultErrorResponseException>`
"""
# Construct URL
url = self.get_hosting_environment_detector_response.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+[^\.]$'),
'name': self._serialize.url("name", name, 'str'),
'detectorName': self._serialize.url("detector_name", detector_name, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if start_time is not None:
query_parameters['startTime'] = self._serialize.query("start_time", start_time, 'iso-8601')
if end_time is not None:
query_parameters['endTime'] = self._serialize.query("end_time", end_time, 'iso-8601')
if time_grain is not None:
query_parameters['timeGrain'] = self._serialize.query("time_grain", time_grain, 'str', pattern=r'PT[1-9][0-9]+[SMH]')
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.DefaultErrorResponseException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('DetectorResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_hosting_environment_detector_response.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/detectors/{detectorName}'}
def list_site_detector_responses(
self, resource_group_name, site_name, custom_headers=None, raw=False, **operation_config):
"""List Site Detector Responses.
List Site Detector Responses.
:param resource_group_name: Name of the resource group to which the
resource belongs.
:type resource_group_name: str
:param site_name: Site Name
:type site_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of DetectorResponse
:rtype:
~azure.mgmt.web.models.DetectorResponsePaged[~azure.mgmt.web.models.DetectorResponse]
:raises:
:class:`DefaultErrorResponseException<azure.mgmt.web.models.DefaultErrorResponseException>`
"""
def internal_paging(next_link=None, raw=False):
if not next_link:
# Construct URL
url = self.list_site_detector_responses.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+[^\.]$'),
'siteName': self._serialize.url("site_name", site_name, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
else:
url = next_link
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.DefaultErrorResponseException(self._deserialize, response)
return response
# Deserialize response
deserialized = models.DetectorResponsePaged(internal_paging, self._deserialize.dependencies)
if raw:
header_dict = {}
client_raw_response = models.DetectorResponsePaged(internal_paging, self._deserialize.dependencies, header_dict)
return client_raw_response
return deserialized
list_site_detector_responses.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/detectors'}
def get_site_detector_response(
self, resource_group_name, site_name, detector_name, start_time=None, end_time=None, time_grain=None, custom_headers=None, raw=False, **operation_config):
"""Get site detector response.
Get site detector response.
:param resource_group_name: Name of the resource group to which the
resource belongs.
:type resource_group_name: str
:param site_name: Site Name
:type site_name: str
:param detector_name: Detector Resource Name
:type detector_name: str
:param start_time: Start Time
:type start_time: datetime
:param end_time: End Time
:type end_time: datetime
:param time_grain: Time Grain
:type time_grain: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: DetectorResponse or ClientRawResponse if raw=true
:rtype: ~azure.mgmt.web.models.DetectorResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`DefaultErrorResponseException<azure.mgmt.web.models.DefaultErrorResponseException>`
"""
# Construct URL
url = self.get_site_detector_response.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+[^\.]$'),
'siteName': self._serialize.url("site_name", site_name, 'str'),
'detectorName': self._serialize.url("detector_name", detector_name, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if start_time is not None:
query_parameters['startTime'] = self._serialize.query("start_time", start_time, 'iso-8601')
if end_time is not None:
query_parameters['endTime'] = self._serialize.query("end_time", end_time, 'iso-8601')
if time_grain is not None:
query_parameters['timeGrain'] = self._serialize.query("time_grain", time_grain, 'str', pattern=r'PT[1-9][0-9]+[SMH]')
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.DefaultErrorResponseException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('DetectorResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_site_detector_response.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/detectors/{detectorName}'}
def list_site_diagnostic_categories(
self, resource_group_name, site_name, custom_headers=None, raw=False, **operation_config):
"""Get Diagnostics Categories.
Get Diagnostics Categories.
:param resource_group_name: Name of the resource group to which the
resource belongs.
:type resource_group_name: str
:param site_name: Site Name
:type site_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of DiagnosticCategory
:rtype:
~azure.mgmt.web.models.DiagnosticCategoryPaged[~azure.mgmt.web.models.DiagnosticCategory]
:raises:
:class:`DefaultErrorResponseException<azure.mgmt.web.models.DefaultErrorResponseException>`
"""
def internal_paging(next_link=None, raw=False):
if not next_link:
# Construct URL
url = self.list_site_diagnostic_categories.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+[^\.]$'),
'siteName': self._serialize.url("site_name", site_name, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
else:
url = next_link
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.DefaultErrorResponseException(self._deserialize, response)
return response
# Deserialize response
deserialized = models.DiagnosticCategoryPaged(internal_paging, self._deserialize.dependencies)
if raw:
header_dict = {}
client_raw_response = models.DiagnosticCategoryPaged(internal_paging, self._deserialize.dependencies, header_dict)
return client_raw_response
return deserialized
list_site_diagnostic_categories.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/diagnostics'}
def get_site_diagnostic_category(
self, resource_group_name, site_name, diagnostic_category, custom_headers=None, raw=False, **operation_config):
"""Get Diagnostics Category.
Get Diagnostics Category.
:param resource_group_name: Name of the | |
('remote_address', (YLeaf(YType.str, 'remote-address'), ['str','str'])),
('member_interface', (YLeaf(YType.str, 'member-interface'), ['str'])),
])
self.local_address = None
self.remote_address = None
self.member_interface = None
self._segment_path = lambda: "config"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Bfd.Interfaces.Interface.MicroBfdSessions.MicroBfdSession.Config, ['local_address', 'remote_address', 'member_interface'], name, value)
class State(_Entity_):
"""
Operational state parameters for the micro\-BFD session.
.. attribute:: local_address
The local IP address used by the system for the micro\-BFD session specified
**type**\: union of the below types:
**type**\: str
**pattern:** ^(([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])$
**type**\: str
**pattern:** ^(([0\-9a\-fA\-F]{1,4}\:){7}[0\-9a\-fA\-F]{1,4}\|([0\-9a\-fA\-F]{1,4}\:){1,7}\:\|([0\-9a\-fA\-F]{1,4}\:){1,6}\:[0\-9a\-fA\-F]{1,4}\|([0\-9a\-fA\-F]{1,4}\:){1,5}(\:[0\-9a\-fA\-F]{1,4}){1,2}\|([0\-9a\-fA\-F]{1,4}\:){1,4}(\:[0\-9a\-fA\-F]{1,4}){1,3}\|([0\-9a\-fA\-F]{1,4}\:){1,3}(\:[0\-9a\-fA\-F]{1,4}){1,4}\|([0\-9a\-fA\-F]{1,4}\:){1,2}(\:[0\-9a\-fA\-F]{1,4}){1,5}\|[0\-9a\-fA\-F]{1,4}\:((\:[0\-9a\-fA\-F]{1,4}){1,6})\|\:((\:[0\-9a\-fA\-F]{1,4}){1,7}\|\:))$
**config**\: False
.. attribute:: remote_address
The remote IP destination that should be used by the system for the micro\-BFD session specified
**type**\: union of the below types:
**type**\: str
**pattern:** ^(([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])$
**type**\: str
**pattern:** ^(([0\-9a\-fA\-F]{1,4}\:){7}[0\-9a\-fA\-F]{1,4}\|([0\-9a\-fA\-F]{1,4}\:){1,7}\:\|([0\-9a\-fA\-F]{1,4}\:){1,6}\:[0\-9a\-fA\-F]{1,4}\|([0\-9a\-fA\-F]{1,4}\:){1,5}(\:[0\-9a\-fA\-F]{1,4}){1,2}\|([0\-9a\-fA\-F]{1,4}\:){1,4}(\:[0\-9a\-fA\-F]{1,4}){1,3}\|([0\-9a\-fA\-F]{1,4}\:){1,3}(\:[0\-9a\-fA\-F]{1,4}){1,4}\|([0\-9a\-fA\-F]{1,4}\:){1,2}(\:[0\-9a\-fA\-F]{1,4}){1,5}\|[0\-9a\-fA\-F]{1,4}\:((\:[0\-9a\-fA\-F]{1,4}){1,6})\|\:((\:[0\-9a\-fA\-F]{1,4}){1,7}\|\:))$
**config**\: False
.. attribute:: member_interface
Reference to a member link of the aggregate interface being described
**type**\: str
**refers to**\: :py:class:`name <ydk.models.openconfig.openconfig_interfaces.Interfaces.Interface.Config>`
**config**\: False
.. attribute:: session_state
The state of the BFD session perceived by the local system
**type**\: :py:class:`BfdSessionState <ydk.models.openconfig.openconfig_bfd.BfdSessionState>`
**config**\: False
.. attribute:: remote_session_state
The reported state of the BFD session according to the remote system. This state reflects the last state reported in a BFD control packet
**type**\: :py:class:`BfdSessionState <ydk.models.openconfig.openconfig_bfd.BfdSessionState>`
**config**\: False
.. attribute:: last_failure_time
The time of the last transition of the BFD session out of the UP state, expressed as the number of nanoseconds since the Unix epoch
**type**\: int
**range:** 0..18446744073709551615
**config**\: False
.. attribute:: failure_transitions
The number of times that the BFD session has transitioned out of the UP state
**type**\: int
**range:** 0..18446744073709551615
**config**\: False
.. attribute:: local_discriminator
A unique identifier used by the local system to identify this BFD session
**type**\: str
**config**\: False
.. attribute:: remote_discriminator
A unique identified used by the remote system to identify this BFD session
**type**\: str
**config**\: False
.. attribute:: local_diagnostic_code
The local BFD diagnostic code indicating the most recent reason for failure of this BFD session
**type**\: :py:class:`BfdDiagnosticCode <ydk.models.openconfig.openconfig_bfd.BfdDiagnosticCode>`
**config**\: False
.. attribute:: remote_diagnostic_code
The remote BFD diagnostic code indicating the remote system's reason for failure of the BFD session
**type**\: :py:class:`BfdDiagnosticCode <ydk.models.openconfig.openconfig_bfd.BfdDiagnosticCode>`
**config**\: False
.. attribute:: remote_minimum_receive_interval
The value of the minimum receive interval that was specified in the most recent BFD control packet received from the peer
**type**\: int
**range:** 0..4294967295
**config**\: False
.. attribute:: demand_mode_requested
This leaf is set to true when the remote system has requested demand mode be run for this session
**type**\: bool
**config**\: False
.. attribute:: remote_authentication_enabled
This leaf is set to true when the remote system has specified that authentication is present for the BFD session
**type**\: bool
**config**\: False
.. attribute:: remote_control_plane_independent
This leaf is set to true when the remote system has specified that the hardware implementing this BFD session is independent of the control plane's liveliness
**type**\: bool
**config**\: False
.. attribute:: async_
Operational state parameters specifically relating to asynchronous mode of BFD
**type**\: :py:class:`Async <ydk.models.openconfig.openconfig_bfd.Bfd.Interfaces.Interface.MicroBfdSessions.MicroBfdSession.State.Async>`
**config**\: False
"""
_prefix = 'oc-bfd'
_revision = '2018-11-21'
def __init__(self):
if sys.version_info > (3,):
super().__init__()
else:
super(Bfd.Interfaces.Interface.MicroBfdSessions.MicroBfdSession.State, self).__init__()
self.yang_name = "state"
self.yang_parent_name = "micro-bfd-session"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([("async", ("async_", Bfd.Interfaces.Interface.MicroBfdSessions.MicroBfdSession.State.Async))])
self._leafs = OrderedDict([
('local_address', (YLeaf(YType.str, 'local-address'), ['str','str'])),
('remote_address', (YLeaf(YType.str, 'remote-address'), ['str','str'])),
('member_interface', (YLeaf(YType.str, 'member-interface'), ['str'])),
('session_state', (YLeaf(YType.enumeration, 'session-state'), [('ydk.models.openconfig.openconfig_bfd', 'BfdSessionState', '')])),
('remote_session_state', (YLeaf(YType.enumeration, 'remote-session-state'), [('ydk.models.openconfig.openconfig_bfd', 'BfdSessionState', '')])),
('last_failure_time', (YLeaf(YType.uint64, 'last-failure-time'), ['int'])),
('failure_transitions', (YLeaf(YType.uint64, 'failure-transitions'), ['int'])),
('local_discriminator', (YLeaf(YType.str, 'local-discriminator'), ['str'])),
('remote_discriminator', (YLeaf(YType.str, 'remote-discriminator'), ['str'])),
('local_diagnostic_code', (YLeaf(YType.enumeration, 'local-diagnostic-code'), [('ydk.models.openconfig.openconfig_bfd', 'BfdDiagnosticCode', '')])),
('remote_diagnostic_code', (YLeaf(YType.enumeration, 'remote-diagnostic-code'), [('ydk.models.openconfig.openconfig_bfd', 'BfdDiagnosticCode', '')])),
('remote_minimum_receive_interval', (YLeaf(YType.uint32, 'remote-minimum-receive-interval'), ['int'])),
('demand_mode_requested', (YLeaf(YType.boolean, 'demand-mode-requested'), ['bool'])),
('remote_authentication_enabled', (YLeaf(YType.boolean, 'remote-authentication-enabled'), ['bool'])),
('remote_control_plane_independent', (YLeaf(YType.boolean, 'remote-control-plane-independent'), ['bool'])),
])
self.local_address = None
self.remote_address = None
self.member_interface = None
self.session_state = None
self.remote_session_state = None
self.last_failure_time = None
self.failure_transitions = None
self.local_discriminator = None
self.remote_discriminator = None
self.local_diagnostic_code = None
self.remote_diagnostic_code = None
self.remote_minimum_receive_interval = None
self.demand_mode_requested = None
self.remote_authentication_enabled = None
self.remote_control_plane_independent = None
self.async_ = Bfd.Interfaces.Interface.MicroBfdSessions.MicroBfdSession.State.Async()
self.async_.parent = self
self._children_name_map["async_"] = "async"
self._segment_path = lambda: "state"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Bfd.Interfaces.Interface.MicroBfdSessions.MicroBfdSession.State, ['local_address', 'remote_address', 'member_interface', 'session_state', 'remote_session_state', 'last_failure_time', 'failure_transitions', 'local_discriminator', 'remote_discriminator', 'local_diagnostic_code', 'remote_diagnostic_code', 'remote_minimum_receive_interval', 'demand_mode_requested', 'remote_authentication_enabled', 'remote_control_plane_independent'], name, value)
class Async(_Entity_):
"""
Operational state parameters specifically relating to
asynchronous mode of BFD.
.. attribute:: last_packet_transmitted
The date and time at which the last BFD packet was transmitted for this session, expressed as the number of nanoseconds since the Unix Epoch (January 1, 1970, 00\:00 UTC)
**type**\: int
**range:** 0..18446744073709551615
**config**\: False
.. attribute:: last_packet_received
The date and time at which the last BFD packet was received for this session, expressed as the number of nanoseconds since the Unix Epoch (January 1, 1970, 00\:00 UTC)
**type**\: int
**range:** 0..18446744073709551615
**config**\: False
.. attribute:: transmitted_packets
The number of packets that have been transmitted by the local system
**type**\: int
**range:** 0..18446744073709551615
**config**\: False
.. attribute:: received_packets
The number of packets that have been received by the local system from the remote neighbour
**type**\: int
**range:** 0..18446744073709551615
**config**\: False
.. attribute:: up_transitions
The number of times that the adjacency with the neighbor has transitioned into the up state
**type**\: int
**range:** 0..18446744073709551615
**config**\: False
"""
_prefix = 'oc-bfd'
_revision = '2018-11-21'
def __init__(self):
if sys.version_info > (3,):
super().__init__()
else:
super(Bfd.Interfaces.Interface.MicroBfdSessions.MicroBfdSession.State.Async, self).__init__()
self.yang_name = "async"
self.yang_parent_name = "state"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([])
self._leafs = OrderedDict([
('last_packet_transmitted', (YLeaf(YType.uint64, 'last-packet-transmitted'), ['int'])),
('last_packet_received', (YLeaf(YType.uint64, 'last-packet-received'), ['int'])),
('transmitted_packets', (YLeaf(YType.uint64, 'transmitted-packets'), ['int'])),
('received_packets', (YLeaf(YType.uint64, 'received-packets'), ['int'])),
('up_transitions', (YLeaf(YType.uint64, 'up-transitions'), ['int'])),
])
self.last_packet_transmitted = None
self.last_packet_received = None
self.transmitted_packets = None
self.received_packets = None
self.up_transitions = None
self._segment_path = lambda: "async"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Bfd.Interfaces.Interface.MicroBfdSessions.MicroBfdSession.State.Async, ['last_packet_transmitted', 'last_packet_received', 'transmitted_packets', 'received_packets', 'up_transitions'], name, value)
class Peers(_Entity_):
"""
Parameters relating to the BFD peers which are seen
over this interface.
.. attribute:: peer
Parameters relating to the BFD peer specified by the remote address
**type**\: list of :py:class:`Peer <ydk.models.openconfig.openconfig_bfd.Bfd.Interfaces.Interface.Peers.Peer>`
**config**\: False
"""
_prefix = 'oc-bfd'
_revision = '2018-11-21'
def __init__(self):
if sys.version_info > (3,):
super().__init__()
else:
super(Bfd.Interfaces.Interface.Peers, self).__init__()
self.yang_name = "peers"
self.yang_parent_name = "interface"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_classes = OrderedDict([("peer", ("peer", Bfd.Interfaces.Interface.Peers.Peer))])
self._leafs = OrderedDict()
self.peer = YList(self)
self._segment_path = lambda: "peers"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Bfd.Interfaces.Interface.Peers, [], name, value)
class Peer(_Entity_):
"""
Parameters relating to the BFD peer specified by the
remote address.
.. attribute:: local_discriminator (key)
The local discriminator, which is unique for the session on the system
**type**\: str
**refers to**\: :py:class:`local_discriminator <ydk.models.openconfig.openconfig_bfd.Bfd.Interfaces.Interface.Peers.Peer.State>`
**config**\: False
.. attribute:: state
Operational state parameters for the BFD session
**type**\: :py:class:`State <ydk.models.openconfig.openconfig_bfd.Bfd.Interfaces.Interface.Peers.Peer.State>`
**config**\: False
"""
_prefix = 'oc-bfd'
_revision = '2018-11-21'
def __init__(self):
if sys.version_info > (3,):
super().__init__()
else:
super(Bfd.Interfaces.Interface.Peers.Peer, self).__init__()
self.yang_name = "peer"
self.yang_parent_name = "peers"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = ['local_discriminator']
self._child_classes = OrderedDict([("state", ("state", Bfd.Interfaces.Interface.Peers.Peer.State))])
self._leafs = OrderedDict([
('local_discriminator', (YLeaf(YType.str, 'local-discriminator'), ['str'])),
])
self.local_discriminator = None
self.state = Bfd.Interfaces.Interface.Peers.Peer.State()
self.state.parent = self
self._children_name_map["state"] = "state"
self._segment_path = lambda: "peer" + "[local-discriminator='" + str(self.local_discriminator) + "']"
self._is_frozen = True
def __setattr__(self, name, value):
self._perform_setattr(Bfd.Interfaces.Interface.Peers.Peer, ['local_discriminator'], name, value)
class State(_Entity_):
"""
Operational state parameters for the BFD session.
.. attribute:: local_address
The IP address used by the local system for this BFD session
**type**\: union of the below types:
**type**\: str
**pattern:** ^(([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])$
**type**\: str
**pattern:** |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.