ngram
listlengths 0
67.8k
|
|---|
[
"'Python') def test_multiple_word(self): text = 'python django' result = cap.cap_text(text) self.assertEquals(result, 'Python Django')",
"= 'python' result = cap.cap_text(text) self.assertEquals(result, 'Python') def test_multiple_word(self): text = 'python django'",
"'python django' result = cap.cap_text(text) self.assertEquals(result, 'Python Django') if __name__ == '__main__': unittest.main()",
"def test_multiple_word(self): text = 'python django' result = cap.cap_text(text) self.assertEquals(result, 'Python Django') if",
"self.assertEquals(result, 'Python') def test_multiple_word(self): text = 'python django' result = cap.cap_text(text) self.assertEquals(result, 'Python",
"TestCap(unittest.TestCase): def test_single_word(self): text = 'python' result = cap.cap_text(text) self.assertEquals(result, 'Python') def test_multiple_word(self):",
"text = 'python django' result = cap.cap_text(text) self.assertEquals(result, 'Python Django') if __name__ ==",
"test_single_word(self): text = 'python' result = cap.cap_text(text) self.assertEquals(result, 'Python') def test_multiple_word(self): text =",
"class TestCap(unittest.TestCase): def test_single_word(self): text = 'python' result = cap.cap_text(text) self.assertEquals(result, 'Python') def",
"import unittest import cap class TestCap(unittest.TestCase): def test_single_word(self): text = 'python' result =",
"= cap.cap_text(text) self.assertEquals(result, 'Python') def test_multiple_word(self): text = 'python django' result = cap.cap_text(text)",
"= 'python django' result = cap.cap_text(text) self.assertEquals(result, 'Python Django') if __name__ == '__main__':",
"def test_single_word(self): text = 'python' result = cap.cap_text(text) self.assertEquals(result, 'Python') def test_multiple_word(self): text",
"cap.cap_text(text) self.assertEquals(result, 'Python') def test_multiple_word(self): text = 'python django' result = cap.cap_text(text) self.assertEquals(result,",
"'python' result = cap.cap_text(text) self.assertEquals(result, 'Python') def test_multiple_word(self): text = 'python django' result",
"text = 'python' result = cap.cap_text(text) self.assertEquals(result, 'Python') def test_multiple_word(self): text = 'python",
"test_multiple_word(self): text = 'python django' result = cap.cap_text(text) self.assertEquals(result, 'Python Django') if __name__",
"import cap class TestCap(unittest.TestCase): def test_single_word(self): text = 'python' result = cap.cap_text(text) self.assertEquals(result,",
"unittest import cap class TestCap(unittest.TestCase): def test_single_word(self): text = 'python' result = cap.cap_text(text)",
"result = cap.cap_text(text) self.assertEquals(result, 'Python') def test_multiple_word(self): text = 'python django' result =",
"cap class TestCap(unittest.TestCase): def test_single_word(self): text = 'python' result = cap.cap_text(text) self.assertEquals(result, 'Python')"
] |
[
"} class Vault: _cache = {} cast_handlers: 'Dict[Callable]' = {} secret_sources: 'List[BaseSecretSource]' =",
"self._get_from_source(name, default, source) value = self._preprocess(value, preprocessors) value = self._cast_to(value, cast_to, default) if",
"= {} if secret_sources is None: secret_sources = [] if preprocessors is None:",
"cast_to=None, no_cache=False, cache_result=True ): if no_cache is False and name in self._cache: return",
"cast_handlers = {} if secret_sources is None: secret_sources = [] if preprocessors is",
"source): if source is not None: return source.get(name) if not self.secret_sources: raise SecretSourceMissing",
"import EnvironmentVariableSecretSource class NoDefault: pass DEFAULT_SECRET_SOURCES = [ EnvironmentVariableSecretSource() ] DEFAULT_CAST_HANDLERS = {",
".secret_sources import BaseSecretSource from .secret_sources import EnvironmentVariableSecretSource class NoDefault: pass DEFAULT_SECRET_SOURCES = [",
"SecretMissingError(name) else: value = default return value def _preprocess(self, value, preprocessors): if preprocessors",
"value = default return value def _preprocess(self, value, preprocessors): if preprocessors is None:",
"else: if default is NoDefault: raise SecretMissingError(name) else: value = default return value",
"'List[Callable[str, str]]' = [] def __init__(self, secret_sources=None, cast_handlers=None, preprocessors=None): if cast_handlers is None:",
"= {**self.default_cast_handlers} def add_preprocessor(self, fn): self.preprocessors.append(fn) def clear_preprocessors(self): self.preprocessors = [] def reset_preprocessors(self):",
"self.preprocessors else: preprocessors = preprocessors for preprocessor in preprocessors: value = preprocessor(value) return",
"= self._get_from_source(name, default, source) value = self._preprocess(value, preprocessors) value = self._cast_to(value, cast_to, default)",
"preprocessors) value = self._cast_to(value, cast_to, default) if cache_result: self._cache[name] = value return value",
"value = source.get(name) break except SecretMissingError: pass else: if default is NoDefault: raise",
"= [] self.default_secret_sources = secret_sources self.default_cast_handlers = cast_handlers self.default_preprocessors = preprocessors self.reset() def",
"'BaseSecretSource'): if source in self.secret_sources: return self.secret_sources.append(source) def clear_secret_sources(self): self.secret_sources = [] def",
"Callable from .cast_handlers import bool_cast_handler from .exceptions import CastHandlerMissingError from .exceptions import SecretMissingError",
"cast_handlers: 'Dict[Callable]' = {} secret_sources: 'List[BaseSecretSource]' = [] preprocessors: 'List[Callable[str, str]]' = []",
"from .cast_handlers import bool_cast_handler from .exceptions import CastHandlerMissingError from .exceptions import SecretMissingError from",
"= handler def clear_cast_handlers(self): self.cast_handlers = {} def reset_cast_handlers(self): self.cast_handlers = {**self.default_cast_handlers} def",
"return value def _preprocess(self, value, preprocessors): if preprocessors is None: preprocessors = self.preprocessors",
"value return value def _get_from_source(self, name, default, source): if source is not None:",
"[] self.default_secret_sources = secret_sources self.default_cast_handlers = cast_handlers self.default_preprocessors = preprocessors self.reset() def add_secret_source(self,",
"preprocessors: 'List[Callable[str, str]]' = [] def __init__(self, secret_sources=None, cast_handlers=None, preprocessors=None): if cast_handlers is",
"self.secret_sources: raise SecretSourceMissing for source in self.secret_sources: try: value = source.get(name) break except",
"EnvironmentVariableSecretSource class NoDefault: pass DEFAULT_SECRET_SOURCES = [ EnvironmentVariableSecretSource() ] DEFAULT_CAST_HANDLERS = { bool:",
"preprocessors = self.preprocessors else: preprocessors = preprocessors for preprocessor in preprocessors: value =",
"= cast_handlers self.default_preprocessors = preprocessors self.reset() def add_secret_source(self, source: 'BaseSecretSource'): if source in",
"if preprocessors is None: preprocessors = [] self.default_secret_sources = secret_sources self.default_cast_handlers = cast_handlers",
"self.reset() def add_secret_source(self, source: 'BaseSecretSource'): if source in self.secret_sources: return self.secret_sources.append(source) def clear_secret_sources(self):",
"else: preprocessors = preprocessors for preprocessor in preprocessors: value = preprocessor(value) return value",
"None: return source.get(name) if not self.secret_sources: raise SecretSourceMissing for source in self.secret_sources: try:",
"source in self.secret_sources: return self.secret_sources.append(source) def clear_secret_sources(self): self.secret_sources = [] def reset_secret_sources(self): self.secret_sources",
"self.default_secret_sources = secret_sources self.default_cast_handlers = cast_handlers self.default_preprocessors = preprocessors self.reset() def add_secret_source(self, source:",
"value, preprocessors): if preprocessors is None: preprocessors = self.preprocessors else: preprocessors = preprocessors",
"SecretMissingError from .exceptions import SecretSourceMissing from .secret_sources import BaseSecretSource from .secret_sources import EnvironmentVariableSecretSource",
"default): if value is default: return value if cast_to is not None: handler",
"reset_secret_sources(self): self.secret_sources = list(self.default_secret_sources) def add_cast_handler(self, handler_key, handler): self.cast_handlers[handler_key] = handler def clear_cast_handlers(self):",
"self._cache = {} def reset(self): self.reset_secret_sources() self.reset_cast_handlers() self.reset_preprocessors() self.clear_cache() def get( self, name,",
"from typing import List, Dict, Callable from .cast_handlers import bool_cast_handler from .exceptions import",
"from .secret_sources import EnvironmentVariableSecretSource class NoDefault: pass DEFAULT_SECRET_SOURCES = [ EnvironmentVariableSecretSource() ] DEFAULT_CAST_HANDLERS",
"return value def _cast_to(self, value, cast_to, default): if value is default: return value",
"def get( self, name, default=NoDefault, *, source=None, preprocessors=None, cast_to=None, no_cache=False, cache_result=True ): if",
"is default: return value if cast_to is not None: handler = self.cast_handlers.get(cast_to, cast_to)",
"secret_sources: 'List[BaseSecretSource]' = [] preprocessors: 'List[Callable[str, str]]' = [] def __init__(self, secret_sources=None, cast_handlers=None,",
"def reset_cast_handlers(self): self.cast_handlers = {**self.default_cast_handlers} def add_preprocessor(self, fn): self.preprocessors.append(fn) def clear_preprocessors(self): self.preprocessors =",
"__init__(self, secret_sources=None, cast_handlers=None, preprocessors=None): if cast_handlers is None: cast_handlers = {} if secret_sources",
"if cast_handlers is None: cast_handlers = {} if secret_sources is None: secret_sources =",
"is None: preprocessors = [] self.default_secret_sources = secret_sources self.default_cast_handlers = cast_handlers self.default_preprocessors =",
"reset_cast_handlers(self): self.cast_handlers = {**self.default_cast_handlers} def add_preprocessor(self, fn): self.preprocessors.append(fn) def clear_preprocessors(self): self.preprocessors = []",
"[] def reset_preprocessors(self): self.preprocessors = list(self.default_preprocessors) def clear_cache(self): self._cache = {} def reset(self):",
"from .exceptions import CastHandlerMissingError from .exceptions import SecretMissingError from .exceptions import SecretSourceMissing from",
"= { bool: bool_cast_handler, } class Vault: _cache = {} cast_handlers: 'Dict[Callable]' =",
"raise SecretMissingError(name) else: value = default return value def _preprocess(self, value, preprocessors): if",
"self._cast_to(value, cast_to, default) if cache_result: self._cache[name] = value return value def _get_from_source(self, name,",
"NoDefault: raise SecretMissingError(name) else: value = default return value def _preprocess(self, value, preprocessors):",
"SecretSourceMissing from .secret_sources import BaseSecretSource from .secret_sources import EnvironmentVariableSecretSource class NoDefault: pass DEFAULT_SECRET_SOURCES",
"{ bool: bool_cast_handler, } class Vault: _cache = {} cast_handlers: 'Dict[Callable]' = {}",
"class NoDefault: pass DEFAULT_SECRET_SOURCES = [ EnvironmentVariableSecretSource() ] DEFAULT_CAST_HANDLERS = { bool: bool_cast_handler,",
"self.preprocessors = list(self.default_preprocessors) def clear_cache(self): self._cache = {} def reset(self): self.reset_secret_sources() self.reset_cast_handlers() self.reset_preprocessors()",
"None: secret_sources = [] if preprocessors is None: preprocessors = [] self.default_secret_sources =",
"): if no_cache is False and name in self._cache: return self._cache[name] value =",
"{} def reset_cast_handlers(self): self.cast_handlers = {**self.default_cast_handlers} def add_preprocessor(self, fn): self.preprocessors.append(fn) def clear_preprocessors(self): self.preprocessors",
"self._cache: return self._cache[name] value = self._get_from_source(name, default, source) value = self._preprocess(value, preprocessors) value",
"try: value = source.get(name) break except SecretMissingError: pass else: if default is NoDefault:",
"_cast_to(self, value, cast_to, default): if value is default: return value if cast_to is",
"BaseSecretSource from .secret_sources import EnvironmentVariableSecretSource class NoDefault: pass DEFAULT_SECRET_SOURCES = [ EnvironmentVariableSecretSource() ]",
"value if cast_to is not None: handler = self.cast_handlers.get(cast_to, cast_to) if not callable(handler):",
"not self.secret_sources: raise SecretSourceMissing for source in self.secret_sources: try: value = source.get(name) break",
"in preprocessors: value = preprocessor(value) return value def _cast_to(self, value, cast_to, default): if",
"bool_cast_handler from .exceptions import CastHandlerMissingError from .exceptions import SecretMissingError from .exceptions import SecretSourceMissing",
"except SecretMissingError: pass else: if default is NoDefault: raise SecretMissingError(name) else: value =",
"secret_sources = [] if preprocessors is None: preprocessors = [] self.default_secret_sources = secret_sources",
"is not None: return source.get(name) if not self.secret_sources: raise SecretSourceMissing for source in",
"= preprocessors for preprocessor in preprocessors: value = preprocessor(value) return value def _cast_to(self,",
"no_cache=False, cache_result=True ): if no_cache is False and name in self._cache: return self._cache[name]",
"source in self.secret_sources: try: value = source.get(name) break except SecretMissingError: pass else: if",
"import List, Dict, Callable from .cast_handlers import bool_cast_handler from .exceptions import CastHandlerMissingError from",
"is None: secret_sources = [] if preprocessors is None: preprocessors = [] self.default_secret_sources",
"self.preprocessors.append(fn) def clear_preprocessors(self): self.preprocessors = [] def reset_preprocessors(self): self.preprocessors = list(self.default_preprocessors) def clear_cache(self):",
"preprocessors self.reset() def add_secret_source(self, source: 'BaseSecretSource'): if source in self.secret_sources: return self.secret_sources.append(source) def",
"value = preprocessor(value) return value def _cast_to(self, value, cast_to, default): if value is",
"= [] def __init__(self, secret_sources=None, cast_handlers=None, preprocessors=None): if cast_handlers is None: cast_handlers =",
"def add_cast_handler(self, handler_key, handler): self.cast_handlers[handler_key] = handler def clear_cast_handlers(self): self.cast_handlers = {} def",
"cast_to is not None: handler = self.cast_handlers.get(cast_to, cast_to) if not callable(handler): raise CastHandlerMissingError(",
"not None: handler = self.cast_handlers.get(cast_to, cast_to) if not callable(handler): raise CastHandlerMissingError( f'Cast handler:",
"{handler!r}, is not registered.' ) value = handler(value) return value vault = Vault(DEFAULT_SECRET_SOURCES,",
"and name in self._cache: return self._cache[name] value = self._get_from_source(name, default, source) value =",
"handler_key, handler): self.cast_handlers[handler_key] = handler def clear_cast_handlers(self): self.cast_handlers = {} def reset_cast_handlers(self): self.cast_handlers",
"for preprocessor in preprocessors: value = preprocessor(value) return value def _cast_to(self, value, cast_to,",
"for source in self.secret_sources: try: value = source.get(name) break except SecretMissingError: pass else:",
"is NoDefault: raise SecretMissingError(name) else: value = default return value def _preprocess(self, value,",
"self._preprocess(value, preprocessors) value = self._cast_to(value, cast_to, default) if cache_result: self._cache[name] = value return",
"is None: preprocessors = self.preprocessors else: preprocessors = preprocessors for preprocessor in preprocessors:",
"EnvironmentVariableSecretSource() ] DEFAULT_CAST_HANDLERS = { bool: bool_cast_handler, } class Vault: _cache = {}",
"self.cast_handlers = {**self.default_cast_handlers} def add_preprocessor(self, fn): self.preprocessors.append(fn) def clear_preprocessors(self): self.preprocessors = [] def",
"SecretMissingError: pass else: if default is NoDefault: raise SecretMissingError(name) else: value = default",
"if secret_sources is None: secret_sources = [] if preprocessors is None: preprocessors =",
"name in self._cache: return self._cache[name] value = self._get_from_source(name, default, source) value = self._preprocess(value,",
"def _preprocess(self, value, preprocessors): if preprocessors is None: preprocessors = self.preprocessors else: preprocessors",
"None: preprocessors = [] self.default_secret_sources = secret_sources self.default_cast_handlers = cast_handlers self.default_preprocessors = preprocessors",
"default) if cache_result: self._cache[name] = value return value def _get_from_source(self, name, default, source):",
"return value def _get_from_source(self, name, default, source): if source is not None: return",
"pass DEFAULT_SECRET_SOURCES = [ EnvironmentVariableSecretSource() ] DEFAULT_CAST_HANDLERS = { bool: bool_cast_handler, } class",
"name, default=NoDefault, *, source=None, preprocessors=None, cast_to=None, no_cache=False, cache_result=True ): if no_cache is False",
"name, default, source): if source is not None: return source.get(name) if not self.secret_sources:",
"str]]' = [] def __init__(self, secret_sources=None, cast_handlers=None, preprocessors=None): if cast_handlers is None: cast_handlers",
"default, source) value = self._preprocess(value, preprocessors) value = self._cast_to(value, cast_to, default) if cache_result:",
"default, source): if source is not None: return source.get(name) if not self.secret_sources: raise",
"= [] def reset_preprocessors(self): self.preprocessors = list(self.default_preprocessors) def clear_cache(self): self._cache = {} def",
"def reset_preprocessors(self): self.preprocessors = list(self.default_preprocessors) def clear_cache(self): self._cache = {} def reset(self): self.reset_secret_sources()",
"is not None: handler = self.cast_handlers.get(cast_to, cast_to) if not callable(handler): raise CastHandlerMissingError( f'Cast",
"handler = self.cast_handlers.get(cast_to, cast_to) if not callable(handler): raise CastHandlerMissingError( f'Cast handler: {handler!r}, is",
"= self.preprocessors else: preprocessors = preprocessors for preprocessor in preprocessors: value = preprocessor(value)",
"source.get(name) break except SecretMissingError: pass else: if default is NoDefault: raise SecretMissingError(name) else:",
"[] def __init__(self, secret_sources=None, cast_handlers=None, preprocessors=None): if cast_handlers is None: cast_handlers = {}",
"is None: cast_handlers = {} if secret_sources is None: secret_sources = [] if",
"value is default: return value if cast_to is not None: handler = self.cast_handlers.get(cast_to,",
"source) value = self._preprocess(value, preprocessors) value = self._cast_to(value, cast_to, default) if cache_result: self._cache[name]",
"add_secret_source(self, source: 'BaseSecretSource'): if source in self.secret_sources: return self.secret_sources.append(source) def clear_secret_sources(self): self.secret_sources =",
"self.secret_sources.append(source) def clear_secret_sources(self): self.secret_sources = [] def reset_secret_sources(self): self.secret_sources = list(self.default_secret_sources) def add_cast_handler(self,",
"break except SecretMissingError: pass else: if default is NoDefault: raise SecretMissingError(name) else: value",
"value, cast_to, default): if value is default: return value if cast_to is not",
".exceptions import SecretSourceMissing from .secret_sources import BaseSecretSource from .secret_sources import EnvironmentVariableSecretSource class NoDefault:",
"preprocessors = preprocessors for preprocessor in preprocessors: value = preprocessor(value) return value def",
"preprocessors=None, cast_to=None, no_cache=False, cache_result=True ): if no_cache is False and name in self._cache:",
"default=NoDefault, *, source=None, preprocessors=None, cast_to=None, no_cache=False, cache_result=True ): if no_cache is False and",
"{} secret_sources: 'List[BaseSecretSource]' = [] preprocessors: 'List[Callable[str, str]]' = [] def __init__(self, secret_sources=None,",
"import SecretSourceMissing from .secret_sources import BaseSecretSource from .secret_sources import EnvironmentVariableSecretSource class NoDefault: pass",
"self.default_preprocessors = preprocessors self.reset() def add_secret_source(self, source: 'BaseSecretSource'): if source in self.secret_sources: return",
"Dict, Callable from .cast_handlers import bool_cast_handler from .exceptions import CastHandlerMissingError from .exceptions import",
"self.cast_handlers[handler_key] = handler def clear_cast_handlers(self): self.cast_handlers = {} def reset_cast_handlers(self): self.cast_handlers = {**self.default_cast_handlers}",
"def add_secret_source(self, source: 'BaseSecretSource'): if source in self.secret_sources: return self.secret_sources.append(source) def clear_secret_sources(self): self.secret_sources",
"not None: return source.get(name) if not self.secret_sources: raise SecretSourceMissing for source in self.secret_sources:",
"_preprocess(self, value, preprocessors): if preprocessors is None: preprocessors = self.preprocessors else: preprocessors =",
"preprocessor in preprocessors: value = preprocessor(value) return value def _cast_to(self, value, cast_to, default):",
"= [ EnvironmentVariableSecretSource() ] DEFAULT_CAST_HANDLERS = { bool: bool_cast_handler, } class Vault: _cache",
"None: cast_handlers = {} if secret_sources is None: secret_sources = [] if preprocessors",
"List, Dict, Callable from .cast_handlers import bool_cast_handler from .exceptions import CastHandlerMissingError from .exceptions",
"= {} cast_handlers: 'Dict[Callable]' = {} secret_sources: 'List[BaseSecretSource]' = [] preprocessors: 'List[Callable[str, str]]'",
"= [] def reset_secret_sources(self): self.secret_sources = list(self.default_secret_sources) def add_cast_handler(self, handler_key, handler): self.cast_handlers[handler_key] =",
"get( self, name, default=NoDefault, *, source=None, preprocessors=None, cast_to=None, no_cache=False, cache_result=True ): if no_cache",
"import CastHandlerMissingError from .exceptions import SecretMissingError from .exceptions import SecretSourceMissing from .secret_sources import",
"None: handler = self.cast_handlers.get(cast_to, cast_to) if not callable(handler): raise CastHandlerMissingError( f'Cast handler: {handler!r},",
"default is NoDefault: raise SecretMissingError(name) else: value = default return value def _preprocess(self,",
"def clear_secret_sources(self): self.secret_sources = [] def reset_secret_sources(self): self.secret_sources = list(self.default_secret_sources) def add_cast_handler(self, handler_key,",
"self.secret_sources: return self.secret_sources.append(source) def clear_secret_sources(self): self.secret_sources = [] def reset_secret_sources(self): self.secret_sources = list(self.default_secret_sources)",
"value = self._cast_to(value, cast_to, default) if cache_result: self._cache[name] = value return value def",
"bool_cast_handler, } class Vault: _cache = {} cast_handlers: 'Dict[Callable]' = {} secret_sources: 'List[BaseSecretSource]'",
"self.default_cast_handlers = cast_handlers self.default_preprocessors = preprocessors self.reset() def add_secret_source(self, source: 'BaseSecretSource'): if source",
"cache_result=True ): if no_cache is False and name in self._cache: return self._cache[name] value",
"cast_to, default) if cache_result: self._cache[name] = value return value def _get_from_source(self, name, default,",
"self._cache[name] = value return value def _get_from_source(self, name, default, source): if source is",
"None: preprocessors = self.preprocessors else: preprocessors = preprocessors for preprocessor in preprocessors: value",
"secret_sources is None: secret_sources = [] if preprocessors is None: preprocessors = []",
"preprocessors is None: preprocessors = [] self.default_secret_sources = secret_sources self.default_cast_handlers = cast_handlers self.default_preprocessors",
"clear_cache(self): self._cache = {} def reset(self): self.reset_secret_sources() self.reset_cast_handlers() self.reset_preprocessors() self.clear_cache() def get( self,",
"clear_preprocessors(self): self.preprocessors = [] def reset_preprocessors(self): self.preprocessors = list(self.default_preprocessors) def clear_cache(self): self._cache =",
"self.cast_handlers = {} def reset_cast_handlers(self): self.cast_handlers = {**self.default_cast_handlers} def add_preprocessor(self, fn): self.preprocessors.append(fn) def",
"def reset(self): self.reset_secret_sources() self.reset_cast_handlers() self.reset_preprocessors() self.clear_cache() def get( self, name, default=NoDefault, *, source=None,",
"= self._cast_to(value, cast_to, default) if cache_result: self._cache[name] = value return value def _get_from_source(self,",
"source.get(name) if not self.secret_sources: raise SecretSourceMissing for source in self.secret_sources: try: value =",
"reset(self): self.reset_secret_sources() self.reset_cast_handlers() self.reset_preprocessors() self.clear_cache() def get( self, name, default=NoDefault, *, source=None, preprocessors=None,",
"{} cast_handlers: 'Dict[Callable]' = {} secret_sources: 'List[BaseSecretSource]' = [] preprocessors: 'List[Callable[str, str]]' =",
"default: return value if cast_to is not None: handler = self.cast_handlers.get(cast_to, cast_to) if",
"from .exceptions import SecretMissingError from .exceptions import SecretSourceMissing from .secret_sources import BaseSecretSource from",
"= {} secret_sources: 'List[BaseSecretSource]' = [] preprocessors: 'List[Callable[str, str]]' = [] def __init__(self,",
"= list(self.default_secret_sources) def add_cast_handler(self, handler_key, handler): self.cast_handlers[handler_key] = handler def clear_cast_handlers(self): self.cast_handlers =",
"Vault: _cache = {} cast_handlers: 'Dict[Callable]' = {} secret_sources: 'List[BaseSecretSource]' = [] preprocessors:",
"not callable(handler): raise CastHandlerMissingError( f'Cast handler: {handler!r}, is not registered.' ) value =",
"self.preprocessors = [] def reset_preprocessors(self): self.preprocessors = list(self.default_preprocessors) def clear_cache(self): self._cache = {}",
"in self._cache: return self._cache[name] value = self._get_from_source(name, default, source) value = self._preprocess(value, preprocessors)",
"SecretSourceMissing for source in self.secret_sources: try: value = source.get(name) break except SecretMissingError: pass",
"= source.get(name) break except SecretMissingError: pass else: if default is NoDefault: raise SecretMissingError(name)",
"self._cache[name] value = self._get_from_source(name, default, source) value = self._preprocess(value, preprocessors) value = self._cast_to(value,",
"source is not None: return source.get(name) if not self.secret_sources: raise SecretSourceMissing for source",
"CastHandlerMissingError( f'Cast handler: {handler!r}, is not registered.' ) value = handler(value) return value",
"[ EnvironmentVariableSecretSource() ] DEFAULT_CAST_HANDLERS = { bool: bool_cast_handler, } class Vault: _cache =",
"list(self.default_preprocessors) def clear_cache(self): self._cache = {} def reset(self): self.reset_secret_sources() self.reset_cast_handlers() self.reset_preprocessors() self.clear_cache() def",
"value def _get_from_source(self, name, default, source): if source is not None: return source.get(name)",
".cast_handlers import bool_cast_handler from .exceptions import CastHandlerMissingError from .exceptions import SecretMissingError from .exceptions",
"cache_result: self._cache[name] = value return value def _get_from_source(self, name, default, source): if source",
"is False and name in self._cache: return self._cache[name] value = self._get_from_source(name, default, source)",
"def clear_preprocessors(self): self.preprocessors = [] def reset_preprocessors(self): self.preprocessors = list(self.default_preprocessors) def clear_cache(self): self._cache",
"source: 'BaseSecretSource'): if source in self.secret_sources: return self.secret_sources.append(source) def clear_secret_sources(self): self.secret_sources = []",
"in self.secret_sources: return self.secret_sources.append(source) def clear_secret_sources(self): self.secret_sources = [] def reset_secret_sources(self): self.secret_sources =",
"cast_handlers self.default_preprocessors = preprocessors self.reset() def add_secret_source(self, source: 'BaseSecretSource'): if source in self.secret_sources:",
"def _get_from_source(self, name, default, source): if source is not None: return source.get(name) if",
"cast_handlers=None, preprocessors=None): if cast_handlers is None: cast_handlers = {} if secret_sources is None:",
"= list(self.default_preprocessors) def clear_cache(self): self._cache = {} def reset(self): self.reset_secret_sources() self.reset_cast_handlers() self.reset_preprocessors() self.clear_cache()",
"self.secret_sources = [] def reset_secret_sources(self): self.secret_sources = list(self.default_secret_sources) def add_cast_handler(self, handler_key, handler): self.cast_handlers[handler_key]",
".exceptions import SecretMissingError from .exceptions import SecretSourceMissing from .secret_sources import BaseSecretSource from .secret_sources",
"self.clear_cache() def get( self, name, default=NoDefault, *, source=None, preprocessors=None, cast_to=None, no_cache=False, cache_result=True ):",
"else: value = default return value def _preprocess(self, value, preprocessors): if preprocessors is",
"handler def clear_cast_handlers(self): self.cast_handlers = {} def reset_cast_handlers(self): self.cast_handlers = {**self.default_cast_handlers} def add_preprocessor(self,",
"from .exceptions import SecretSourceMissing from .secret_sources import BaseSecretSource from .secret_sources import EnvironmentVariableSecretSource class",
"add_preprocessor(self, fn): self.preprocessors.append(fn) def clear_preprocessors(self): self.preprocessors = [] def reset_preprocessors(self): self.preprocessors = list(self.default_preprocessors)",
"pass else: if default is NoDefault: raise SecretMissingError(name) else: value = default return",
"if default is NoDefault: raise SecretMissingError(name) else: value = default return value def",
"= default return value def _preprocess(self, value, preprocessors): if preprocessors is None: preprocessors",
"f'Cast handler: {handler!r}, is not registered.' ) value = handler(value) return value vault",
"fn): self.preprocessors.append(fn) def clear_preprocessors(self): self.preprocessors = [] def reset_preprocessors(self): self.preprocessors = list(self.default_preprocessors) def",
"{} if secret_sources is None: secret_sources = [] if preprocessors is None: preprocessors",
"default return value def _preprocess(self, value, preprocessors): if preprocessors is None: preprocessors =",
"bool: bool_cast_handler, } class Vault: _cache = {} cast_handlers: 'Dict[Callable]' = {} secret_sources:",
"[] if preprocessors is None: preprocessors = [] self.default_secret_sources = secret_sources self.default_cast_handlers =",
"_cache = {} cast_handlers: 'Dict[Callable]' = {} secret_sources: 'List[BaseSecretSource]' = [] preprocessors: 'List[Callable[str,",
"preprocessors): if preprocessors is None: preprocessors = self.preprocessors else: preprocessors = preprocessors for",
"if source in self.secret_sources: return self.secret_sources.append(source) def clear_secret_sources(self): self.secret_sources = [] def reset_secret_sources(self):",
"callable(handler): raise CastHandlerMissingError( f'Cast handler: {handler!r}, is not registered.' ) value = handler(value)",
"value = self._preprocess(value, preprocessors) value = self._cast_to(value, cast_to, default) if cache_result: self._cache[name] =",
"value def _cast_to(self, value, cast_to, default): if value is default: return value if",
"value def _preprocess(self, value, preprocessors): if preprocessors is None: preprocessors = self.preprocessors else:",
"CastHandlerMissingError from .exceptions import SecretMissingError from .exceptions import SecretSourceMissing from .secret_sources import BaseSecretSource",
"clear_secret_sources(self): self.secret_sources = [] def reset_secret_sources(self): self.secret_sources = list(self.default_secret_sources) def add_cast_handler(self, handler_key, handler):",
"reset_preprocessors(self): self.preprocessors = list(self.default_preprocessors) def clear_cache(self): self._cache = {} def reset(self): self.reset_secret_sources() self.reset_cast_handlers()",
"= self.cast_handlers.get(cast_to, cast_to) if not callable(handler): raise CastHandlerMissingError( f'Cast handler: {handler!r}, is not",
"if cast_to is not None: handler = self.cast_handlers.get(cast_to, cast_to) if not callable(handler): raise",
"list(self.default_secret_sources) def add_cast_handler(self, handler_key, handler): self.cast_handlers[handler_key] = handler def clear_cast_handlers(self): self.cast_handlers = {}",
"import SecretMissingError from .exceptions import SecretSourceMissing from .secret_sources import BaseSecretSource from .secret_sources import",
".exceptions import CastHandlerMissingError from .exceptions import SecretMissingError from .exceptions import SecretSourceMissing from .secret_sources",
"_get_from_source(self, name, default, source): if source is not None: return source.get(name) if not",
"preprocessors = [] self.default_secret_sources = secret_sources self.default_cast_handlers = cast_handlers self.default_preprocessors = preprocessors self.reset()",
"= {} def reset_cast_handlers(self): self.cast_handlers = {**self.default_cast_handlers} def add_preprocessor(self, fn): self.preprocessors.append(fn) def clear_preprocessors(self):",
"return source.get(name) if not self.secret_sources: raise SecretSourceMissing for source in self.secret_sources: try: value",
"add_cast_handler(self, handler_key, handler): self.cast_handlers[handler_key] = handler def clear_cast_handlers(self): self.cast_handlers = {} def reset_cast_handlers(self):",
"preprocessors is None: preprocessors = self.preprocessors else: preprocessors = preprocessors for preprocessor in",
"return value if cast_to is not None: handler = self.cast_handlers.get(cast_to, cast_to) if not",
"= [] if preprocessors is None: preprocessors = [] self.default_secret_sources = secret_sources self.default_cast_handlers",
"= self._preprocess(value, preprocessors) value = self._cast_to(value, cast_to, default) if cache_result: self._cache[name] = value",
"{} def reset(self): self.reset_secret_sources() self.reset_cast_handlers() self.reset_preprocessors() self.clear_cache() def get( self, name, default=NoDefault, *,",
"value = self._get_from_source(name, default, source) value = self._preprocess(value, preprocessors) value = self._cast_to(value, cast_to,",
"= {} def reset(self): self.reset_secret_sources() self.reset_cast_handlers() self.reset_preprocessors() self.clear_cache() def get( self, name, default=NoDefault,",
"if no_cache is False and name in self._cache: return self._cache[name] value = self._get_from_source(name,",
"def clear_cache(self): self._cache = {} def reset(self): self.reset_secret_sources() self.reset_cast_handlers() self.reset_preprocessors() self.clear_cache() def get(",
"NoDefault: pass DEFAULT_SECRET_SOURCES = [ EnvironmentVariableSecretSource() ] DEFAULT_CAST_HANDLERS = { bool: bool_cast_handler, }",
"import bool_cast_handler from .exceptions import CastHandlerMissingError from .exceptions import SecretMissingError from .exceptions import",
"self.reset_cast_handlers() self.reset_preprocessors() self.clear_cache() def get( self, name, default=NoDefault, *, source=None, preprocessors=None, cast_to=None, no_cache=False,",
"if source is not None: return source.get(name) if not self.secret_sources: raise SecretSourceMissing for",
"no_cache is False and name in self._cache: return self._cache[name] value = self._get_from_source(name, default,",
"preprocessors for preprocessor in preprocessors: value = preprocessor(value) return value def _cast_to(self, value,",
"*, source=None, preprocessors=None, cast_to=None, no_cache=False, cache_result=True ): if no_cache is False and name",
"def reset_secret_sources(self): self.secret_sources = list(self.default_secret_sources) def add_cast_handler(self, handler_key, handler): self.cast_handlers[handler_key] = handler def",
"def add_preprocessor(self, fn): self.preprocessors.append(fn) def clear_preprocessors(self): self.preprocessors = [] def reset_preprocessors(self): self.preprocessors =",
"cast_to) if not callable(handler): raise CastHandlerMissingError( f'Cast handler: {handler!r}, is not registered.' )",
"'List[BaseSecretSource]' = [] preprocessors: 'List[Callable[str, str]]' = [] def __init__(self, secret_sources=None, cast_handlers=None, preprocessors=None):",
"preprocessors: value = preprocessor(value) return value def _cast_to(self, value, cast_to, default): if value",
"False and name in self._cache: return self._cache[name] value = self._get_from_source(name, default, source) value",
"if not callable(handler): raise CastHandlerMissingError( f'Cast handler: {handler!r}, is not registered.' ) value",
"] DEFAULT_CAST_HANDLERS = { bool: bool_cast_handler, } class Vault: _cache = {} cast_handlers:",
"'Dict[Callable]' = {} secret_sources: 'List[BaseSecretSource]' = [] preprocessors: 'List[Callable[str, str]]' = [] def",
"DEFAULT_SECRET_SOURCES = [ EnvironmentVariableSecretSource() ] DEFAULT_CAST_HANDLERS = { bool: bool_cast_handler, } class Vault:",
"secret_sources=None, cast_handlers=None, preprocessors=None): if cast_handlers is None: cast_handlers = {} if secret_sources is",
"self, name, default=NoDefault, *, source=None, preprocessors=None, cast_to=None, no_cache=False, cache_result=True ): if no_cache is",
"return self._cache[name] value = self._get_from_source(name, default, source) value = self._preprocess(value, preprocessors) value =",
"clear_cast_handlers(self): self.cast_handlers = {} def reset_cast_handlers(self): self.cast_handlers = {**self.default_cast_handlers} def add_preprocessor(self, fn): self.preprocessors.append(fn)",
"[] preprocessors: 'List[Callable[str, str]]' = [] def __init__(self, secret_sources=None, cast_handlers=None, preprocessors=None): if cast_handlers",
"raise SecretSourceMissing for source in self.secret_sources: try: value = source.get(name) break except SecretMissingError:",
"self.cast_handlers.get(cast_to, cast_to) if not callable(handler): raise CastHandlerMissingError( f'Cast handler: {handler!r}, is not registered.'",
"handler: {handler!r}, is not registered.' ) value = handler(value) return value vault =",
"cast_handlers is None: cast_handlers = {} if secret_sources is None: secret_sources = []",
"preprocessors=None): if cast_handlers is None: cast_handlers = {} if secret_sources is None: secret_sources",
"= value return value def _get_from_source(self, name, default, source): if source is not",
"= [] preprocessors: 'List[Callable[str, str]]' = [] def __init__(self, secret_sources=None, cast_handlers=None, preprocessors=None): if",
"self.reset_preprocessors() self.clear_cache() def get( self, name, default=NoDefault, *, source=None, preprocessors=None, cast_to=None, no_cache=False, cache_result=True",
"= preprocessors self.reset() def add_secret_source(self, source: 'BaseSecretSource'): if source in self.secret_sources: return self.secret_sources.append(source)",
"= secret_sources self.default_cast_handlers = cast_handlers self.default_preprocessors = preprocessors self.reset() def add_secret_source(self, source: 'BaseSecretSource'):",
"source=None, preprocessors=None, cast_to=None, no_cache=False, cache_result=True ): if no_cache is False and name in",
"DEFAULT_CAST_HANDLERS = { bool: bool_cast_handler, } class Vault: _cache = {} cast_handlers: 'Dict[Callable]'",
"def __init__(self, secret_sources=None, cast_handlers=None, preprocessors=None): if cast_handlers is None: cast_handlers = {} if",
"[] def reset_secret_sources(self): self.secret_sources = list(self.default_secret_sources) def add_cast_handler(self, handler_key, handler): self.cast_handlers[handler_key] = handler",
"in self.secret_sources: try: value = source.get(name) break except SecretMissingError: pass else: if default",
"self.secret_sources: try: value = source.get(name) break except SecretMissingError: pass else: if default is",
"return self.secret_sources.append(source) def clear_secret_sources(self): self.secret_sources = [] def reset_secret_sources(self): self.secret_sources = list(self.default_secret_sources) def",
".secret_sources import EnvironmentVariableSecretSource class NoDefault: pass DEFAULT_SECRET_SOURCES = [ EnvironmentVariableSecretSource() ] DEFAULT_CAST_HANDLERS =",
"if preprocessors is None: preprocessors = self.preprocessors else: preprocessors = preprocessors for preprocessor",
"preprocessor(value) return value def _cast_to(self, value, cast_to, default): if value is default: return",
"if not self.secret_sources: raise SecretSourceMissing for source in self.secret_sources: try: value = source.get(name)",
"typing import List, Dict, Callable from .cast_handlers import bool_cast_handler from .exceptions import CastHandlerMissingError",
"secret_sources self.default_cast_handlers = cast_handlers self.default_preprocessors = preprocessors self.reset() def add_secret_source(self, source: 'BaseSecretSource'): if",
"raise CastHandlerMissingError( f'Cast handler: {handler!r}, is not registered.' ) value = handler(value) return",
"cast_to, default): if value is default: return value if cast_to is not None:",
"self.secret_sources = list(self.default_secret_sources) def add_cast_handler(self, handler_key, handler): self.cast_handlers[handler_key] = handler def clear_cast_handlers(self): self.cast_handlers",
"self.reset_secret_sources() self.reset_cast_handlers() self.reset_preprocessors() self.clear_cache() def get( self, name, default=NoDefault, *, source=None, preprocessors=None, cast_to=None,",
"is not registered.' ) value = handler(value) return value vault = Vault(DEFAULT_SECRET_SOURCES, DEFAULT_CAST_HANDLERS)",
"from .secret_sources import BaseSecretSource from .secret_sources import EnvironmentVariableSecretSource class NoDefault: pass DEFAULT_SECRET_SOURCES =",
"def _cast_to(self, value, cast_to, default): if value is default: return value if cast_to",
"class Vault: _cache = {} cast_handlers: 'Dict[Callable]' = {} secret_sources: 'List[BaseSecretSource]' = []",
"= preprocessor(value) return value def _cast_to(self, value, cast_to, default): if value is default:",
"import BaseSecretSource from .secret_sources import EnvironmentVariableSecretSource class NoDefault: pass DEFAULT_SECRET_SOURCES = [ EnvironmentVariableSecretSource()",
"handler): self.cast_handlers[handler_key] = handler def clear_cast_handlers(self): self.cast_handlers = {} def reset_cast_handlers(self): self.cast_handlers =",
"def clear_cast_handlers(self): self.cast_handlers = {} def reset_cast_handlers(self): self.cast_handlers = {**self.default_cast_handlers} def add_preprocessor(self, fn):",
"if cache_result: self._cache[name] = value return value def _get_from_source(self, name, default, source): if",
"if value is default: return value if cast_to is not None: handler =",
"{**self.default_cast_handlers} def add_preprocessor(self, fn): self.preprocessors.append(fn) def clear_preprocessors(self): self.preprocessors = [] def reset_preprocessors(self): self.preprocessors"
] |
[
"-*- coding: utf-8 -*- \"\"\" Demo showing how km_dict and insegtannotator may be",
"print('Loading image') filename = '../data/glass.png' image = skimage.io.imread(filename) #%% EXAMPLE 2: nerve fibres",
"= 35000 normalization = False image_float = image.astype(np.float)/255 # Build tree T =",
"label_image = np.zeros((r,c,l)) for k in range(number_repetitions): for i in range(1,l): label_image[:,:,i] =",
"# Dictionary P = km_dict.dictprob_to_improb(A, D, patch_size) # Probability map labels = np.argmax(P,axis=2)",
"sys import insegtannotator import skimage.io import skimage.data import km_dict import numpy as np",
"i).astype(float) D = km_dict.improb_to_dictprob(A, label_image, number_nodes, patch_size) # Dictionary P = km_dict.dictprob_to_improb(A, D,",
"be used together for interactive segmentation. @author: vand and abda \"\"\" import sys",
"5 number_layers = 5 number_training_patches = 35000 normalization = False image_float = image.astype(np.float)/255",
"print('Loading image') filename = '../data/nerve_im_scale.png' image = skimage.io.imread(filename) #%% COMMON PART patch_size =",
"in range(number_repetitions): for i in range(1,l): label_image[:,:,i] = (labels == i).astype(float) D =",
"def processing_function(labels): r,c = labels.shape l = np.max(labels)+1 label_image = np.zeros((r,c,l)) for k",
"normalization = False image_float = image.astype(np.float)/255 # Build tree T = km_dict.build_km_tree(image_float, patch_size,",
"numpy as np #%% EXAMPLE 1: glass fibres ## loading image print('Loading image')",
"image_float = image.astype(np.float)/255 # Build tree T = km_dict.build_km_tree(image_float, patch_size, branching_factor, number_training_patches, number_layers,",
"number_nodes, patch_size) # Dictionary P = km_dict.dictprob_to_improb(A, D, patch_size) # Probability map labels",
"= km_dict.dictprob_to_improb(A, D, patch_size) # Probability map labels = np.argmax(P,axis=2) # Segmentation return",
"segmentation. @author: vand and abda \"\"\" import sys import insegtannotator import skimage.io import",
"import numpy as np #%% EXAMPLE 1: glass fibres ## loading image print('Loading",
"# Segmentation return labels print('Showtime') # showtime app = insegtannotator.PyQt5.QtWidgets.QApplication([]) ex = insegtannotator.InSegtAnnotator(image,",
"# number of repetitions for updating the segmentation number_repetitions = 2 def processing_function(labels):",
"== i).astype(float) D = km_dict.improb_to_dictprob(A, label_image, number_nodes, patch_size) # Dictionary P = km_dict.dictprob_to_improb(A,",
"interactive segmentation. @author: vand and abda \"\"\" import sys import insegtannotator import skimage.io",
"fibres ## loading image print('Loading image') filename = '../data/nerve_im_scale.png' image = skimage.io.imread(filename) #%%",
"# Build tree T = km_dict.build_km_tree(image_float, patch_size, branching_factor, number_training_patches, number_layers, normalization) # Search",
"number of repetitions for updating the segmentation number_repetitions = 2 def processing_function(labels): r,c",
"T = km_dict.build_km_tree(image_float, patch_size, branching_factor, number_training_patches, number_layers, normalization) # Search km-tree and get",
"= labels.shape l = np.max(labels)+1 label_image = np.zeros((r,c,l)) for k in range(number_repetitions): for",
"D = km_dict.improb_to_dictprob(A, label_image, number_nodes, patch_size) # Dictionary P = km_dict.dictprob_to_improb(A, D, patch_size)",
"EXAMPLE 2: nerve fibres ## loading image print('Loading image') filename = '../data/nerve_im_scale.png' image",
"loading image print('Loading image') filename = '../data/nerve_im_scale.png' image = skimage.io.imread(filename) #%% COMMON PART",
"get assignment A, number_nodes = km_dict.search_km_tree(image_float, T, branching_factor, normalization) # number of repetitions",
"'../data/glass.png' image = skimage.io.imread(filename) #%% EXAMPLE 2: nerve fibres ## loading image print('Loading",
"Search km-tree and get assignment A, number_nodes = km_dict.search_km_tree(image_float, T, branching_factor, normalization) #",
"number_training_patches = 35000 normalization = False image_float = image.astype(np.float)/255 # Build tree T",
"branching_factor, normalization) # number of repetitions for updating the segmentation number_repetitions = 2",
"branching_factor = 5 number_layers = 5 number_training_patches = 35000 normalization = False image_float",
"image') filename = '../data/glass.png' image = skimage.io.imread(filename) #%% EXAMPLE 2: nerve fibres ##",
"= skimage.io.imread(filename) #%% COMMON PART patch_size = 11 branching_factor = 5 number_layers =",
"image print('Loading image') filename = '../data/nerve_im_scale.png' image = skimage.io.imread(filename) #%% COMMON PART patch_size",
"km_dict.build_km_tree(image_float, patch_size, branching_factor, number_training_patches, number_layers, normalization) # Search km-tree and get assignment A,",
"## loading image print('Loading image') filename = '../data/nerve_im_scale.png' image = skimage.io.imread(filename) #%% COMMON",
"np.max(labels)+1 label_image = np.zeros((r,c,l)) for k in range(number_repetitions): for i in range(1,l): label_image[:,:,i]",
"used together for interactive segmentation. @author: vand and abda \"\"\" import sys import",
"= 5 number_layers = 5 number_training_patches = 35000 normalization = False image_float =",
"coding: utf-8 -*- \"\"\" Demo showing how km_dict and insegtannotator may be used",
"# Search km-tree and get assignment A, number_nodes = km_dict.search_km_tree(image_float, T, branching_factor, normalization)",
"import insegtannotator import skimage.io import skimage.data import km_dict import numpy as np #%%",
"patch_size) # Probability map labels = np.argmax(P,axis=2) # Segmentation return labels print('Showtime') #",
"python3 # -*- coding: utf-8 -*- \"\"\" Demo showing how km_dict and insegtannotator",
"tree T = km_dict.build_km_tree(image_float, patch_size, branching_factor, number_training_patches, number_layers, normalization) # Search km-tree and",
"labels = np.argmax(P,axis=2) # Segmentation return labels print('Showtime') # showtime app = insegtannotator.PyQt5.QtWidgets.QApplication([])",
"= skimage.io.imread(filename) #%% EXAMPLE 2: nerve fibres ## loading image print('Loading image') filename",
"# -*- coding: utf-8 -*- \"\"\" Demo showing how km_dict and insegtannotator may",
"np.argmax(P,axis=2) # Segmentation return labels print('Showtime') # showtime app = insegtannotator.PyQt5.QtWidgets.QApplication([]) ex =",
"normalization) # Search km-tree and get assignment A, number_nodes = km_dict.search_km_tree(image_float, T, branching_factor,",
"Build tree T = km_dict.build_km_tree(image_float, patch_size, branching_factor, number_training_patches, number_layers, normalization) # Search km-tree",
"range(1,l): label_image[:,:,i] = (labels == i).astype(float) D = km_dict.improb_to_dictprob(A, label_image, number_nodes, patch_size) #",
"(labels == i).astype(float) D = km_dict.improb_to_dictprob(A, label_image, number_nodes, patch_size) # Dictionary P =",
"normalization) # number of repetitions for updating the segmentation number_repetitions = 2 def",
"number_training_patches, number_layers, normalization) # Search km-tree and get assignment A, number_nodes = km_dict.search_km_tree(image_float,",
"for interactive segmentation. @author: vand and abda \"\"\" import sys import insegtannotator import",
"np #%% EXAMPLE 1: glass fibres ## loading image print('Loading image') filename =",
"EXAMPLE 1: glass fibres ## loading image print('Loading image') filename = '../data/glass.png' image",
"= 5 number_training_patches = 35000 normalization = False image_float = image.astype(np.float)/255 # Build",
"T, branching_factor, normalization) # number of repetitions for updating the segmentation number_repetitions =",
"km-tree and get assignment A, number_nodes = km_dict.search_km_tree(image_float, T, branching_factor, normalization) # number",
"repetitions for updating the segmentation number_repetitions = 2 def processing_function(labels): r,c = labels.shape",
"range(number_repetitions): for i in range(1,l): label_image[:,:,i] = (labels == i).astype(float) D = km_dict.improb_to_dictprob(A,",
"= np.max(labels)+1 label_image = np.zeros((r,c,l)) for k in range(number_repetitions): for i in range(1,l):",
"map labels = np.argmax(P,axis=2) # Segmentation return labels print('Showtime') # showtime app =",
"P = km_dict.dictprob_to_improb(A, D, patch_size) # Probability map labels = np.argmax(P,axis=2) # Segmentation",
"fibres ## loading image print('Loading image') filename = '../data/glass.png' image = skimage.io.imread(filename) #%%",
"number_repetitions = 2 def processing_function(labels): r,c = labels.shape l = np.max(labels)+1 label_image =",
"as np #%% EXAMPLE 1: glass fibres ## loading image print('Loading image') filename",
"import skimage.io import skimage.data import km_dict import numpy as np #%% EXAMPLE 1:",
"= 11 branching_factor = 5 number_layers = 5 number_training_patches = 35000 normalization =",
"utf-8 -*- \"\"\" Demo showing how km_dict and insegtannotator may be used together",
"km_dict.search_km_tree(image_float, T, branching_factor, normalization) # number of repetitions for updating the segmentation number_repetitions",
"PART patch_size = 11 branching_factor = 5 number_layers = 5 number_training_patches = 35000",
"image print('Loading image') filename = '../data/glass.png' image = skimage.io.imread(filename) #%% EXAMPLE 2: nerve",
"= np.argmax(P,axis=2) # Segmentation return labels print('Showtime') # showtime app = insegtannotator.PyQt5.QtWidgets.QApplication([]) ex",
"np.zeros((r,c,l)) for k in range(number_repetitions): for i in range(1,l): label_image[:,:,i] = (labels ==",
"and get assignment A, number_nodes = km_dict.search_km_tree(image_float, T, branching_factor, normalization) # number of",
"i in range(1,l): label_image[:,:,i] = (labels == i).astype(float) D = km_dict.improb_to_dictprob(A, label_image, number_nodes,",
"insegtannotator may be used together for interactive segmentation. @author: vand and abda \"\"\"",
"Probability map labels = np.argmax(P,axis=2) # Segmentation return labels print('Showtime') # showtime app",
"image = skimage.io.imread(filename) #%% COMMON PART patch_size = 11 branching_factor = 5 number_layers",
"image.astype(np.float)/255 # Build tree T = km_dict.build_km_tree(image_float, patch_size, branching_factor, number_training_patches, number_layers, normalization) #",
"## loading image print('Loading image') filename = '../data/glass.png' image = skimage.io.imread(filename) #%% EXAMPLE",
"for updating the segmentation number_repetitions = 2 def processing_function(labels): r,c = labels.shape l",
"image') filename = '../data/nerve_im_scale.png' image = skimage.io.imread(filename) #%% COMMON PART patch_size = 11",
"updating the segmentation number_repetitions = 2 def processing_function(labels): r,c = labels.shape l =",
"and abda \"\"\" import sys import insegtannotator import skimage.io import skimage.data import km_dict",
"k in range(number_repetitions): for i in range(1,l): label_image[:,:,i] = (labels == i).astype(float) D",
"processing_function(labels): r,c = labels.shape l = np.max(labels)+1 label_image = np.zeros((r,c,l)) for k in",
"= 2 def processing_function(labels): r,c = labels.shape l = np.max(labels)+1 label_image = np.zeros((r,c,l))",
"patch_size = 11 branching_factor = 5 number_layers = 5 number_training_patches = 35000 normalization",
"\"\"\" Demo showing how km_dict and insegtannotator may be used together for interactive",
"number_nodes = km_dict.search_km_tree(image_float, T, branching_factor, normalization) # number of repetitions for updating the",
"Segmentation return labels print('Showtime') # showtime app = insegtannotator.PyQt5.QtWidgets.QApplication([]) ex = insegtannotator.InSegtAnnotator(image, processing_function)",
"nerve fibres ## loading image print('Loading image') filename = '../data/nerve_im_scale.png' image = skimage.io.imread(filename)",
"label_image, number_nodes, patch_size) # Dictionary P = km_dict.dictprob_to_improb(A, D, patch_size) # Probability map",
"COMMON PART patch_size = 11 branching_factor = 5 number_layers = 5 number_training_patches =",
"= image.astype(np.float)/255 # Build tree T = km_dict.build_km_tree(image_float, patch_size, branching_factor, number_training_patches, number_layers, normalization)",
"skimage.io.imread(filename) #%% EXAMPLE 2: nerve fibres ## loading image print('Loading image') filename =",
"segmentation number_repetitions = 2 def processing_function(labels): r,c = labels.shape l = np.max(labels)+1 label_image",
"l = np.max(labels)+1 label_image = np.zeros((r,c,l)) for k in range(number_repetitions): for i in",
"skimage.io import skimage.data import km_dict import numpy as np #%% EXAMPLE 1: glass",
"'../data/nerve_im_scale.png' image = skimage.io.imread(filename) #%% COMMON PART patch_size = 11 branching_factor = 5",
"= km_dict.search_km_tree(image_float, T, branching_factor, normalization) # number of repetitions for updating the segmentation",
"in range(1,l): label_image[:,:,i] = (labels == i).astype(float) D = km_dict.improb_to_dictprob(A, label_image, number_nodes, patch_size)",
"35000 normalization = False image_float = image.astype(np.float)/255 # Build tree T = km_dict.build_km_tree(image_float,",
"= np.zeros((r,c,l)) for k in range(number_repetitions): for i in range(1,l): label_image[:,:,i] = (labels",
"5 number_training_patches = 35000 normalization = False image_float = image.astype(np.float)/255 # Build tree",
"and insegtannotator may be used together for interactive segmentation. @author: vand and abda",
"filename = '../data/glass.png' image = skimage.io.imread(filename) #%% EXAMPLE 2: nerve fibres ## loading",
"D, patch_size) # Probability map labels = np.argmax(P,axis=2) # Segmentation return labels print('Showtime')",
"number_layers = 5 number_training_patches = 35000 normalization = False image_float = image.astype(np.float)/255 #",
"Dictionary P = km_dict.dictprob_to_improb(A, D, patch_size) # Probability map labels = np.argmax(P,axis=2) #",
"# Probability map labels = np.argmax(P,axis=2) # Segmentation return labels print('Showtime') # showtime",
"= km_dict.build_km_tree(image_float, patch_size, branching_factor, number_training_patches, number_layers, normalization) # Search km-tree and get assignment",
"= km_dict.improb_to_dictprob(A, label_image, number_nodes, patch_size) # Dictionary P = km_dict.dictprob_to_improb(A, D, patch_size) #",
"labels print('Showtime') # showtime app = insegtannotator.PyQt5.QtWidgets.QApplication([]) ex = insegtannotator.InSegtAnnotator(image, processing_function) app.exec() sys.exit()",
"#%% EXAMPLE 2: nerve fibres ## loading image print('Loading image') filename = '../data/nerve_im_scale.png'",
"loading image print('Loading image') filename = '../data/glass.png' image = skimage.io.imread(filename) #%% EXAMPLE 2:",
"for i in range(1,l): label_image[:,:,i] = (labels == i).astype(float) D = km_dict.improb_to_dictprob(A, label_image,",
"for k in range(number_repetitions): for i in range(1,l): label_image[:,:,i] = (labels == i).astype(float)",
"skimage.data import km_dict import numpy as np #%% EXAMPLE 1: glass fibres ##",
"assignment A, number_nodes = km_dict.search_km_tree(image_float, T, branching_factor, normalization) # number of repetitions for",
"import sys import insegtannotator import skimage.io import skimage.data import km_dict import numpy as",
"2: nerve fibres ## loading image print('Loading image') filename = '../data/nerve_im_scale.png' image =",
"2 def processing_function(labels): r,c = labels.shape l = np.max(labels)+1 label_image = np.zeros((r,c,l)) for",
"km_dict.improb_to_dictprob(A, label_image, number_nodes, patch_size) # Dictionary P = km_dict.dictprob_to_improb(A, D, patch_size) # Probability",
"#%% EXAMPLE 1: glass fibres ## loading image print('Loading image') filename = '../data/glass.png'",
"may be used together for interactive segmentation. @author: vand and abda \"\"\" import",
"number_layers, normalization) # Search km-tree and get assignment A, number_nodes = km_dict.search_km_tree(image_float, T,",
"Demo showing how km_dict and insegtannotator may be used together for interactive segmentation.",
"= '../data/glass.png' image = skimage.io.imread(filename) #%% EXAMPLE 2: nerve fibres ## loading image",
"False image_float = image.astype(np.float)/255 # Build tree T = km_dict.build_km_tree(image_float, patch_size, branching_factor, number_training_patches,",
"label_image[:,:,i] = (labels == i).astype(float) D = km_dict.improb_to_dictprob(A, label_image, number_nodes, patch_size) # Dictionary",
"abda \"\"\" import sys import insegtannotator import skimage.io import skimage.data import km_dict import",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Demo showing how km_dict and",
"km_dict import numpy as np #%% EXAMPLE 1: glass fibres ## loading image",
"showing how km_dict and insegtannotator may be used together for interactive segmentation. @author:",
"@author: vand and abda \"\"\" import sys import insegtannotator import skimage.io import skimage.data",
"labels.shape l = np.max(labels)+1 label_image = np.zeros((r,c,l)) for k in range(number_repetitions): for i",
"the segmentation number_repetitions = 2 def processing_function(labels): r,c = labels.shape l = np.max(labels)+1",
"11 branching_factor = 5 number_layers = 5 number_training_patches = 35000 normalization = False",
"return labels print('Showtime') # showtime app = insegtannotator.PyQt5.QtWidgets.QApplication([]) ex = insegtannotator.InSegtAnnotator(image, processing_function) app.exec()",
"image = skimage.io.imread(filename) #%% EXAMPLE 2: nerve fibres ## loading image print('Loading image')",
"1: glass fibres ## loading image print('Loading image') filename = '../data/glass.png' image =",
"branching_factor, number_training_patches, number_layers, normalization) # Search km-tree and get assignment A, number_nodes =",
"= (labels == i).astype(float) D = km_dict.improb_to_dictprob(A, label_image, number_nodes, patch_size) # Dictionary P",
"insegtannotator import skimage.io import skimage.data import km_dict import numpy as np #%% EXAMPLE",
"filename = '../data/nerve_im_scale.png' image = skimage.io.imread(filename) #%% COMMON PART patch_size = 11 branching_factor",
"how km_dict and insegtannotator may be used together for interactive segmentation. @author: vand",
"-*- \"\"\" Demo showing how km_dict and insegtannotator may be used together for",
"glass fibres ## loading image print('Loading image') filename = '../data/glass.png' image = skimage.io.imread(filename)",
"km_dict and insegtannotator may be used together for interactive segmentation. @author: vand and",
"km_dict.dictprob_to_improb(A, D, patch_size) # Probability map labels = np.argmax(P,axis=2) # Segmentation return labels",
"= '../data/nerve_im_scale.png' image = skimage.io.imread(filename) #%% COMMON PART patch_size = 11 branching_factor =",
"patch_size) # Dictionary P = km_dict.dictprob_to_improb(A, D, patch_size) # Probability map labels =",
"\"\"\" import sys import insegtannotator import skimage.io import skimage.data import km_dict import numpy",
"import skimage.data import km_dict import numpy as np #%% EXAMPLE 1: glass fibres",
"#%% COMMON PART patch_size = 11 branching_factor = 5 number_layers = 5 number_training_patches",
"patch_size, branching_factor, number_training_patches, number_layers, normalization) # Search km-tree and get assignment A, number_nodes",
"of repetitions for updating the segmentation number_repetitions = 2 def processing_function(labels): r,c =",
"vand and abda \"\"\" import sys import insegtannotator import skimage.io import skimage.data import",
"r,c = labels.shape l = np.max(labels)+1 label_image = np.zeros((r,c,l)) for k in range(number_repetitions):",
"import km_dict import numpy as np #%% EXAMPLE 1: glass fibres ## loading",
"skimage.io.imread(filename) #%% COMMON PART patch_size = 11 branching_factor = 5 number_layers = 5",
"A, number_nodes = km_dict.search_km_tree(image_float, T, branching_factor, normalization) # number of repetitions for updating",
"together for interactive segmentation. @author: vand and abda \"\"\" import sys import insegtannotator",
"= False image_float = image.astype(np.float)/255 # Build tree T = km_dict.build_km_tree(image_float, patch_size, branching_factor,"
] |
[
"t in h.tetrads] logging.debug(f'Selected chain order: {\" \".join(final_order)} ' f'{\" \".join(map(lambda onz: onz.value,",
"ONZM.from_value(f'{onz}{direction}{plus_minus}') def __classify_by_gba(self) -> List[GbaQuadruplexClassification]: gbas = set() for t in self.tetrads: gba",
"from collections import defaultdict, Counter from dataclasses import dataclass, field from typing import",
"impossible if not all([nt.chi_class in (GlycosidicBond.syn, GlycosidicBond.anti) for nt in self.nucleotides]): return None",
"'aasa': GbaTetradClassification.Va, 'ssas': GbaTetradClassification.Vb, 'assa': GbaTetradClassification.VIa, 'saas': GbaTetradClassification.VIb, 'asss': GbaTetradClassification.VIIa, 'saaa': GbaTetradClassification.VIIb, 'aaaa':",
"{ 'ppp': '1', 'ppl': '2', 'plp': '3', 'lpp': '4', 'pdp': '5', 'lll': '6',",
"without stacking\\n' builder += str(self.tetrads[0]) return builder @dataclass class Analysis: structure2d: Structure2D structure3d:",
"complete2d: bool onz_dict: Dict[BasePair3D, ONZ] = field(init=False) def __post_init__(self): self.onz_dict = {pair: tetrad.onz",
"= self.__classify_by_gba() def reorder_to_match_other_tetrad(self, order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D]): if order == (self.nt1,",
"self.nt1, self.nt4): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse() elif order",
"+1 or -1 counter = Counter(1 if j - i > 0 else",
"n1, n4), (n2, n1, n4, n3)] for nts2 in viable_permutations: score_stacking = [1",
"tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]: # main check if pair.nt1 == first and pair.nt2 ==",
"if conflicts: pair, _ = max(conflicts.items(), key=lambda x: (len(x[1]), x[0].nt1)) removed.append(pair) queue.remove(pair) else:",
"self.structure3d.residues) return list({nt.chain: 0 for nt in sorted(only_nucleic_acids, key=lambda nt: nt.index)}.keys()) def canonical(self)",
"= self.__detect_loop_sign(nt_first, nt_last, tetrad_with_first) if sign is not None: return LoopType.from_value(f'lateral{sign}') return LoopType.diagonal",
"str, str, Dict[Residue3D, int]]: layer1, layer2 = [], [] for tetrad in self.tetrads:",
"self.nucleotides] inner = [nt.innermost_atom for nt in self.nucleotides] return numpy.linalg.norm(center_of_mass(outer) - center_of_mass(inner)) @property",
"tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) helix1 = self.__to_helix(layer1, self.analysis.canonical() if self.complete2d else []) helix2 =",
"if len(self.tetrad_pairs) > 0: self.tetrad_pairs[0].tetrad1.reorder_to_match_5p_3p() for tp in self.tetrad_pairs: order = (tp.stacked[tp.tetrad1.nt1], tp.stacked[tp.tetrad1.nt2],",
"self.tetrad_pairs: order = (tp.stacked[tp.tetrad1.nt1], tp.stacked[tp.tetrad1.nt2], tp.stacked[tp.tetrad1.nt3], tp.stacked[tp.tetrad1.nt4]) tp.tetrad2.reorder_to_match_5p_3p() # this is required to",
"pair tetrad.ions_outside[residue] = ions def __generate_twoline_dotbracket(self) -> Tuple[str, str, str, Dict[Residue3D, int]]: layer1,",
"self.pair_23, self.pair_34, self.pair_41 = self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse() elif order == (self.nt1, self.nt4,",
"= candidates[i], candidates[j] if not qi.isdisjoint(qj): qi.update(qj) del candidates[j] changed = True break",
"self.pair_34, self.pair_41, self.pair_12 elif nmin == nk: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt3,",
"the tract to check what pairs with nt_first for nt in tract_with_last.nucleotides: if",
"GbaTetradClassification.VIb, 'asss': GbaTetradClassification.VIIa, 'saaa': GbaTetradClassification.VIIb, 'aaaa': GbaTetradClassification.VIIIa, 'ssss': GbaTetradClassification.VIIIb } if fingerprint not",
"t.pair_34, t.pair_41]: c1 = p.nt1.chain c2 = p.nt2.chain if c1 != c2 and",
"+ string.ascii_lowercase dotbracket = dict() for pair, order in orders.items(): nt1, nt2 =",
"= self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() if not self.no_reorder: self.__find_best_chain_order() self.sequence, self.line1, self.line2, self.shifts",
"in h.tetrads: for p in [t.pair_12, t.pair_23, t.pair_34, t.pair_41]: c1 = p.nt1.chain c2",
"GbaTetradClassification.IIIa, 'sass': GbaTetradClassification.IIIb, 'aaas': GbaTetradClassification.IVa, 'sssa': GbaTetradClassification.IVb, 'aasa': GbaTetradClassification.Va, 'ssas': GbaTetradClassification.Vb, 'assa': GbaTetradClassification.VIa,",
"n3), (n1, n4, n3, n2), (n4, n3, n2, n1), (n3, n2, n1, n4),",
"pair.nt2]) dotbracket[nt1] = opening[order] dotbracket[nt2] = closing[order] sequence = '' structure = ''",
"self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif nmin == nk: self.nt1,",
"nts = list(filter(lambda nt: nprev.index < nt.index < ncur.index, self.structure3d.residues)) loop_type = self.__detect_loop_type(nprev,",
"in self.nucleotides] return numpy.linalg.norm(center_of_mass(outer) - center_of_mass(inner)) @property def nucleotides(self) -> Tuple[Residue3D, Residue3D, Residue3D,",
"# ONZ and da Silva's classification are valid in 5'-3' order self.onz =",
"(self.nt2, self.nt3, self.nt4, self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12",
"\".join(map(lambda c: c.value, classifications))}') onz_score = sum(c.score() for c in classifications) chain_order_score =",
"groups = [] for candidate in candidates: if any([group.issuperset(candidate) for group in groups]):",
"l, self.base_pair_dict): pair_12 = self.base_pair_dict[(i, j)] pair_23 = self.base_pair_dict[(j, k)] pair_34 = self.base_pair_dict[(k,",
"classifications))}') onz_score = sum(c.score() for c in classifications) chain_order_score = self.__chain_order_score(permutation) score =",
"tract_with_last = self.__find_tract_with_nt(nt_last) if tract_with_last is not None: # search along the tract",
"lw_i, lw_j in ((lw1, lw4), (lw2, lw1), (lw3, lw2), (lw4, lw3)): if lw_i.name[1]",
"for h in self.helices for t in h.tetrads] logging.debug( f'Checking reorder: {\" \".join(permutation)}",
"(4 - stacking_mismatch): nts1, nts2 = self.tetrad_scores[ti][tj][1:] stacked = {nts1[i]: nts2[i] for i",
"in self.nucleotides]): return None # this will create a 4-letter string made of",
"self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() if not self.no_reorder: self.__find_best_chain_order() self.sequence, self.line1, self.line2, self.shifts =",
"in self.tetrad_pairs: order = (tp.stacked[tp.tetrad1.nt1], tp.stacked[tp.tetrad1.nt2], tp.stacked[tp.tetrad1.nt3], tp.stacked[tp.tetrad1.nt4]) tp.tetrad2.reorder_to_match_5p_3p() # this is required",
"str, suffix: str): fasta = tempfile.NamedTemporaryFile('w+', suffix='.fasta') fasta.write(f'>{prefix}-{suffix}\\n') fasta.write(self.analysis.sequence) fasta.flush() layer1, layer2 =",
"self.pair_12 elif order == (self.nt3, self.nt4, self.nt1, self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41 =",
"fasta = tempfile.NamedTemporaryFile('w+', suffix='.fasta') fasta.write(f'>{prefix}-{suffix}\\n') fasta.write(self.analysis.sequence) fasta.flush() layer1, layer2 = [], [] for",
"for pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]} def visualize(self, prefix: str, suffix: str):",
"best_order = tj.nucleotides n1, n2, n3, n4 = tj.nucleotides viable_permutations = [(n1, n2,",
"= self.__find_tetrads(True) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() def __group_related_chains(self)",
"= [atom.coordinates() for atom in atoms] xs = (coord[0] for coord in coords)",
"builder += str(self.tetrads[0]) return builder @dataclass class Analysis: structure2d: Structure2D structure3d: Structure3D strict:",
"filter(lambda x: x not in (i, j), self.base_pair_graph[j]): for l in filter(lambda x:",
"nt.index < ncur.index, self.structure3d.residues)) loop_type = self.__detect_loop_type(nprev, ncur) loops.append(Loop(nts, loop_type)) return loops def",
"if self.complete2d else []) helix2 = self.__to_helix(layer2) currdir = os.path.dirname(os.path.realpath(__file__)) output_pdf = f'{prefix}-{suffix}.pdf'",
"self.nt1, self.nt2, self.nt3, self.nt4 = self.nt2, self.nt3, self.nt4, self.nt1 self.pair_12, self.pair_23, self.pair_34, self.pair_41",
"self.base_pair_graph[x], self.base_pair_graph[k]): if Tetrad.is_valid(i, j, k, l, self.base_pair_dict): pair_12 = self.base_pair_dict[(i, j)] pair_23",
"\".join(permutation)} {\" \".join(map(lambda c: c.value, classifications))}') onz_score = sum(c.score() for c in classifications)",
"nt: nt.is_nucleotide, self.structure3d.residues), key=lambda nt: nt.index): if chain and chain != nt.chain: sequence",
"if pair.score() < pair.reverse().score(): return '-' return '+' # reverse check if pair.nt1",
"Residue3D], BasePair3D]) -> bool: lw1 = pair_dictionary[(nt1, nt2)].lw lw2 = pair_dictionary[(nt2, nt3)].lw lw3",
"float: t1 = self.tetrad1.outer_and_inner_atoms() t2 = self.tetrad2.outer_and_inner_atoms() return numpy.linalg.norm(center_of_mass(t1) - center_of_mass(t2)) def __calculate_twist(self)",
"'lpl': '8', 'pll': '9', 'pdl': '10', 'ldl': '11', 'dpd': '12', 'ldp': '13' }",
"return None # this will create a 4-letter string made of 's' for",
"between {nt_first} and {nt_last}') return None if tetrad_with_first == tetrad_with_last: # diagonal or",
"self.nt1, self.nt2, self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34 elif",
"for x in (ni, nj, nk, nl)) while ni != 0: ni, nj,",
"ions_channel[min_tetrad].append(ion) continue min_distance = math.inf min_tetrad = self.tetrads[0] min_nt = min_tetrad.nt1 for tetrad",
"builder += 'single tetrad without stacking\\n' builder += str(self.tetrads[0]) return builder @dataclass class",
"self.nt2, self.nt3, self.nt4 = order def __classify_onz(self) -> ONZ: # transform into (0,",
"0: return [Quadruplex(self.tetrads, [], self.structure3d)] quadruplexes = list() tetrads = list() for tetrad",
"if distance < min_distance: min_distance = distance min_tetrad = tetrad min_nt = nt",
"t in self.tetrads]): return None counter = Counter([t.onz.value[0] for t in self.tetrads]) onz,",
"self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23 else: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt4,",
"def check_pair(tp: TetradPair) -> bool: return check_tetrad(tp.tetrad1) and check_tetrad(tp.tetrad2) return list(filter(check_pair, self.tetrad_pairs)) def",
"self.nt4): pass elif order == (self.nt2, self.nt3, self.nt4, self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41",
"n4, n1, n2), (n4, n1, n2, n3), (n1, n4, n3, n2), (n4, n3,",
"return frozenset(self.nucleotides).isdisjoint(frozenset(other.nucleotides)) def center(self) -> numpy.ndarray: return center_of_mass(self.outer_and_inner_atoms()) def outer_and_inner_atoms(self) -> List[Atom3D]: return",
"in self.tetrads: if not any([tetrad in helix.tetrads for helix in helices]): helices.append(Helix([tetrad], [],",
"nt: nt.index, self.tetrad2_nts_best_order)) # count directions 5' -> 3' as +1 or -1",
"if permutation < best_permutation: best_permutation = permutation final_order.extend(best_permutation) if len(final_order) > 1: self.__reorder_chains(final_order)",
"!= c2 and c1 in chain_order and c2 in chain_order: chain_pairs.append([c1, c2]) sum_sq",
"in self.structure3d.residues: if nt.chain not in chain_order: nt.index = i i += 1",
"nt2.index) == 1 tetrad_scores = defaultdict(dict) for ti, tj in itertools.combinations(self.tetrads, 2): nts1",
"float = field(init=False) def __post_init__(self): self.tetrad2_nts_best_order = ( self.stacked[self.tetrad1.nt1], self.stacked[self.tetrad1.nt2], self.stacked[self.tetrad1.nt3], self.stacked[self.tetrad1.nt4] )",
"helix_tetrads.append(tj) helix_tetrad_pairs.append(tp) else: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) helix_tetrads = [ti, tj] helix_tetrad_pairs = [tp]",
"self.strict) self.stacking_graph = self.structure3d.stacking_graph(self.structure2d) self.tetrads = self.__find_tetrads(self.no_reorder) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch)",
"Dict[Residue3D, List[Residue3D]] = field(init=False) base_pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = field(init=False) stacking_graph: Dict[Residue3D, List[Residue3D]]",
"chain_groups = self.__group_related_chains() final_order = [] for chains in chain_groups: best_permutation, best_score =",
"if tetrad.chains().isdisjoint(tetrads[-1].chains()): quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) tetrads = list() tetrads.append(tetrad) quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) return",
"{self.gba_class.value} ' \\ f'planarity={round(self.planarity_deviation, 2)} ' \\ f'{self.__ions_channel_str()} ' \\ f'{self.__ions_outside_str()}\\n' def chains(self)",
"visualization, reason:\\n {run.stderr.decode()}') def __to_helix(self, layer: List[BasePair3D], canonical: Optional[List[BasePair3D]] = None) -> tempfile.NamedTemporaryFile():",
"0 else -1 for i, j in zip(indices1, indices2)) direction, count = counter.most_common()[0]",
"self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif order == (self.nt3, self.nt4, self.nt1,",
"in self.graph: for j in filter(lambda x: x != i, self.graph[i]): for k",
"(n3, n4, n1, n2), (n4, n1, n2, n3), (n1, n4, n3, n2), (n4,",
"candidates: if any([group.issuperset(candidate) for group in groups]): continue groups.append(candidate) return sorted([sorted(group) for group",
"self.nt4, self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif order",
"or 'a' for anti fingerprint = ''.join([nt.chi_class.value[0] for nt in self.nucleotides]) # this",
"it is too far from any tetrad (distance={min_distance})') for tetrad, ions in ions_channel.items():",
"def __hash__(self): return hash(frozenset([self.nt1, self.nt2, self.nt3, self.nt4])) def __str__(self): return f' ' \\",
"__classify_by_gba(self) -> List[GbaQuadruplexClassification]: gbas = set() for t in self.tetrads: gba = t.gba_class",
"Quadruplex Folding. Chemistry - A European Journal, 13(35), 9738–9745. https://doi.org/10.1002/chem.200701255 :return: Classification according",
"tetrad_nucleotides = sorted([nt for tetrad in self.tetrads for nt in tetrad.nucleotides], key=lambda nt:",
"# search along the tract to check what pairs with nt_first for nt",
"self.tetrads = self.__find_tetrads(self.no_reorder) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() if",
"c: c.value, classifications))}') onz_score = sum(c.score() for c in classifications) chain_order_score = self.__chain_order_score(permutation)",
"[tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]} def visualize(self, prefix: str, suffix: str): fasta = tempfile.NamedTemporaryFile('w+',",
"best_order) tetrad_scores[tj][ti] = (best_score, best_order, nts1) return tetrad_scores def __find_tetrad_pairs(self, stacking_mismatch: int) ->",
"= '*' return ONZM.from_value(f'{onz}{direction}{plus_minus}') def __classify_by_gba(self) -> List[GbaQuadruplexClassification]: gbas = set() for t",
"no_reorder=False) -> List[Tetrad]: # search for a tetrad: i -> j -> k",
"= tj.nucleotides viable_permutations = [(n1, n2, n3, n4), (n2, n3, n4, n1), (n3,",
"if sign is not None: return LoopType.from_value(f'propeller{sign}') logging.warning(f'Failed to classify the loop between",
"= self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() if not self.no_reorder: self.__find_best_chain_order() self.sequence,",
"pair.score() < pair.reverse().score(): return '-' return '+' # reverse check if pair.nt1 ==",
"to recalculate ONZ tp.tetrad2.reorder_to_match_other_tetrad(order) def __chain_order_score(self, chain_order: Tuple[str, ...]) -> int: chain_pairs =",
"\"\"\" See: <NAME>. (2007). Geometric Formalism for DNA Quadruplex Folding. Chemistry - A",
"/ len(coords))) def eltetrado(structure2d: Structure2D, structure3d: Structure3D, strict: bool, no_reorder: bool, stacking_mismatch: int)",
"strict, no_reorder, stacking_mismatch) def has_tetrad(structure2d: Structure2D, structure3d: Structure3D) -> bool: structure = AnalysisSimple(structure2d,",
"sum([max(score_stacking[i], score_sequential[i]) for i in range(4)]) score_sequential = sum(score_sequential) score_stacking = sum(score_stacking) if",
"= self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() else: raise RuntimeError(f'Cannot apply order: {order}') self.nt1, self.nt2,",
"shifts = self.__elimination_conflicts(layer1) _, line2, _ = self.__elimination_conflicts(layer2) return sequence, line1, line2, shifts",
"fingerprint = ''.join([loop.loop_type.value[0] for loop in self.loops]) if fingerprint not in loop_classes: logging.error(f'Unknown",
"set() for residue in self.structure3d.residues: for atom in residue.atoms: if atom.atomName.upper() in metal_atom_names:",
"the same direction return Direction.parallel elif count == 2: # two in +,",
"self.structure3d.base_pairs(self.structure2d) self.base_pair_graph = self.structure3d.base_pair_graph(self.structure2d, self.strict) self.base_pair_dict = self.structure3d.base_pair_dict(self.structure2d, self.strict) self.stacking_graph = self.structure3d.stacking_graph(self.structure2d) self.tetrads",
"order == (self.nt3, self.nt4, self.nt1, self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41,",
"self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse() elif order == (self.nt2, self.nt1, self.nt4, self.nt3): self.pair_12, self.pair_23, self.pair_34,",
"nt.full_name, self.nucleotides))}' @dataclass class Quadruplex: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D onzm: Optional[ONZM]",
"self.pair_34, self.pair_41 = self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse() elif order == (self.nt2, self.nt1, self.nt4,",
"best_score_stacking = 0 best_order = tj.nucleotides n1, n2, n3, n4 = tj.nucleotides viable_permutations",
"[1 if is_next_by_stacking(nts1[i], nts2[i]) else 0 for i in range(4)] score_sequential = [1",
"= True while changed: changed = False for i, j in itertools.combinations(range(len(candidates)), 2):",
"conflicts[pi].append(pj) conflicts[pj].append(pi) if conflicts: pair, _ = max(conflicts.items(), key=lambda x: (len(x[1]), x[0].nt1)) removed.append(pair)",
"not in (i, j, k) and x in self.graph[i], self.graph[k]): if Tetrad.is_valid(i, j,",
"'asss': GbaTetradClassification.VIIa, 'saaa': GbaTetradClassification.VIIb, 'aaaa': GbaTetradClassification.VIIIa, 'ssss': GbaTetradClassification.VIIIb } if fingerprint not in",
"self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23 elif order == (self.nt4, self.nt1, self.nt2, self.nt3):",
"import logging import math import os import string import subprocess import tempfile from",
"self.__classify_by_gba() self.tracts = self.__find_tracts() self.loops = self.__find_loops() self.loop_class = self.__classify_by_loops() def __classify_onzm(self) ->",
"string import subprocess import tempfile from collections import defaultdict, Counter from dataclasses import",
"'\\n' return builder @dataclass class Helix: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D quadruplexes:",
"(1e10, 1e10) if len(chains) > 1: for permutation in itertools.permutations(chains): self.__reorder_chains(permutation) classifications =",
"ONZ] = field(init=False) def __post_init__(self): self.onz_dict = {pair: tetrad.onz for tetrad in self.tetrads",
"GbaQuadruplexClassification[x], gbas)) def __find_tracts(self) -> List[Tract]: tracts = [[self.tetrads[0].nt1], [self.tetrads[0].nt2], [self.tetrads[0].nt3], [self.tetrads[0].nt4]] if",
"= [] for i in self.base_pair_graph: for j in filter(lambda x: x !=",
"recalculate ONZ tp.tetrad2.reorder_to_match_other_tetrad(order) def __chain_order_score(self, chain_order: Tuple[str, ...]) -> int: chain_pairs = []",
"-> List[str]: only_nucleic_acids = filter(lambda nt: nt.is_nucleotide, self.structure3d.residues) return list({nt.chain: 0 for nt",
"in coords) return numpy.array((sum(xs) / len(coords), sum(ys) / len(coords), sum(zs) / len(coords))) def",
"gba is not None: gbas.add(gba.value[:-1]) # discard 'a' or 'b' subvariant roman_numerals =",
"in case of a tie, remove one which has the worst planarity deviation",
"1 + shifts[x], nucleotides.index(y) + 1 + shifts[y] onz = self.onz_dict[pair] helix.write(f'{x}\\t{y}\\t1\\t{onz_value.get(onz, 7)}\\n')",
"Tracts:\\n' for tract in self.tracts: builder += f'{tract}\\n' if self.loops: builder += '\\n",
"= tj if score > best_score: best_score = score best_order = order if",
"outer_and_inner_atoms(self) -> List[Atom3D]: return list(map(lambda residue: residue.outermost_atom, self.nucleotides)) + \\ list(map(lambda residue: residue.innermost_atom,",
"if self.loops: builder += '\\n Loops:\\n' for loop in self.loops: builder += f'{loop}\\n'",
"= self.__calculate_rise() self.twist = self.__calculate_twist() def __determine_direction(self) -> Direction: indices1 = list(map(lambda nt:",
"ion and an atom if min_distance < 3.0: ions_outside[(min_tetrad, min_nt)].append(ion) continue logging.debug(f'Skipping an",
"candidates.add(frozenset([t.nt1.chain, t.nt2.chain, t.nt3.chain, t.nt4.chain])) candidates = [set(c) for c in candidates] changed =",
"nt.is_nucleotide, self.structure3d.residues), key=lambda nt: nt.index): if chain and chain != nt.chain: sequence +=",
"__find_tetrad_pairs(self, stacking_mismatch: int) -> List[TetradPair]: tetrads = list(self.tetrads) best_score = 0 best_order =",
"self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse() elif order == (self.nt2, self.nt1, self.nt4, self.nt3): self.pair_12, self.pair_23,",
"chains = set() for tetrad in tetrads: chains.update(tetrad.chains()) def check_tetrad(t: Tetrad) -> bool:",
"return sequence, structure, shifts def __str__(self): builder = f'Chain order: {\" \".join(self.__chain_order())}\\n' for",
"def __post_init__(self): self.onz_dict = {pair: tetrad.onz for tetrad in self.tetrads for pair in",
"TetradPair: tetrad1: Tetrad tetrad2: Tetrad stacked: Dict[Residue3D, Residue3D] tetrad2_nts_best_order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D]",
"{self.nt4.full_name} ' \\ f'{self.pair_12.lw.value} {self.pair_23.lw.value} {self.pair_34.lw.value} {self.pair_41.lw.value} ' \\ f'{self.onz.value} {self.gba_class.value} ' \\",
"{pair: tetrad.onz for tetrad in self.tetrads for pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]}",
"only_nucleic_acids = filter(lambda nt: nt.is_nucleotide, self.structure3d.residues) return list({nt.chain: 0 for nt in sorted(only_nucleic_acids,",
"order == (self.nt1, self.nt2, self.nt3, self.nt4): pass elif order == (self.nt2, self.nt3, self.nt4,",
"nj, nk, nl) if nmin == ni: pass elif nmin == nj: self.nt1,",
"= self.nt4, self.nt1, self.nt2, self.nt3 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23,",
"GbaTetradClassification.Va, 'ssas': GbaTetradClassification.Vb, 'assa': GbaTetradClassification.VIa, 'saas': GbaTetradClassification.VIb, 'asss': GbaTetradClassification.VIIa, 'saaa': GbaTetradClassification.VIIb, 'aaaa': GbaTetradClassification.VIIIa,",
"with {len(self.tetrads)} tetrads\\n' for quadruplex in self.quadruplexes: builder += str(quadruplex) elif len(self.tetrads) ==",
"Iterable[str]): i = 1 for chain in chain_order: for nt in self.structure3d.residues: if",
"ONZ.Z_MINUS: 6} nucleotides = self.analysis.structure3d.residues shifts = self.analysis.shifts helix = tempfile.NamedTemporaryFile('w+', suffix='.helix') helix.write(f'#{len(self.analysis.sequence)",
"tetrad_pair in self.tetrad_pairs: nt_dict = { tetrad_pair.tetrad1.nt1: tetrad_pair.tetrad2_nts_best_order[0], tetrad_pair.tetrad1.nt2: tetrad_pair.tetrad2_nts_best_order[1], tetrad_pair.tetrad1.nt3: tetrad_pair.tetrad2_nts_best_order[2], tetrad_pair.tetrad1.nt4:",
"tp in self.tetrad_pairs]) direction, support = counter.most_common()[0] if support != len(self.tetrad_pairs): direction =",
"== '-' else 'b' return LoopClassification.from_value(f'{loop_classes[fingerprint]}{subtype}') def __str__(self): builder = '' if len(self.tetrads)",
"order: {\" \".join(self.__chain_order())}\\n' for helix in self.helices: builder += str(helix) builder += f'{self.sequence}\\n{self.line1}\\n{self.line2}'",
"queue}) queue, removed = removed, [] order += 1 opening = '([{<' +",
"pair_34, pair_41)) # build graph of tetrads while tetrads: graph = defaultdict(list) for",
"'-' structure += '-' shift_value += 1 sequence += nt.one_letter_name structure += dotbracket.get(nt,",
"h in self.helices: for t in h.tetrads: for p in [t.pair_12, t.pair_23, t.pair_34,",
"+ shifts[y] helix.write(f'{x}\\t{y}\\t1\\t8\\n') helix.flush() return helix class AnalysisSimple: def __init__(self, structure2d: Structure2D, structure3d:",
"= structure3d.base_pairs(structure2d) self.graph: Dict[Residue3D, List[Residue3D]] = structure3d.base_pair_graph(structure2d) self.pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = structure3d.base_pair_dict(structure2d)",
"== (self.nt3, self.nt4, self.nt1, self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12,",
"dict() for pair, order in orders.items(): nt1, nt2 = sorted([pair.nt1, pair.nt2]) dotbracket[nt1] =",
"self.__filter_tetrad_pairs(tetrads), self.structure3d)) return quadruplexes def __filter_tetrad_pairs(self, tetrads: List[Tetrad]) -> List[TetradPair]: chains = set()",
"= f'Chain order: {\" \".join(self.__chain_order())}\\n' for helix in self.helices: builder += str(helix) builder",
"stacked)) order = (stacked[ti.nt1], stacked[ti.nt2], stacked[ti.nt3], stacked[ti.nt4]) tj.reorder_to_match_other_tetrad(order) return tetrad_pairs def __find_helices(self): helices",
"= nts2 if best_score == 4: break tetrad_scores[ti][tj] = (best_score, nts1, best_order) tetrad_scores[tj][ti]",
"n2), (n4, n1, n2, n3), (n1, n4, n3, n2), (n4, n3, n2, n1),",
"tetrad.onz for tetrad in self.tetrads for pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]} def",
"self.analysis.shifts helix = tempfile.NamedTemporaryFile('w+', suffix='.helix') helix.write(f'#{len(self.analysis.sequence) + 1}\\n') helix.write('i\\tj\\tlength\\tvalue\\n') for pair in layer:",
"order = (tp.stacked[tp.tetrad1.nt1], tp.stacked[tp.tetrad1.nt2], tp.stacked[tp.tetrad1.nt3], tp.stacked[tp.tetrad1.nt4]) tp.tetrad2.reorder_to_match_5p_3p() # this is required to recalculate",
"builder += f'n4-helix with {len(self.tetrads)} tetrads\\n' for quadruplex in self.quadruplexes: builder += str(quadruplex)",
"classes mapped to fingerprints gba_classes = { 'aass': GbaTetradClassification.Ia, 'ssaa': GbaTetradClassification.Ib, 'asas': GbaTetradClassification.IIa,",
"for loop in self.loops]) if fingerprint not in loop_classes: logging.error(f'Unknown loop classification: {fingerprint}')",
"in (i, j), self.base_pair_graph[j]): for l in filter(lambda x: x not in (i,",
"v2 = v2 / numpy.linalg.norm(v2) return math.degrees(numpy.arccos(numpy.clip(numpy.dot(v1, v2), -1.0, 1.0))) def __str__(self): return",
"l, pair_12, pair_23, pair_34, pair_41)) # build graph of tetrads while tetrads: graph",
"str, Dict[Residue3D, int]]: orders = dict() order = 0 queue = list(pairs) removed",
"in self.tracts: builder += f'{tract}\\n' if self.loops: builder += '\\n Loops:\\n' for loop",
"gba: roman_numerals.get(gba, 100)) return list(map(lambda x: GbaQuadruplexClassification[x], gbas)) def __find_tracts(self) -> List[Tract]: tracts",
"0: return {}, {} ions_channel = defaultdict(list) ions_outside = defaultdict(list) for ion in",
"- 1] ncur = tetrad_nucleotides[i] if ncur.index - nprev.index > 1 and ncur.chain",
"Residue3D) -> Optional[Tract]: for tract in self.tracts: if nt in tract.nucleotides: return tract",
"with nt_first for nt in tract_with_last.nucleotides: if nt in tetrad_with_first.nucleotides: sign = self.__detect_loop_sign(nt_first,",
"tetrads = [] for i in self.base_pair_graph: for j in filter(lambda x: x",
"== first and pair.nt2 == last: if pair.score() < pair.reverse().score(): return '-' return",
"{self.pair_23.lw.value} {self.pair_34.lw.value} {self.pair_41.lw.value} ' \\ f'{self.onz.value} {self.gba_class.value} ' \\ f'planarity={round(self.planarity_deviation, 2)} ' \\",
"> 0: for tetrad_pair in self.tetrad_pairs: nt_dict = { tetrad_pair.tetrad1.nt1: tetrad_pair.tetrad2_nts_best_order[0], tetrad_pair.tetrad1.nt2: tetrad_pair.tetrad2_nts_best_order[1],",
"= dict() shift_value = 0 chain = None for nt in sorted(filter(lambda nt:",
"(1, 2, 3): return ONZ.O_PLUS elif order == (3, 2, 1): return ONZ.O_MINUS",
"ONZ.N_MINUS: 4, ONZ.Z_PLUS: 5, ONZ.Z_MINUS: 6} nucleotides = self.analysis.structure3d.residues shifts = self.analysis.shifts helix",
"i i += 1 for nt in self.structure3d.residues: if nt.chain not in chain_order:",
"laterals happen when first and last nt of a loop is in the",
"= True break candidates = sorted(candidates, key=lambda x: len(x), reverse=True) groups = []",
"1 sequence += nt.one_letter_name structure += dotbracket.get(nt, '.') shifts[nt] = shift_value chain =",
"self.nt3, self.nt4 = self.nt2, self.nt3, self.nt4, self.nt1 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23,",
"1 and ncur.chain == nprev.chain: for tract in self.tracts: if nprev in tract.nucleotides",
"__str__(self): builder = f'Chain order: {\" \".join(self.__chain_order())}\\n' for helix in self.helices: builder +=",
"= [1 if is_next_by_stacking(nts1[i], nts2[i]) else 0 for i in range(4)] score_sequential =",
"+ 1 + shifts[y] helix.write(f'{x}\\t{y}\\t1\\t8\\n') helix.flush() return helix class AnalysisSimple: def __init__(self, structure2d:",
"Residue3D nt2: Residue3D nt3: Residue3D nt4: Residue3D pair_12: BasePair3D pair_23: BasePair3D pair_34: BasePair3D",
"1): return ONZ.N_MINUS elif order == (2, 1, 3): return ONZ.Z_PLUS elif order",
"self.shifts = self.__generate_twoline_dotbracket() self.ions = self.__find_ions() self.__assign_ions_to_tetrads() def __find_tetrads(self, no_reorder=False) -> List[Tetrad]: #",
"BasePair3D] = field(init=False) stacking_graph: Dict[Residue3D, List[Residue3D]] = field(init=False) tetrads: List[Tetrad] = field(init=False) tetrad_scores:",
"order: {\" \".join(final_order)} ' f'{\" \".join(map(lambda onz: onz.value, classifications))}') self.tetrads = self.__find_tetrads(True) self.tetrad_scores",
"for nt in tetrad.nucleotides: for atom in nt.atoms: distance = numpy.linalg.norm(ion.coordinates() - atom.coordinates())",
"ONZ.Z_PLUS elif order == (3, 1, 2): return ONZ.Z_MINUS raise RuntimeError(f'Impossible combination: {ni}",
"inner = [nt.innermost_atom for nt in self.nucleotides] return numpy.linalg.norm(center_of_mass(outer) - center_of_mass(inner)) @property def",
"n4), (n2, n1, n4, n3)] for nts2 in viable_permutations: score_stacking = [1 if",
"if len(self.tetrad_pairs) > 0: for tetrad_pair in self.tetrad_pairs: nt_dict = { tetrad_pair.tetrad1.nt1: tetrad_pair.tetrad2_nts_best_order[0],",
"GbaTetradClassification.Ib, 'asas': GbaTetradClassification.IIa, 'sasa': GbaTetradClassification.IIb, 'asaa': GbaTetradClassification.IIIa, 'sass': GbaTetradClassification.IIIb, 'aaas': GbaTetradClassification.IVa, 'sssa': GbaTetradClassification.IVb,",
"'a' if self.loops[0 if fingerprint != 'dpd' else 1].loop_type.value[-1] == '-' else 'b'",
"2)} twist={round(self.twist, 2)}\\n' @dataclass class Tract: nucleotides: List[Residue3D] def __str__(self): return f' {\",",
"c2 = p.nt2.chain if c1 != c2 and c1 in chain_order and c2",
"self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34 elif order ==",
"= ti.nucleotides best_score = 0 best_score_sequential = 0 best_score_stacking = 0 best_order =",
"List[Atom3D]: metal_atom_names = set([ion.value.upper() for ion in Ion]) ions = [] used =",
"pairs: List[BasePair3D]) -> Tuple[str, str, Dict[Residue3D, int]]: orders = dict() order = 0",
"if fingerprint not in gba_classes: logging.error(f'Impossible combination of syn/anti: {[nt.chi_class for nt in",
"tempfile.NamedTemporaryFile('w+', suffix='.helix') helix.write(f'#{len(self.analysis.sequence) + 1}\\n') helix.write('i\\tj\\tlength\\tvalue\\n') for pair in layer: x, y =",
"self.stacked[self.tetrad1.nt2], self.stacked[self.tetrad1.nt3], self.stacked[self.tetrad1.nt4] ) self.direction = self.__determine_direction() self.rise = self.__calculate_rise() self.twist = self.__calculate_twist()",
"[t.onz for h in self.helices for t in h.tetrads] logging.debug( f'Checking reorder: {\"",
"self.tracts: builder += '\\n Tracts:\\n' for tract in self.tracts: builder += f'{tract}\\n' if",
"Optional[LoopClassification] = field(init=False) def __post_init__(self): self.onzm = self.__classify_onzm() self.gba_classes = self.__classify_by_gba() self.tracts =",
"List[Helix] = field(init=False) ions: List[Atom3D] = field(init=False) sequence: str = field(init=False) line1: str",
"in the same direction return Direction.parallel elif count == 2: # two in",
"1) * 4: break tetrad_pairs = [] for i in range(1, len(best_order)): ti,",
"None if any([t.onz is None for t in self.tetrads]): return None counter =",
"line2: str = field(init=False) shifts: Dict[Residue3D, int] = field(init=False) def __post_init__(self): self.base_pairs =",
"return tract return None def __detect_loop_sign(self, first: Residue3D, last: Residue3D, tetrad: Tetrad) ->",
"4: # all in the same direction return Direction.parallel elif count == 2:",
"BasePair3D pair_23: BasePair3D pair_34: BasePair3D pair_41: BasePair3D onz: ONZ = field(init=False) gba_class: Optional[GbaTetradClassification]",
"return sorted([sorted(group) for group in groups], key=lambda x: x[0]) def __reorder_chains(self, chain_order: Iterable[str]):",
"shift_value += 1 sequence += nt.one_letter_name structure += dotbracket.get(nt, '.') shifts[nt] = shift_value",
"in self.loops]): return None loop_classes = { 'ppp': '1', 'ppl': '2', 'plp': '3',",
"bool: return nt2 in self.stacking_graph.get(nt1, []) def is_next_sequentially(nt1: Residue3D, nt2: Residue3D) -> bool:",
"numpy.linalg.norm(v1) v2 = nt2_1.find_atom(\"C1'\").coordinates() - nt2_2.find_atom(\"C1'\").coordinates() v2 = v2 / numpy.linalg.norm(v2) return math.degrees(numpy.arccos(numpy.clip(numpy.dot(v1,",
"self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() # ONZ and",
"gbas.add(gba.value[:-1]) # discard 'a' or 'b' subvariant roman_numerals = {'I': 1, 'II': 2,",
"for t in h.tetrads] logging.debug( f'Checking reorder: {\" \".join(permutation)} {\" \".join(map(lambda c: c.value,",
"tj.nucleotides n1, n2, n3, n4 = tj.nucleotides viable_permutations = [(n1, n2, n3, n4),",
"Loops:\\n' for loop in self.loops: builder += f'{loop}\\n' builder += '\\n' return builder",
"score < best_score: best_score = score best_permutation = permutation elif score == best_score:",
"lw4), (lw2, lw1), (lw3, lw2), (lw4, lw3)): if lw_i.name[1] == lw_j.name[2]: return False",
"fingerprint not in loop_classes: logging.error(f'Unknown loop classification: {fingerprint}') return None subtype = 'a'",
"# without all nucleotides having a valid syn/anti, this classification is impossible if",
"nt.full_name, self.nucleotides))}' @dataclass class Loop: nucleotides: List[Residue3D] loop_type: Optional[LoopType] def __str__(self): return f'",
"import subprocess import tempfile from collections import defaultdict, Counter from dataclasses import dataclass,",
"shifts[nt] = shift_value chain = nt.chain return sequence, structure, shifts def __str__(self): builder",
"-> bool: return nt1.chain == nt2.chain and abs(nt1.index - nt2.index) == 1 tetrad_scores",
"[] helix_tetrads = [] helix_tetrad_pairs = [] for tp in self.tetrad_pairs: ti, tj",
"Ion]) ions = [] used = set() for residue in self.structure3d.residues: for atom",
"None for loop in self.loops]): return None loop_classes = { 'ppp': '1', 'ppl':",
"return numpy.array((sum(xs) / len(coords), sum(ys) / len(coords), sum(zs) / len(coords))) def eltetrado(structure2d: Structure2D,",
"helix in helices]): helices.append(Helix([tetrad], [], self.structure3d)) return helices def __find_best_chain_order(self): chain_groups = self.__group_related_chains()",
"return builder def __chain_order(self) -> List[str]: only_nucleic_acids = filter(lambda nt: nt.is_nucleotide, self.structure3d.residues) return",
"x, y = pair.nt1, pair.nt2 x, y = nucleotides.index(x) + 1 + shifts[x],",
"import itertools import logging import math import os import string import subprocess import",
"return ONZ.O_MINUS elif order == (1, 3, 2): return ONZ.N_PLUS elif order ==",
"loop in self.loops: builder += f'{loop}\\n' builder += '\\n' return builder @dataclass class",
"self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() else: raise RuntimeError(f'Cannot apply order: {order}') self.nt1,",
"= ''.join([nt.chi_class.value[0] for nt in self.nucleotides]) # this dict has all classes mapped",
"len(best_order)): ti, tj = best_order[i - 1], best_order[i] score = self.tetrad_scores[ti][tj][0] if score",
"= self.tetrad1.nucleotides nt2_1, nt2_2, _, _ = self.tetrad2_nts_best_order v1 = nt1_1.find_atom(\"C1'\").coordinates() - nt1_2.find_atom(\"C1'\").coordinates()",
"def __post_init__(self): self.reorder_to_match_5p_3p() self.planarity_deviation = self.__calculate_planarity_deviation() def reorder_to_match_5p_3p(self): # transform into (0, 1,",
"too far from any tetrad (distance={min_distance})') for tetrad, ions in ions_channel.items(): tetrad.ions_channel =",
"score, score_sequential, score_stacking best_order = nts2 if best_score == 4: break tetrad_scores[ti][tj] =",
"Counter([t.onz.value[1] for t in self.tetrads]) plus_minus, support = counter.most_common()[0] if support != len(self.tetrads):",
"and c2 in chain_order: chain_pairs.append([c1, c2]) sum_sq = 0 for c1, c2 in",
"tetrad_nucleotides[i] if ncur.index - nprev.index > 1 and ncur.chain == nprev.chain: for tract",
"[] while queue: conflicts = defaultdict(list) for pi, pj in itertools.combinations(queue, 2): if",
"tempfile from collections import defaultdict, Counter from dataclasses import dataclass, field from typing",
"discard 'a' or 'b' subvariant roman_numerals = {'I': 1, 'II': 2, 'III': 3,",
"'lpp': '4', 'pdp': '5', 'lll': '6', 'llp': '7', 'lpl': '8', 'pll': '9', 'pdl':",
"center_of_mass(inner)) @property def nucleotides(self) -> Tuple[Residue3D, Residue3D, Residue3D, Residue3D]: return self.nt1, self.nt2, self.nt3,",
"self.nt3, self.nt4 = self.nt3, self.nt4, self.nt1, self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34,",
"[tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]: # main check if pair.nt1 == first and pair.nt2",
"x: x not in (i, j, k) and i in self.base_pair_graph[x], self.base_pair_graph[k]): if",
"+ shifts[x], nucleotides.index(y) + 1 + shifts[y] onz = self.onz_dict[pair] helix.write(f'{x}\\t{y}\\t1\\t{onz_value.get(onz, 7)}\\n') if",
"is None or tetrad_with_last is None: logging.warning(f'Failed to classify the loop between {nt_first}",
"- atom.coordinates()) if distance < min_distance: min_distance = distance min_tetrad = tetrad min_nt",
"shifts[y] onz = self.onz_dict[pair] helix.write(f'{x}\\t{y}\\t1\\t{onz_value.get(onz, 7)}\\n') if canonical: for pair in canonical: x,",
"or n/a \"\"\" # without all nucleotides having a valid syn/anti, this classification",
"roman_numerals = {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5, 'VI':",
"coords) return numpy.array((sum(xs) / len(coords), sum(ys) / len(coords), sum(zs) / len(coords))) def eltetrado(structure2d:",
"[] helix_tetrad_pairs = [] for tp in self.tetrad_pairs: ti, tj = tp.tetrad1, tp.tetrad2",
"field(init=False) def __post_init__(self): self.onzm = self.__classify_onzm() self.gba_classes = self.__classify_by_gba() self.tracts = self.__find_tracts() self.loops",
"v1 = v1 / numpy.linalg.norm(v1) v2 = nt2_1.find_atom(\"C1'\").coordinates() - nt2_2.find_atom(\"C1'\").coordinates() v2 = v2",
"c.value, classifications))}') onz_score = sum(c.score() for c in classifications) chain_order_score = self.__chain_order_score(permutation) score",
"in filter(lambda x: x not in (i, j, k) and x in self.graph[i],",
"self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23 else: self.nt1, self.nt2, self.nt3, self.nt4",
"self.nt4 = order def __classify_onz(self) -> ONZ: # transform into (0, 1, 2,",
"output_pdf) else: logging.error(f'Failed to prepare visualization, reason:\\n {run.stderr.decode()}') def __to_helix(self, layer: List[BasePair3D], canonical:",
"-> Tuple[str, str, str, Dict[Residue3D, int]]: layer1, layer2 = [], [] for tetrad",
"fasta.flush() layer1, layer2 = [], [] for tetrad in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23,",
"/ numpy.linalg.norm(v2) return math.degrees(numpy.arccos(numpy.clip(numpy.dot(v1, v2), -1.0, 1.0))) def __str__(self): return f' direction={self.direction.value} rise={round(self.rise,",
"sorted(tetrads, key=lambda t: min(map(lambda nt: nt.index, t.nucleotides))) def __calculate_tetrad_scores(self) \\ -> Dict[Tetrad, Dict[Tetrad,",
"for tetrad in self.tetrads: if not any([tetrad in helix.tetrads for helix in helices]):",
"graph = defaultdict(list) for (ti, tj) in itertools.combinations(tetrads, 2): if not ti.is_disjoint(tj): graph[ti].append(tj)",
"min_tetrad = self.tetrads[0] for tetrad in self.tetrads: distance = numpy.linalg.norm(ion.coordinates() - tetrad.center()) if",
"self.pairs: List[BasePair3D] = structure3d.base_pairs(structure2d) self.graph: Dict[Residue3D, List[Residue3D]] = structure3d.base_pair_graph(structure2d) self.pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D]",
"coords) zs = (coord[2] for coord in coords) return numpy.array((sum(xs) / len(coords), sum(ys)",
"'quadraw.R'), fasta.name, helix1.name, helix2.name, output_pdf], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if run.returncode == 0: print('\\nPlot:', output_pdf)",
"t.nucleotides))) def __calculate_tetrad_scores(self) \\ -> Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]]: def is_next_by_stacking(nt1: Residue3D,",
"structure3d: Structure3D strict: bool no_reorder: bool stacking_mismatch: int base_pairs: List[BasePair3D] = field(init=False) base_pair_graph:",
"c2]) sum_sq = 0 for c1, c2 in chain_pairs: sum_sq += (chain_order.index(c1) -",
"for tj in candidates], key=lambda tk: self.tetrad_scores[ti][tk][0]) score += self.tetrad_scores[ti][tj][0] order.append(tj) candidates.remove(tj) ti",
"[], self.structure3d)) return helices def __find_best_chain_order(self): chain_groups = self.__group_related_chains() final_order = [] for",
"Silva or n/a \"\"\" # without all nucleotides having a valid syn/anti, this",
"best_score_sequential, best_score_stacking): best_score, best_score_sequential, best_score_stacking = score, score_sequential, score_stacking best_order = nts2 if",
"order == (self.nt2, self.nt3, self.nt4, self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34,",
"indices2 = list(map(lambda nt: nt.index, self.tetrad2_nts_best_order)) # count directions 5' -> 3' as",
"= field(init=False) ions: List[Atom3D] = field(init=False) sequence: str = field(init=False) line1: str =",
"n1, n2, n3), (n1, n4, n3, n2), (n4, n3, n2, n1), (n3, n2,",
"1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5, 'VI': 6, 'VII': 7,",
"not helix_tetrads: helix_tetrads.append(ti) score = self.tetrad_scores[helix_tetrads[-1]][tj][0] if score >= (4 - self.stacking_mismatch): helix_tetrads.append(tj)",
"self.structure3d)) return helices def __find_best_chain_order(self): chain_groups = self.__group_related_chains() final_order = [] for chains",
"self.tetrads: for nt in tetrad.nucleotides: for atom in nt.atoms: distance = numpy.linalg.norm(ion.coordinates() -",
"x: len(x), reverse=True) groups = [] for candidate in candidates: if any([group.issuperset(candidate) for",
"canonical(self) -> List[BasePair3D]: return [base_pair for base_pair in self.base_pairs if base_pair.is_canonical()] @dataclass class",
"for l in filter(lambda x: x not in (i, j, k) and i",
"ions = [] used = set() for residue in self.structure3d.residues: for atom in",
"for nt in sorted(only_nucleic_acids, key=lambda nt: nt.index)}.keys()) def canonical(self) -> List[BasePair3D]: return [base_pair",
"break tetrad_pairs = [] for i in range(1, len(best_order)): ti, tj = best_order[i",
"else 0 for i in range(4)] score = sum([max(score_stacking[i], score_sequential[i]) for i in",
"= field(default_factory=list) ions_outside: Dict[Residue3D, List[Atom3D]] = field(default_factory=dict) def __post_init__(self): self.reorder_to_match_5p_3p() self.planarity_deviation = self.__calculate_planarity_deviation()",
"x != i, self.base_pair_graph[i]): for k in filter(lambda x: x not in (i,",
"in filter(lambda x: x != i, self.base_pair_graph[i]): for k in filter(lambda x: x",
"layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) helix1 = self.__to_helix(layer1, self.analysis.canonical() if self.complete2d else []) helix2",
"in h.tetrads] logging.debug(f'Selected chain order: {\" \".join(final_order)} ' f'{\" \".join(map(lambda onz: onz.value, classifications))}')",
"break else: nts = list(filter(lambda nt: nprev.index < nt.index < ncur.index, self.structure3d.residues)) loop_type",
"(3, 1, 2): return ONZ.Z_MINUS raise RuntimeError(f'Impossible combination: {ni} {nj} {nk} {nl}') def",
"= {pair: tetrad.onz for tetrad in self.tetrads for pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34,",
"ions: List[Atom3D] = field(init=False) sequence: str = field(init=False) line1: str = field(init=False) line2:",
"fasta.write(self.analysis.sequence) fasta.flush() layer1, layer2 = [], [] for tetrad in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34])",
"import math import os import string import subprocess import tempfile from collections import",
"stacking_mismatch: int) -> List[TetradPair]: tetrads = list(self.tetrads) best_score = 0 best_order = tetrads",
"loop between {nt_first} and {nt_last}') return None if tetrad_with_first == tetrad_with_last: # diagonal",
"{\" \".join(final_order)} ' f'{\" \".join(map(lambda onz: onz.value, classifications))}') self.tetrads = self.__find_tetrads(True) self.tetrad_scores =",
"= self.__classify_by_gba() self.tracts = self.__find_tracts() self.loops = self.__find_loops() self.loop_class = self.__classify_by_loops() def __classify_onzm(self)",
"i, self.base_pair_graph[i]): for k in filter(lambda x: x not in (i, j), self.base_pair_graph[j]):",
"nl = (nt.index for nt in self.nucleotides) indices = sorted((ni, nj, nk, nl))",
"tetrad: i -> j -> k -> l # ^--------------^ tetrads = []",
"coord in coords) zs = (coord[2] for coord in coords) return numpy.array((sum(xs) /",
"which conflicts the most with others # in case of a tie, remove",
"structure3d: Structure3D): self.pairs: List[BasePair3D] = structure3d.base_pairs(structure2d) self.graph: Dict[Residue3D, List[Residue3D]] = structure3d.base_pair_graph(structure2d) self.pair_dict: Dict[Tuple[Residue3D,",
"{\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass class Loop: nucleotides: List[Residue3D] loop_type: Optional[LoopType] def",
"j, k, l, self.base_pair_dict): pair_12 = self.base_pair_dict[(i, j)] pair_23 = self.base_pair_dict[(j, k)] pair_34",
"self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif order == (self.nt3,",
"chain_pairs = [] for h in self.helices: for t in h.tetrads: for p",
"self.tetrads]) plus_minus, support = counter.most_common()[0] if support != len(self.tetrads): plus_minus = '*' return",
"elif nmin == nk: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt3, self.nt4, self.nt1, self.nt2",
"v1 = nt1_1.find_atom(\"C1'\").coordinates() - nt1_2.find_atom(\"C1'\").coordinates() v1 = v1 / numpy.linalg.norm(v1) v2 = nt2_1.find_atom(\"C1'\").coordinates()",
"!= 'dpd' else 1].loop_type.value[-1] == '-' else 'b' return LoopClassification.from_value(f'{loop_classes[fingerprint]}{subtype}') def __str__(self): builder",
"in [self.tetrad_pairs[0].tetrad1] + [tetrad_pair.tetrad2 for tetrad_pair in self.tetrad_pairs]: if tetrads: if tetrad.chains().isdisjoint(tetrads[-1].chains()): quadruplexes.append(Quadruplex(tetrads,",
"tempfile.NamedTemporaryFile('w+', suffix='.fasta') fasta.write(f'>{prefix}-{suffix}\\n') fasta.write(self.analysis.sequence) fasta.flush() layer1, layer2 = [], [] for tetrad in",
"has_tetrads(self): tetrads = set() for i in self.graph: for j in filter(lambda x:",
"f'{prefix}-{suffix}.pdf' run = subprocess.run([os.path.join(currdir, 'quadraw.R'), fasta.name, helix1.name, helix2.name, output_pdf], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if run.returncode",
"self.onzm = self.__classify_onzm() self.gba_classes = self.__classify_by_gba() self.tracts = self.__find_tracts() self.loops = self.__find_loops() self.loop_class",
"self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif nmin == nk: self.nt1, self.nt2,",
"syn/anti, this classification is impossible if not all([nt.chi_class in (GlycosidicBond.syn, GlycosidicBond.anti) for nt",
"pair_12 = self.base_pair_dict[(i, j)] pair_23 = self.base_pair_dict[(j, k)] pair_34 = self.base_pair_dict[(k, l)] pair_41",
"for chains in chain_groups: best_permutation, best_score = chains, (1e10, 1e10) if len(chains) >",
"= [], [] for tetrad in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) helix1 =",
"helix.write(f'#{len(self.analysis.sequence) + 1}\\n') helix.write('i\\tj\\tlength\\tvalue\\n') for pair in layer: x, y = pair.nt1, pair.nt2",
"self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif nmin == nk: self.nt1, self.nt2, self.nt3, self.nt4 =",
"Journal, 13(35), 9738–9745. https://doi.org/10.1002/chem.200701255 :return: Classification according to Webba da Silva or n/a",
"final_order.extend(best_permutation) if len(final_order) > 1: self.__reorder_chains(final_order) classifications = [t.onz for h in self.helices",
"LoopType.from_value(f'propeller{sign}') logging.warning(f'Failed to classify the loop between {nt_first} and {nt_last}') return None def",
"self.nt1, self.nt2, self.nt3, self.nt4 def __hash__(self): return hash(frozenset([self.nt1, self.nt2, self.nt3, self.nt4])) def __str__(self):",
"def __chain_order(self) -> List[str]: only_nucleic_acids = filter(lambda nt: nt.is_nucleotide, self.structure3d.residues) return list({nt.chain: 0",
"bool: lw1 = pair_dictionary[(nt1, nt2)].lw lw2 = pair_dictionary[(nt2, nt3)].lw lw3 = pair_dictionary[(nt3, nt4)].lw",
"str(self.tetrads[0]) return builder @dataclass class Analysis: structure2d: Structure2D structure3d: Structure3D strict: bool no_reorder:",
"= tetrad_nucleotides[i] if ncur.index - nprev.index > 1 and ncur.chain == nprev.chain: for",
"= nucleotides.index(x) + 1 + shifts[x], nucleotides.index(y) + 1 + shifts[y] onz =",
"dotbracket[nt1] = opening[order] dotbracket[nt2] = closing[order] sequence = '' structure = '' shifts",
"in chain_groups: best_permutation, best_score = chains, (1e10, 1e10) if len(chains) > 1: for",
"= tetrad_nucleotides[i - 1] ncur = tetrad_nucleotides[i] if ncur.index - nprev.index > 1",
"= Counter(1 if j - i > 0 else -1 for i, j",
"def __find_best_chain_order(self): chain_groups = self.__group_related_chains() final_order = [] for chains in chain_groups: best_permutation,",
"in self.ions: min_distance = math.inf min_tetrad = self.tetrads[0] for tetrad in self.tetrads: distance",
"Optional[LoopType]: tetrad_with_first = self.__find_tetrad_with_nt(nt_first) tetrad_with_last = self.__find_tetrad_with_nt(nt_last) if tetrad_with_first is None or tetrad_with_last",
"in self.graph[i], self.graph[k]): if Tetrad.is_valid(i, j, k, l, self.pair_dict): tetrads.add(frozenset([i, j, k, l]))",
"__calculate_planarity_deviation(self) -> float: outer = [nt.outermost_atom for nt in self.nucleotides] inner = [nt.innermost_atom",
"field(init=False) gba_class: Optional[GbaTetradClassification] = field(init=False) planarity_deviation: float = field(init=False) ions_channel: List[Atom3D] = field(default_factory=list)",
"tetrad_pair.tetrad1.nt3: tetrad_pair.tetrad2_nts_best_order[2], tetrad_pair.tetrad1.nt4: tetrad_pair.tetrad2_nts_best_order[3], } for i in range(4): tracts[i].append(nt_dict[tracts[i][-1]]) return [Tract(nts) for",
"threshold of 3A between an ion and an atom if min_distance < 3.0:",
"len(self.tetrads): plus_minus = '*' return ONZM.from_value(f'{onz}{direction}{plus_minus}') def __classify_by_gba(self) -> List[GbaQuadruplexClassification]: gbas = set()",
"order == (1, 3, 2): return ONZ.N_PLUS elif order == (2, 3, 1):",
"ncur = tetrad_nucleotides[i] if ncur.index - nprev.index > 1 and ncur.chain == nprev.chain:",
"and last nt of a loop is in the same tetrad sign =",
"builder += ' single tetrad\\n' builder += str(self.tetrads[0]) else: builder += f' {self.onzm.value",
"for atom in residue.atoms: if atom.atomName.upper() in metal_atom_names: coordinates = tuple(atom.coordinates()) if coordinates",
"base_pair.is_canonical()] @dataclass class Visualizer: analysis: Analysis tetrads: List[Tetrad] complete2d: bool onz_dict: Dict[BasePair3D, ONZ]",
"{ti} while candidates: tj = max([tj for tj in candidates], key=lambda tk: self.tetrad_scores[ti][tk][0])",
"= set() for residue in self.structure3d.residues: for atom in residue.atoms: if atom.atomName.upper() in",
"fasta.name, helix1.name, helix2.name, output_pdf], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if run.returncode == 0: print('\\nPlot:', output_pdf) else:",
"self.__reorder_chains(final_order) classifications = [t.onz for h in self.helices for t in h.tetrads] logging.debug(f'Selected",
"def __str__(self): return f' direction={self.direction.value} rise={round(self.rise, 2)} twist={round(self.twist, 2)}\\n' @dataclass class Tract: nucleotides:",
"nucleotides: List[Residue3D] def __str__(self): return f' {\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass class",
"chains in chain_groups: best_permutation, best_score = chains, (1e10, 1e10) if len(chains) > 1:",
"'a' for anti fingerprint = ''.join([nt.chi_class.value[0] for nt in self.nucleotides]) # this dict",
"queue.remove(pair) else: orders.update({pair: order for pair in queue}) queue, removed = removed, []",
"__filter_tetrad_pairs(self, tetrads: List[Tetrad]) -> List[TetradPair]: chains = set() for tetrad in tetrads: chains.update(tetrad.chains())",
"no_reorder: bool stacking_mismatch: int base_pairs: List[BasePair3D] = field(init=False) base_pair_graph: Dict[Residue3D, List[Residue3D]] = field(init=False)",
"counter.most_common()[0] if support != len(self.tetrads): onz = 'M' counter = Counter([tp.direction.value[0] for tp",
"n3, n4 = tj.nucleotides viable_permutations = [(n1, n2, n3, n4), (n2, n3, n4,",
"onz_dict: Dict[BasePair3D, ONZ] = field(init=False) def __post_init__(self): self.onz_dict = {pair: tetrad.onz for tetrad",
"sorted((ni, nj, nk, nl)) ni, nj, nk, nl = (indices.index(x) for x in",
"i -> j -> k -> l # ^--------------^ tetrads = [] for",
"pick permutation earlier in lexicographical sense if permutation < best_permutation: best_permutation = permutation",
"return None return gba_classes[fingerprint] def __calculate_planarity_deviation(self) -> float: outer = [nt.outermost_atom for nt",
"(n1, n4, n3, n2), (n4, n3, n2, n1), (n3, n2, n1, n4), (n2,",
"for t in h.tetrads: for p in [t.pair_12, t.pair_23, t.pair_34, t.pair_41]: c1 =",
"'' if len(self.tetrads) > 1: builder += f'n4-helix with {len(self.tetrads)} tetrads\\n' for quadruplex",
"Residue3D pair_12: BasePair3D pair_23: BasePair3D pair_34: BasePair3D pair_41: BasePair3D onz: ONZ = field(init=False)",
"canonical: for pair in canonical: x, y = pair.nt1, pair.nt2 x, y =",
"Residue3D]: return self.nt1, self.nt2, self.nt3, self.nt4 def __hash__(self): return hash(frozenset([self.nt1, self.nt2, self.nt3, self.nt4]))",
"'a' or 'b' subvariant roman_numerals = {'I': 1, 'II': 2, 'III': 3, 'IV':",
"chains(self) -> Set[str]: return set([nt.chain for nt in self.nucleotides]) def is_disjoint(self, other) ->",
"onz = 'M' counter = Counter([tp.direction.value[0] for tp in self.tetrad_pairs]) direction, support =",
"return hash(frozenset([self.nt1, self.nt2, self.nt3, self.nt4])) def __str__(self): return f' ' \\ f'{self.nt1.full_name} {self.nt2.full_name}",
"helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) for tetrad in self.tetrads: if not any([tetrad in helix.tetrads for",
"ti, tj = tp.tetrad1, tp.tetrad2 if not helix_tetrads: helix_tetrads.append(ti) score = self.tetrad_scores[helix_tetrads[-1]][tj][0] if",
"self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() def __group_related_chains(self) -> List[List[str]]:",
"len(self.loops) != 3 or any([loop.loop_type is None for loop in self.loops]): return None",
"^--------------^ tetrads = [] for i in self.base_pair_graph: for j in filter(lambda x:",
"-> bool: return not t.chains().isdisjoint(chains) def check_pair(tp: TetradPair) -> bool: return check_tetrad(tp.tetrad1) and",
"== ni: pass elif nmin == nj: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt2,",
"= '' if len(self.tetrads) == 1: builder += ' single tetrad\\n' builder +=",
"class Analysis: structure2d: Structure2D structure3d: Structure3D strict: bool no_reorder: bool stacking_mismatch: int base_pairs:",
"in (ni, nj, nk, nl)) while ni != 0: ni, nj, nk, nl",
"= '' structure = '' shifts = dict() shift_value = 0 chain =",
"-> List[Tract]: tracts = [[self.tetrads[0].nt1], [self.tetrads[0].nt2], [self.tetrads[0].nt3], [self.tetrads[0].nt4]] if len(self.tetrad_pairs) > 0: for",
"tetrad_pairs.append(TetradPair(ti, tj, stacked)) order = (stacked[ti.nt1], stacked[ti.nt2], stacked[ti.nt3], stacked[ti.nt4]) tj.reorder_to_match_other_tetrad(order) return tetrad_pairs def",
"self.onz_dict = {pair: tetrad.onz for tetrad in self.tetrads for pair in [tetrad.pair_12, tetrad.pair_23,",
"tetrads.append(tetrad) quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) return quadruplexes def __filter_tetrad_pairs(self, tetrads: List[Tetrad]) -> List[TetradPair]: chains",
"c1 = p.nt1.chain c2 = p.nt2.chain if c1 != c2 and c1 in",
"x: x != i, self.graph[i]): for k in filter(lambda x: x not in",
"logging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"INFO\")) @dataclass(order=True) class Tetrad: @staticmethod def is_valid(nt1: Residue3D, nt2: Residue3D, nt3: Residue3D,",
"'' def __ions_outside_str(self) -> str: if self.ions_outside: result = [] for residue, ions",
"loop classification: {fingerprint}') return None subtype = 'a' if self.loops[0 if fingerprint !=",
"= nt # TODO: verify threshold of 3A between an ion and an",
"else: break return sorted(tetrads, key=lambda t: min(map(lambda nt: nt.index, t.nucleotides))) def __calculate_tetrad_scores(self) \\",
"= (best_score, nts1, best_order) tetrad_scores[tj][ti] = (best_score, best_order, nts1) return tetrad_scores def __find_tetrad_pairs(self,",
"pair in canonical: x, y = pair.nt1, pair.nt2 x, y = nucleotides.index(x) +",
"having a valid syn/anti, this classification is impossible if not all([nt.chi_class in (GlycosidicBond.syn,",
"field(init=False) gba_classes: List[GbaQuadruplexClassification] = field(init=False) tracts: List[Tract] = field(init=False) loops: List[Loop] = field(init=False)",
"def outer_and_inner_atoms(self) -> List[Atom3D]: return list(map(lambda residue: residue.outermost_atom, self.nucleotides)) + \\ list(map(lambda residue:",
"in self.base_pair_graph[x], self.base_pair_graph[k]): if Tetrad.is_valid(i, j, k, l, self.base_pair_dict): pair_12 = self.base_pair_dict[(i, j)]",
"nt in tract_with_last.nucleotides: if nt in tetrad_with_first.nucleotides: sign = self.__detect_loop_sign(nt_first, nt, tetrad_with_first) if",
"numpy.linalg.norm(center_of_mass(t1) - center_of_mass(t2)) def __calculate_twist(self) -> float: nt1_1, nt1_2, _, _ = self.tetrad1.nucleotides",
"has the worst planarity deviation candidates = sorted(tetrads, key=lambda t: (len(graph[t]), t.planarity_deviation), reverse=True)",
"= defaultdict(dict) for ti, tj in itertools.combinations(self.tetrads, 2): nts1 = ti.nucleotides best_score =",
"two in +, one in - direction return Direction.antiparallel return Direction.hybrid def __calculate_rise(self)",
"score_stacking = sum(score_stacking) if (score, score_sequential, score_stacking) > (best_score, best_score_sequential, best_score_stacking): best_score, best_score_sequential,",
"sum(ys) / len(coords), sum(zs) / len(coords))) def eltetrado(structure2d: Structure2D, structure3d: Structure3D, strict: bool,",
"self.nt2, self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34 elif order",
"def __chain_order_score(self, chain_order: Tuple[str, ...]) -> int: chain_pairs = [] for h in",
"score >= (4 - stacking_mismatch): nts1, nts2 = self.tetrad_scores[ti][tj][1:] stacked = {nts1[i]: nts2[i]",
"v2 = nt2_1.find_atom(\"C1'\").coordinates() - nt2_2.find_atom(\"C1'\").coordinates() v2 = v2 / numpy.linalg.norm(v2) return math.degrees(numpy.arccos(numpy.clip(numpy.dot(v1, v2),",
"of a tie, remove one which has the worst planarity deviation candidates =",
"elif order == (1, 3, 2): return ONZ.N_PLUS elif order == (2, 3,",
"List[TetradPair] structure3d: Structure3D onzm: Optional[ONZM] = field(init=False) gba_classes: List[GbaQuadruplexClassification] = field(init=False) tracts: List[Tract]",
"pi.conflicts_with(pj): conflicts[pi].append(pj) conflicts[pj].append(pi) if conflicts: pair, _ = max(conflicts.items(), key=lambda x: (len(x[1]), x[0].nt1))",
"strict: bool, no_reorder: bool, stacking_mismatch: int) -> Analysis: return Analysis(structure2d, structure3d, strict, no_reorder,",
"3) ni, nj, nk, nl = (nt.index for nt in self.nucleotides) indices =",
"== 1: builder += 'single tetrad without stacking\\n' builder += str(self.tetrads[0]) return builder",
"0 best_score_sequential = 0 best_score_stacking = 0 best_order = tj.nucleotides n1, n2, n3,",
"apply order: {order}') self.nt1, self.nt2, self.nt3, self.nt4 = order def __classify_onz(self) -> ONZ:",
"nk, nl = map(lambda nt: nt.index, self.nucleotides) indices = sorted((ni, nj, nk, nl))",
"return None def __classify_by_loops(self) -> Optional[LoopClassification]: if len(self.loops) != 3 or any([loop.loop_type is",
"None counter = Counter([t.onz.value[0] for t in self.tetrads]) onz, support = counter.most_common()[0] if",
"list() for tetrad in [self.tetrad_pairs[0].tetrad1] + [tetrad_pair.tetrad2 for tetrad_pair in self.tetrad_pairs]: if tetrads:",
"i in self.base_pair_graph: for j in filter(lambda x: x != i, self.base_pair_graph[i]): for",
"= [] for i in range(1, len(best_order)): ti, tj = best_order[i - 1],",
"c1, c2 in chain_pairs: sum_sq += (chain_order.index(c1) - chain_order.index(c2)) ** 2 return sum_sq",
"{fingerprint}') return None subtype = 'a' if self.loops[0 if fingerprint != 'dpd' else",
"in chain_order: for nt in self.structure3d.residues: if nt.chain == chain: nt.index = i",
"helix1.name, helix2.name, output_pdf], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if run.returncode == 0: print('\\nPlot:', output_pdf) else: logging.error(f'Failed",
"if self.ions_channel: return 'ions_channel=' + ','.join([atom.atomName for atom in self.ions_channel]) return '' def",
"nk, nl = (nt.index for nt in self.nucleotides) indices = sorted((ni, nj, nk,",
"None subtype = 'a' if self.loops[0 if fingerprint != 'dpd' else 1].loop_type.value[-1] ==",
"self.ions = self.__find_ions() self.__assign_ions_to_tetrads() def __find_tetrads(self, no_reorder=False) -> List[Tetrad]: # search for a",
"filter(lambda x: x not in (i, j, k) and x in self.graph[i], self.graph[k]):",
"in tetrads: score = 0 order = [ti] candidates = set(self.tetrads) - {ti}",
"key=lambda x: len(x), reverse=True) groups = [] for candidate in candidates: if any([group.issuperset(candidate)",
"= self.__find_tetrads(self.no_reorder) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() if not",
"True while changed: changed = False for i, j in itertools.combinations(range(len(candidates)), 2): qi,",
"atom.atomName.upper() in metal_atom_names: coordinates = tuple(atom.coordinates()) if coordinates not in used: ions.append(atom) used.add(coordinates)",
"self.tetrads: if nt in tetrad.nucleotides: return tetrad return None def __find_tract_with_nt(self, nt: Residue3D)",
"= self.tetrad_scores[helix_tetrads[-1]][tj][0] if score >= (4 - self.stacking_mismatch): helix_tetrads.append(tj) helix_tetrad_pairs.append(tp) else: helices.append(Helix(helix_tetrads, helix_tetrad_pairs,",
"for residue in self.structure3d.residues: for atom in residue.atoms: if atom.atomName.upper() in metal_atom_names: coordinates",
"used.add(coordinates) return ions def __assign_ions_to_tetrads(self) \\ -> Tuple[Dict[Tetrad, List[Atom3D]], Dict[Tuple[Tetrad, Residue3D], List[Atom3D]]]: if",
"self.tetrad_scores[helix_tetrads[-1]][tj][0] if score >= (4 - self.stacking_mismatch): helix_tetrads.append(tj) helix_tetrad_pairs.append(tp) else: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d))",
"set([nt.chain for nt in self.nucleotides]) def is_disjoint(self, other) -> bool: return frozenset(self.nucleotides).isdisjoint(frozenset(other.nucleotides)) def",
"direction: Direction = field(init=False) rise: float = field(init=False) twist: float = field(init=False) def",
"builder += str(quadruplex) elif len(self.tetrads) == 1: builder += 'single tetrad without stacking\\n'",
"= [nt.innermost_atom for nt in self.nucleotides] return numpy.linalg.norm(center_of_mass(outer) - center_of_mass(inner)) @property def nucleotides(self)",
"2): nts1 = ti.nucleotides best_score = 0 best_score_sequential = 0 best_score_stacking = 0",
"self.tetrads: if not any([tetrad in helix.tetrads for helix in helices]): helices.append(Helix([tetrad], [], self.structure3d))",
"= self.tetrads[0] for tetrad in self.tetrads: distance = numpy.linalg.norm(ion.coordinates() - tetrad.center()) if distance",
"score_stacking) > (best_score, best_score_sequential, best_score_stacking): best_score, best_score_sequential, best_score_stacking = score, score_sequential, score_stacking best_order",
"int]]: orders = dict() order = 0 queue = list(pairs) removed = []",
"while changed: changed = False for i, j in itertools.combinations(range(len(candidates)), 2): qi, qj",
"__calculate_tetrad_scores(self) \\ -> Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]]: def is_next_by_stacking(nt1: Residue3D, nt2: Residue3D)",
"nt1: Residue3D nt2: Residue3D nt3: Residue3D nt4: Residue3D pair_12: BasePair3D pair_23: BasePair3D pair_34:",
"(nj, nk, nl) if order == (1, 2, 3): return ONZ.O_PLUS elif order",
"changed: changed = False for i, j in itertools.combinations(range(len(candidates)), 2): qi, qj =",
"tetrad (distance={min_distance})') for tetrad, ions in ions_channel.items(): tetrad.ions_channel = ions for pair, ions",
"self.nucleotides)) def __ions_channel_str(self) -> str: if self.ions_channel: return 'ions_channel=' + ','.join([atom.atomName for atom",
"[] tetrad_nucleotides = sorted([nt for tetrad in self.tetrads for nt in tetrad.nucleotides], key=lambda",
"chain_pairs.append([c1, c2]) sum_sq = 0 for c1, c2 in chain_pairs: sum_sq += (chain_order.index(c1)",
"for tetrad_pair in self.tetrad_pairs: builder += str(tetrad_pair) builder += str(tetrad_pair.tetrad2) if self.tracts: builder",
"Tetrad) -> Optional[str]: for pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]: # main check",
"(len(x[1]), x[0].nt1)) removed.append(pair) queue.remove(pair) else: orders.update({pair: order for pair in queue}) queue, removed",
"pair, order in orders.items(): nt1, nt2 = sorted([pair.nt1, pair.nt2]) dotbracket[nt1] = opening[order] dotbracket[nt2]",
"in range(4)]) score_sequential = sum(score_sequential) score_stacking = sum(score_stacking) if (score, score_sequential, score_stacking) >",
"tetrad.pair_41]) helix1 = self.__to_helix(layer1, self.analysis.canonical() if self.complete2d else []) helix2 = self.__to_helix(layer2) currdir",
"List[TetradPair]: chains = set() for tetrad in tetrads: chains.update(tetrad.chains()) def check_tetrad(t: Tetrad) ->",
"Residue3D, last: Residue3D, tetrad: Tetrad) -> Optional[str]: for pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34,",
"self.nt2, self.nt1, self.nt4): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse() elif",
"__str__(self): return f' ' \\ f'{self.nt1.full_name} {self.nt2.full_name} {self.nt3.full_name} {self.nt4.full_name} ' \\ f'{self.pair_12.lw.value} {self.pair_23.lw.value}",
"def __find_tetrads(self, no_reorder=False) -> List[Tetrad]: # search for a tetrad: i -> j",
"pair_34: BasePair3D pair_41: BasePair3D onz: ONZ = field(init=False) gba_class: Optional[GbaTetradClassification] = field(init=False) planarity_deviation:",
"opening = '([{<' + string.ascii_uppercase closing = ')]}>' + string.ascii_lowercase dotbracket = dict()",
"tetrad # TODO: verify threshold of 6A between an ion and tetrad channel",
"gbas = set() for t in self.tetrads: gba = t.gba_class if gba is",
"roman_numerals.get(gba, 100)) return list(map(lambda x: GbaQuadruplexClassification[x], gbas)) def __find_tracts(self) -> List[Tract]: tracts =",
"= filter(lambda nt: nt.is_nucleotide, self.structure3d.residues) return list({nt.chain: 0 for nt in sorted(only_nucleic_acids, key=lambda",
"+= f'{tract}\\n' if self.loops: builder += '\\n Loops:\\n' for loop in self.loops: builder",
"6} nucleotides = self.analysis.structure3d.residues shifts = self.analysis.shifts helix = tempfile.NamedTemporaryFile('w+', suffix='.helix') helix.write(f'#{len(self.analysis.sequence) +",
"= sorted(tetrads, key=lambda t: (len(graph[t]), t.planarity_deviation), reverse=True) if len(graph[candidates[0]]) > 0: tetrads.remove(candidates[0]) else:",
"i, j in itertools.combinations(range(len(candidates)), 2): qi, qj = candidates[i], candidates[j] if not qi.isdisjoint(qj):",
"return LoopClassification.from_value(f'{loop_classes[fingerprint]}{subtype}') def __str__(self): builder = '' if len(self.tetrads) == 1: builder +=",
"self.nucleotides]) def is_disjoint(self, other) -> bool: return frozenset(self.nucleotides).isdisjoint(frozenset(other.nucleotides)) def center(self) -> numpy.ndarray: return",
"onzm: Optional[ONZM] = field(init=False) gba_classes: List[GbaQuadruplexClassification] = field(init=False) tracts: List[Tract] = field(init=False) loops:",
"'ldp': '13' } fingerprint = ''.join([loop.loop_type.value[0] for loop in self.loops]) if fingerprint not",
"self.loop_class = self.__classify_by_loops() def __classify_onzm(self) -> Optional[ONZM]: if len(self.tetrads) == 1: return None",
"self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse() elif order == (self.nt2,",
"single tetrad\\n' builder += str(self.tetrads[0]) else: builder += f' {self.onzm.value if self.onzm is",
"x not in (i, j, k) and i in self.base_pair_graph[x], self.base_pair_graph[k]): if Tetrad.is_valid(i,",
"metal_atom_names: coordinates = tuple(atom.coordinates()) if coordinates not in used: ions.append(atom) used.add(coordinates) return ions",
"if len(self.tetrads) == 0: return {}, {} ions_channel = defaultdict(list) ions_outside = defaultdict(list)",
"self.nt2, self.nt3 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34 # flip",
"self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() if not self.no_reorder: self.__find_best_chain_order() self.sequence, self.line1,",
"layer: x, y = pair.nt1, pair.nt2 x, y = nucleotides.index(x) + 1 +",
"tie, pick permutation earlier in lexicographical sense if permutation < best_permutation: best_permutation =",
"(lw2, lw1), (lw3, lw2), (lw4, lw3)): if lw_i.name[1] == lw_j.name[2]: return False return",
"+= '\\n' return builder @dataclass class Helix: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D",
"(i, j), self.graph[j]): for l in filter(lambda x: x not in (i, j,",
"transform into (0, 1, 2, 3) ni, nj, nk, nl = map(lambda nt:",
"conflicts: pair, _ = max(conflicts.items(), key=lambda x: (len(x[1]), x[0].nt1)) removed.append(pair) queue.remove(pair) else: orders.update({pair:",
"nt: nt.index) for i in range(1, len(tetrad_nucleotides)): nprev = tetrad_nucleotides[i - 1] ncur",
"== (self.nt2, self.nt1, self.nt4, self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse(),",
"self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() # ONZ and da Silva's classification are",
"if min_distance < 6.0: ions_channel[min_tetrad].append(ion) continue min_distance = math.inf min_tetrad = self.tetrads[0] min_nt",
"1 + shifts[y] helix.write(f'{x}\\t{y}\\t1\\t8\\n') helix.flush() return helix class AnalysisSimple: def __init__(self, structure2d: Structure2D,",
"if pair.nt1 == first and pair.nt2 == last: if pair.score() < pair.reverse().score(): return",
"nt2_2, _, _ = self.tetrad2_nts_best_order v1 = nt1_1.find_atom(\"C1'\").coordinates() - nt1_2.find_atom(\"C1'\").coordinates() v1 = v1",
"# this is required to recalculate ONZ tp.tetrad2.reorder_to_match_other_tetrad(order) def __chain_order_score(self, chain_order: Tuple[str, ...])",
"= nt1_1.find_atom(\"C1'\").coordinates() - nt1_2.find_atom(\"C1'\").coordinates() v1 = v1 / numpy.linalg.norm(v1) v2 = nt2_1.find_atom(\"C1'\").coordinates() -",
"'aaas': GbaTetradClassification.IVa, 'sssa': GbaTetradClassification.IVb, 'aasa': GbaTetradClassification.Va, 'ssas': GbaTetradClassification.Vb, 'assa': GbaTetradClassification.VIa, 'saas': GbaTetradClassification.VIb, 'asss':",
"= self.pair_41, self.pair_12, self.pair_23, self.pair_34 # flip order if necessary if self.pair_12.score() >",
"candidates = set(self.tetrads) - {ti} while candidates: tj = max([tj for tj in",
"__post_init__(self): self.reorder_to_match_5p_3p() self.planarity_deviation = self.__calculate_planarity_deviation() def reorder_to_match_5p_3p(self): # transform into (0, 1, 2,",
"tetrads while tetrads: graph = defaultdict(list) for (ti, tj) in itertools.combinations(tetrads, 2): if",
"Direction = field(init=False) rise: float = field(init=False) twist: float = field(init=False) def __post_init__(self):",
"len(self.tetrad_pairs) > 0: self.tetrad_pairs[0].tetrad1.reorder_to_match_5p_3p() for tp in self.tetrad_pairs: order = (tp.stacked[tp.tetrad1.nt1], tp.stacked[tp.tetrad1.nt2], tp.stacked[tp.tetrad1.nt3],",
"is_next_by_stacking(nts1[i], nts2[i]) else 0 for i in range(4)] score_sequential = [1 if is_next_sequentially(nts1[i],",
"best_score_sequential, best_score_stacking = score, score_sequential, score_stacking best_order = nts2 if best_score == 4:",
"nt: nt.index)}.keys()) def canonical(self) -> List[BasePair3D]: return [base_pair for base_pair in self.base_pairs if",
"prefix: str, suffix: str): fasta = tempfile.NamedTemporaryFile('w+', suffix='.fasta') fasta.write(f'>{prefix}-{suffix}\\n') fasta.write(self.analysis.sequence) fasta.flush() layer1, layer2",
"self.nt1, self.nt4, self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse() elif",
"{'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5, 'VI': 6, 'VII':",
"self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() else: raise RuntimeError(f'Cannot",
"in (i, j), self.graph[j]): for l in filter(lambda x: x not in (i,",
"class Loop: nucleotides: List[Residue3D] loop_type: Optional[LoopType] def __str__(self): return f' {self.loop_type.value if self.loop_type",
"-> Optional[Tetrad]: for tetrad in self.tetrads: if nt in tetrad.nucleotides: return tetrad return",
"13(35), 9738–9745. https://doi.org/10.1002/chem.200701255 :return: Classification according to Webba da Silva or n/a \"\"\"",
"__find_quadruplexes(self): if len(self.tetrad_pairs) == 0: return [Quadruplex(self.tetrads, [], self.structure3d)] quadruplexes = list() tetrads",
"if ncur.index - nprev.index > 1 and ncur.chain == nprev.chain: for tract in",
"Residue3D, nt2: Residue3D) -> bool: return nt1.chain == nt2.chain and abs(nt1.index - nt2.index)",
"nucleotides(self) -> Tuple[Residue3D, Residue3D, Residue3D, Residue3D]: return self.nt1, self.nt2, self.nt3, self.nt4 def __hash__(self):",
"self.stacking_graph = self.structure3d.stacking_graph(self.structure2d) self.tetrads = self.__find_tetrads(self.no_reorder) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices",
"_, _ = self.tetrad1.nucleotides nt2_1, nt2_2, _, _ = self.tetrad2_nts_best_order v1 = nt1_1.find_atom(\"C1'\").coordinates()",
"len(self.tetrads): onz = 'M' counter = Counter([tp.direction.value[0] for tp in self.tetrad_pairs]) direction, support",
"ONZ tp.tetrad2.reorder_to_match_other_tetrad(order) def __chain_order_score(self, chain_order: Tuple[str, ...]) -> int: chain_pairs = [] for",
"1 opening = '([{<' + string.ascii_uppercase closing = ')]}>' + string.ascii_lowercase dotbracket =",
"self.graph[j]): for l in filter(lambda x: x not in (i, j, k) and",
"+ 1 + shifts[x], nucleotides.index(y) + 1 + shifts[y] onz = self.onz_dict[pair] helix.write(f'{x}\\t{y}\\t1\\t{onz_value.get(onz,",
"# transform into (0, 1, 2, 3) ni, nj, nk, nl = map(lambda",
"str = field(init=False) line1: str = field(init=False) line2: str = field(init=False) shifts: Dict[Residue3D,",
"-1 counter = Counter(1 if j - i > 0 else -1 for",
"the same tetrad sign = self.__detect_loop_sign(nt_first, nt_last, tetrad_with_first) if sign is not None:",
"'b' subvariant roman_numerals = {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V':",
"-> float: nt1_1, nt1_2, _, _ = self.tetrad1.nucleotides nt2_1, nt2_2, _, _ =",
"= set() for tetrad in tetrads: chains.update(tetrad.chains()) def check_tetrad(t: Tetrad) -> bool: return",
"__classify_by_loops(self) -> Optional[LoopClassification]: if len(self.loops) != 3 or any([loop.loop_type is None for loop",
"not all([nt.chi_class in (GlycosidicBond.syn, GlycosidicBond.anti) for nt in self.nucleotides]): return None # this",
"= self.structure3d.base_pairs(self.structure2d) self.base_pair_graph = self.structure3d.base_pair_graph(self.structure2d, self.strict) self.base_pair_dict = self.structure3d.base_pair_dict(self.structure2d, self.strict) self.stacking_graph = self.structure3d.stacking_graph(self.structure2d)",
"case of a tie, remove one which has the worst planarity deviation candidates",
"for tract in self.tracts: if nprev in tract.nucleotides and ncur in tract.nucleotides: break",
"self.base_pair_dict = self.structure3d.base_pair_dict(self.structure2d, self.strict) self.stacking_graph = self.structure3d.stacking_graph(self.structure2d) self.tetrads = self.__find_tetrads(self.no_reorder) self.tetrad_scores = self.__calculate_tetrad_scores()",
"Optional[Tetrad]: for tetrad in self.tetrads: if nt in tetrad.nucleotides: return tetrad return None",
"layer2 = [], [] for tetrad in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) helix1",
"nt4: Residue3D pair_12: BasePair3D pair_23: BasePair3D pair_34: BasePair3D pair_41: BasePair3D onz: ONZ =",
"tuple(atom.coordinates()) if coordinates not in used: ions.append(atom) used.add(coordinates) return ions def __assign_ions_to_tetrads(self) \\",
"+ 1 + shifts[x], nucleotides.index(y) + 1 + shifts[y] helix.write(f'{x}\\t{y}\\t1\\t8\\n') helix.flush() return helix",
"t in self.tetrads]) onz, support = counter.most_common()[0] if support != len(self.tetrads): onz =",
"order for pair in queue}) queue, removed = removed, [] order += 1",
"+= self.tetrad_scores[ti][tj][0] order.append(tj) candidates.remove(tj) ti = tj if score > best_score: best_score =",
"nj, nk, nl = (indices.index(x) for x in (ni, nj, nk, nl)) nmin",
"logging.debug(f'Skipping an ion, because it is too far from any tetrad (distance={min_distance})') for",
"chain and chain != nt.chain: sequence += '-' structure += '-' shift_value +=",
"self.nt2, self.nt3, self.nt4 def __hash__(self): return hash(frozenset([self.nt1, self.nt2, self.nt3, self.nt4])) def __str__(self): return",
"quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) return quadruplexes def __filter_tetrad_pairs(self, tetrads: List[Tetrad]) -> List[TetradPair]: chains =",
"__ions_channel_str(self) -> str: if self.ions_channel: return 'ions_channel=' + ','.join([atom.atomName for atom in self.ions_channel])",
"'ions_outside=' + ' '.join(result) return '' @dataclass class TetradPair: tetrad1: Tetrad tetrad2: Tetrad",
"return tetrad_pairs def __find_helices(self): helices = [] helix_tetrads = [] helix_tetrad_pairs = []",
"j in itertools.combinations(range(len(candidates)), 2): qi, qj = candidates[i], candidates[j] if not qi.isdisjoint(qj): qi.update(qj)",
"return quadruplexes def __filter_tetrad_pairs(self, tetrads: List[Tetrad]) -> List[TetradPair]: chains = set() for tetrad",
"\\ f'planarity={round(self.planarity_deviation, 2)} ' \\ f'{self.__ions_channel_str()} ' \\ f'{self.__ions_outside_str()}\\n' def chains(self) -> Set[str]:",
"tetrad2: Tetrad stacked: Dict[Residue3D, Residue3D] tetrad2_nts_best_order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D] = field(init=False) direction:",
"ions def __generate_twoline_dotbracket(self) -> Tuple[str, str, str, Dict[Residue3D, int]]: layer1, layer2 = [],",
"import numpy from eltetrado.model import Atom3D, Structure3D, Structure2D, BasePair3D, Residue3D, GlycosidicBond, ONZ, \\",
"subprocess import tempfile from collections import defaultdict, Counter from dataclasses import dataclass, field",
"(coord[2] for coord in coords) return numpy.array((sum(xs) / len(coords), sum(ys) / len(coords), sum(zs)",
"nt, tetrad_with_first) if sign is not None: return LoopType.from_value(f'propeller{sign}') logging.warning(f'Failed to classify the",
"logging.error(f'Unknown loop classification: {fingerprint}') return None subtype = 'a' if self.loops[0 if fingerprint",
"if len(self.tetrads) == 1: builder += ' single tetrad\\n' builder += str(self.tetrads[0]) else:",
"ONZ.N_PLUS elif order == (2, 3, 1): return ONZ.N_MINUS elif order == (2,",
"self.__find_ions() self.__assign_ions_to_tetrads() def __find_tetrads(self, no_reorder=False) -> List[Tetrad]: # search for a tetrad: i",
"' \\ f'{self.__ions_channel_str()} ' \\ f'{self.__ions_outside_str()}\\n' def chains(self) -> Set[str]: return set([nt.chain for",
"remove tetrad which conflicts the most with others # in case of a",
"= 'h' counter = Counter([t.onz.value[1] for t in self.tetrads]) plus_minus, support = counter.most_common()[0]",
"nk, nl = (indices.index(x) for x in (ni, nj, nk, nl)) while ni",
"has all classes mapped to fingerprints gba_classes = { 'aass': GbaTetradClassification.Ia, 'ssaa': GbaTetradClassification.Ib,",
"nl, ni, nj, nk order = (nj, nk, nl) if order == (1,",
"f'{loop}\\n' builder += '\\n' return builder @dataclass class Helix: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair]",
"stacked[ti.nt3], stacked[ti.nt4]) tj.reorder_to_match_other_tetrad(order) return tetrad_pairs def __find_helices(self): helices = [] helix_tetrads = []",
"+ shifts[y] onz = self.onz_dict[pair] helix.write(f'{x}\\t{y}\\t1\\t{onz_value.get(onz, 7)}\\n') if canonical: for pair in canonical:",
"# in case of a tie, pick permutation earlier in lexicographical sense if",
"'b' return LoopClassification.from_value(f'{loop_classes[fingerprint]}{subtype}') def __str__(self): builder = '' if len(self.tetrads) == 1: builder",
"== first: if pair.score() < pair.reverse().score(): return '+' return '-' return None def",
"< 6.0: ions_channel[min_tetrad].append(ion) continue min_distance = math.inf min_tetrad = self.tetrads[0] min_nt = min_tetrad.nt1",
"'4', 'pdp': '5', 'lll': '6', 'llp': '7', 'lpl': '8', 'pll': '9', 'pdl': '10',",
"nj, nk, nl)) ni, nj, nk, nl = (indices.index(x) for x in (ni,",
"Residue3D nt4: Residue3D pair_12: BasePair3D pair_23: BasePair3D pair_34: BasePair3D pair_41: BasePair3D onz: ONZ",
"ti, tj in itertools.combinations(self.tetrads, 2): nts1 = ti.nucleotides best_score = 0 best_score_sequential =",
"!= len(self.tetrads): onz = 'M' counter = Counter([tp.direction.value[0] for tp in self.tetrad_pairs]) direction,",
"self.base_pair_dict[(i, j)] pair_23 = self.base_pair_dict[(j, k)] pair_34 = self.base_pair_dict[(k, l)] pair_41 = self.base_pair_dict[(l,",
"Tract: nucleotides: List[Residue3D] def __str__(self): return f' {\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass",
"Residue3D], List[Atom3D]]]: if len(self.tetrads) == 0: return {}, {} ions_channel = defaultdict(list) ions_outside",
"return False def center_of_mass(atoms): coords = [atom.coordinates() for atom in atoms] xs =",
"p.nt2.chain if c1 != c2 and c1 in chain_order and c2 in chain_order:",
"best_score_stacking = score, score_sequential, score_stacking best_order = nts2 if best_score == 4: break",
"len(self.tetrads) == 1: builder += ' single tetrad\\n' builder += str(self.tetrads[0]) else: builder",
"+= str(helix) builder += f'{self.sequence}\\n{self.line1}\\n{self.line2}' return builder def __chain_order(self) -> List[str]: only_nucleic_acids =",
"Analysis(structure2d, structure3d, strict, no_reorder, stacking_mismatch) def has_tetrad(structure2d: Structure2D, structure3d: Structure3D) -> bool: structure",
"len(coords), sum(zs) / len(coords))) def eltetrado(structure2d: Structure2D, structure3d: Structure3D, strict: bool, no_reorder: bool,",
"best_order = tetrads for ti in tetrads: score = 0 order = [ti]",
"+= str(self.tetrads[0]) else: builder += f' {self.onzm.value if self.onzm is not None else",
"loop is in the same tetrad sign = self.__detect_loop_sign(nt_first, nt_last, tetrad_with_first) if sign",
"self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse() elif order == (self.nt3, self.nt2, self.nt1, self.nt4): self.pair_12, self.pair_23,",
"return Direction.parallel elif count == 2: # two in +, one in -",
"worst planarity deviation candidates = sorted(tetrads, key=lambda t: (len(graph[t]), t.planarity_deviation), reverse=True) if len(graph[candidates[0]])",
"x in (ni, nj, nk, nl)) while ni != 0: ni, nj, nk,",
"= self.__classify_by_loops() def __classify_onzm(self) -> Optional[ONZM]: if len(self.tetrads) == 1: return None if",
"strict: bool no_reorder: bool stacking_mismatch: int base_pairs: List[BasePair3D] = field(init=False) base_pair_graph: Dict[Residue3D, List[Residue3D]]",
"# discard 'a' or 'b' subvariant roman_numerals = {'I': 1, 'II': 2, 'III':",
"set() for tetrad in tetrads: chains.update(tetrad.chains()) def check_tetrad(t: Tetrad) -> bool: return not",
"elif order == (self.nt3, self.nt2, self.nt1, self.nt4): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23.reverse(),",
"self.tracts: builder += f'{tract}\\n' if self.loops: builder += '\\n Loops:\\n' for loop in",
"self.pair_34.reverse(), self.pair_23.reverse() elif order == (self.nt1, self.nt4, self.nt3, self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41",
"chain in chain_order: for nt in self.structure3d.residues: if nt.chain == chain: nt.index =",
"sorted(only_nucleic_acids, key=lambda nt: nt.index)}.keys()) def canonical(self) -> List[BasePair3D]: return [base_pair for base_pair in",
"made of 's' for syn or 'a' for anti fingerprint = ''.join([nt.chi_class.value[0] for",
"[Tract(nts) for nts in tracts] def __find_loops(self) -> List[Loop]: if len(self.tetrads) == 1:",
"pair.nt1, pair.nt2 x, y = nucleotides.index(x) + 1 + shifts[x], nucleotides.index(y) + 1",
"(lw4, lw3)): if lw_i.name[1] == lw_j.name[2]: return False return True nt1: Residue3D nt2:",
"filter(lambda x: x not in (i, j, k) and i in self.base_pair_graph[x], self.base_pair_graph[k]):",
"a loop is in the same tetrad sign = self.__detect_loop_sign(nt_first, nt_last, tetrad_with_first) if",
"nmin = min(ni, nj, nk, nl) if nmin == ni: pass elif nmin",
"__str__(self): builder = '' if len(self.tetrads) == 1: builder += ' single tetrad\\n'",
"= self.__group_related_chains() final_order = [] for chains in chain_groups: best_permutation, best_score = chains,",
"= field(init=False) planarity_deviation: float = field(init=False) ions_channel: List[Atom3D] = field(default_factory=list) ions_outside: Dict[Residue3D, List[Atom3D]]",
"in range(4)] score = sum([max(score_stacking[i], score_sequential[i]) for i in range(4)]) score_sequential = sum(score_sequential)",
"helix_tetrad_pairs, self.structure3d)) for tetrad in self.tetrads: if not any([tetrad in helix.tetrads for helix",
"tract to check what pairs with nt_first for nt in tract_with_last.nucleotides: if nt",
"'assa': GbaTetradClassification.VIa, 'saas': GbaTetradClassification.VIb, 'asss': GbaTetradClassification.VIIa, 'saaa': GbaTetradClassification.VIIb, 'aaaa': GbaTetradClassification.VIIIa, 'ssss': GbaTetradClassification.VIIIb }",
"fingerprints gba_classes = { 'aass': GbaTetradClassification.Ia, 'ssaa': GbaTetradClassification.Ib, 'asas': GbaTetradClassification.IIa, 'sasa': GbaTetradClassification.IIb, 'asaa':",
"= self.base_pair_dict[(i, j)] pair_23 = self.base_pair_dict[(j, k)] pair_34 = self.base_pair_dict[(k, l)] pair_41 =",
"t in h.tetrads: candidates.add(frozenset([t.nt1.chain, t.nt2.chain, t.nt3.chain, t.nt4.chain])) candidates = [set(c) for c in",
"pair.nt1 == first and pair.nt2 == last: if pair.score() < pair.reverse().score(): return '-'",
"List[Residue3D]] = field(init=False) base_pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = field(init=False) stacking_graph: Dict[Residue3D, List[Residue3D]] =",
"n4), (n2, n3, n4, n1), (n3, n4, n1, n2), (n4, n1, n2, n3),",
"in chain_pairs: sum_sq += (chain_order.index(c1) - chain_order.index(c2)) ** 2 return sum_sq def __find_ions(self)",
"'s' for syn or 'a' for anti fingerprint = ''.join([nt.chi_class.value[0] for nt in",
"tetrad.pair_34, tetrad.pair_41]: # main check if pair.nt1 == first and pair.nt2 == last:",
"chain_order: Tuple[str, ...]) -> int: chain_pairs = [] for h in self.helices: for",
"j), self.base_pair_graph[j]): for l in filter(lambda x: x not in (i, j, k)",
"_, _ = self.tetrad2_nts_best_order v1 = nt1_1.find_atom(\"C1'\").coordinates() - nt1_2.find_atom(\"C1'\").coordinates() v1 = v1 /",
"tetrad_pair.tetrad2_nts_best_order[1], tetrad_pair.tetrad1.nt3: tetrad_pair.tetrad2_nts_best_order[2], tetrad_pair.tetrad1.nt4: tetrad_pair.tetrad2_nts_best_order[3], } for i in range(4): tracts[i].append(nt_dict[tracts[i][-1]]) return [Tract(nts)",
"helix2.name, output_pdf], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if run.returncode == 0: print('\\nPlot:', output_pdf) else: logging.error(f'Failed to",
"ions_outside = defaultdict(list) for ion in self.ions: min_distance = math.inf min_tetrad = self.tetrads[0]",
"self.tetrad2_nts_best_order v1 = nt1_1.find_atom(\"C1'\").coordinates() - nt1_2.find_atom(\"C1'\").coordinates() v1 = v1 / numpy.linalg.norm(v1) v2 =",
"not None: # search along the tract to check what pairs with nt_first",
"quadruplex with {len(self.tetrads)} tetrads\\n' builder += str(self.tetrad_pairs[0].tetrad1) for tetrad_pair in self.tetrad_pairs: builder +=",
"k, l, pair_12, pair_23, pair_34, pair_41)) # build graph of tetrads while tetrads:",
"= ''.join([loop.loop_type.value[0] for loop in self.loops]) if fingerprint not in loop_classes: logging.error(f'Unknown loop",
"itertools.permutations(chains): self.__reorder_chains(permutation) classifications = [t.onz for h in self.helices for t in h.tetrads]",
"= math.inf min_tetrad = self.tetrads[0] for tetrad in self.tetrads: distance = numpy.linalg.norm(ion.coordinates() -",
"if score >= (4 - self.stacking_mismatch): helix_tetrads.append(tj) helix_tetrad_pairs.append(tp) else: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) helix_tetrads",
"if tetrad_with_first is None or tetrad_with_last is None: logging.warning(f'Failed to classify the loop",
"channel if min_distance < 6.0: ions_channel[min_tetrad].append(ion) continue min_distance = math.inf min_tetrad = self.tetrads[0]",
"== (3, 1, 2): return ONZ.Z_MINUS raise RuntimeError(f'Impossible combination: {ni} {nj} {nk} {nl}')",
"[] loops = [] tetrad_nucleotides = sorted([nt for tetrad in self.tetrads for nt",
"numpy.linalg.norm(v2) return math.degrees(numpy.arccos(numpy.clip(numpy.dot(v1, v2), -1.0, 1.0))) def __str__(self): return f' direction={self.direction.value} rise={round(self.rise, 2)}",
"List[Tract] = field(init=False) loops: List[Loop] = field(init=False) loop_class: Optional[LoopClassification] = field(init=False) def __post_init__(self):",
"= { 'ppp': '1', 'ppl': '2', 'plp': '3', 'lpp': '4', 'pdp': '5', 'lll':",
"fingerprint = ''.join([nt.chi_class.value[0] for nt in self.nucleotides]) # this dict has all classes",
"return center_of_mass(self.outer_and_inner_atoms()) def outer_and_inner_atoms(self) -> List[Atom3D]: return list(map(lambda residue: residue.outermost_atom, self.nucleotides)) + \\",
"Tetrad) -> bool: return not t.chains().isdisjoint(chains) def check_pair(tp: TetradPair) -> bool: return check_tetrad(tp.tetrad1)",
"-> k -> l # ^--------------^ tetrads = [] for i in self.base_pair_graph:",
"for tetrad in self.tetrads: distance = numpy.linalg.norm(ion.coordinates() - tetrad.center()) if distance < min_distance:",
"= sorted([pair.nt1, pair.nt2]) dotbracket[nt1] = opening[order] dotbracket[nt2] = closing[order] sequence = '' structure",
"'8', 'pll': '9', 'pdl': '10', 'ldl': '11', 'dpd': '12', 'ldp': '13' } fingerprint",
"in chain_order: chain_pairs.append([c1, c2]) sum_sq = 0 for c1, c2 in chain_pairs: sum_sq",
"-> Tuple[Residue3D, Residue3D, Residue3D, Residue3D]: return self.nt1, self.nt2, self.nt3, self.nt4 def __hash__(self): return",
"= score best_order = order if best_score == (len(self.tetrads) - 1) * 4:",
"self.__find_quadruplexes() def __find_quadruplexes(self): if len(self.tetrad_pairs) == 0: return [Quadruplex(self.tetrads, [], self.structure3d)] quadruplexes =",
"no_reorder: bool, stacking_mismatch: int) -> Analysis: return Analysis(structure2d, structure3d, strict, no_reorder, stacking_mismatch) def",
"= counter.most_common()[0] if support != len(self.tetrads): plus_minus = '*' return ONZM.from_value(f'{onz}{direction}{plus_minus}') def __classify_by_gba(self)",
"nmin == nk: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt3, self.nt4, self.nt1, self.nt2 self.pair_12,",
"self.pair_41, self.pair_12 elif order == (self.nt3, self.nt4, self.nt1, self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41",
"layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) sequence, line1, shifts = self.__elimination_conflicts(layer1) _, line2, _ =",
"self.nt4 = self.nt3, self.nt4, self.nt1, self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41,",
"3, 2): return ONZ.N_PLUS elif order == (2, 3, 1): return ONZ.N_MINUS elif",
"= defaultdict(list) for (ti, tj) in itertools.combinations(tetrads, 2): if not ti.is_disjoint(tj): graph[ti].append(tj) graph[tj].append(ti)",
"__to_helix(self, layer: List[BasePair3D], canonical: Optional[List[BasePair3D]] = None) -> tempfile.NamedTemporaryFile(): onz_value = {ONZ.O_PLUS: 1,",
"not qi.isdisjoint(qj): qi.update(qj) del candidates[j] changed = True break candidates = sorted(candidates, key=lambda",
"self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() else: raise RuntimeError(f'Cannot apply order: {order}') self.nt1, self.nt2, self.nt3, self.nt4",
"self.__chain_order_score(permutation) score = (onz_score, chain_order_score) if score < best_score: best_score = score best_permutation",
"= self.__calculate_twist() def __determine_direction(self) -> Direction: indices1 = list(map(lambda nt: nt.index, self.tetrad1.nucleotides)) indices2",
"removed.append(pair) queue.remove(pair) else: orders.update({pair: order for pair in queue}) queue, removed = removed,",
"stacked = {nts1[i]: nts2[i] for i in range(4)} stacked.update({v: k for k, v",
"self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34 elif order == (self.nt4,",
"= list(self.tetrads) best_score = 0 best_order = tetrads for ti in tetrads: score",
"sum(c.score() for c in classifications) chain_order_score = self.__chain_order_score(permutation) score = (onz_score, chain_order_score) if",
"field(init=False) def __post_init__(self): self.base_pairs = self.structure3d.base_pairs(self.structure2d) self.base_pair_graph = self.structure3d.base_pair_graph(self.structure2d, self.strict) self.base_pair_dict = self.structure3d.base_pair_dict(self.structure2d,",
"suffix='.helix') helix.write(f'#{len(self.analysis.sequence) + 1}\\n') helix.write('i\\tj\\tlength\\tvalue\\n') for pair in layer: x, y = pair.nt1,",
"helix.write(f'{x}\\t{y}\\t1\\t{onz_value.get(onz, 7)}\\n') if canonical: for pair in canonical: x, y = pair.nt1, pair.nt2",
"= self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() def __group_related_chains(self) -> List[List[str]]: candidates",
"j)] pair_23 = self.base_pair_dict[(j, k)] pair_34 = self.base_pair_dict[(k, l)] pair_41 = self.base_pair_dict[(l, i)]",
"n/a' builder += f' quadruplex with {len(self.tetrads)} tetrads\\n' builder += str(self.tetrad_pairs[0].tetrad1) for tetrad_pair",
"\".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass class Loop: nucleotides: List[Residue3D] loop_type: Optional[LoopType] def __str__(self):",
"in stacked.items()}) tetrad_pairs.append(TetradPair(ti, tj, stacked)) order = (stacked[ti.nt1], stacked[ti.nt2], stacked[ti.nt3], stacked[ti.nt4]) tj.reorder_to_match_other_tetrad(order) return",
"tetrads: score = 0 order = [ti] candidates = set(self.tetrads) - {ti} while",
"continue logging.debug(f'Skipping an ion, because it is too far from any tetrad (distance={min_distance})')",
"t.pair_23, t.pair_34, t.pair_41]: c1 = p.nt1.chain c2 = p.nt2.chain if c1 != c2",
"tetrad_pairs: List[TetradPair] = field(init=False) helices: List[Helix] = field(init=False) ions: List[Atom3D] = field(init=False) sequence:",
"bool no_reorder: bool stacking_mismatch: int base_pairs: List[BasePair3D] = field(init=False) base_pair_graph: Dict[Residue3D, List[Residue3D]] =",
"len(x), reverse=True) groups = [] for candidate in candidates: if any([group.issuperset(candidate) for group",
"self.nucleotides] return numpy.linalg.norm(center_of_mass(outer) - center_of_mass(inner)) @property def nucleotides(self) -> Tuple[Residue3D, Residue3D, Residue3D, Residue3D]:",
"in range(1, len(tetrad_nucleotides)): nprev = tetrad_nucleotides[i - 1] ncur = tetrad_nucleotides[i] if ncur.index",
"tp.tetrad2.reorder_to_match_5p_3p() # this is required to recalculate ONZ tp.tetrad2.reorder_to_match_other_tetrad(order) def __chain_order_score(self, chain_order: Tuple[str,",
"best_order[i - 1], best_order[i] score = self.tetrad_scores[ti][tj][0] if score >= (4 - stacking_mismatch):",
"tp.stacked[tp.tetrad1.nt3], tp.stacked[tp.tetrad1.nt4]) tp.tetrad2.reorder_to_match_5p_3p() # this is required to recalculate ONZ tp.tetrad2.reorder_to_match_other_tetrad(order) def __chain_order_score(self,",
"@dataclass class Loop: nucleotides: List[Residue3D] loop_type: Optional[LoopType] def __str__(self): return f' {self.loop_type.value if",
"-1 for i, j in zip(indices1, indices2)) direction, count = counter.most_common()[0] if count",
"'2', 'plp': '3', 'lpp': '4', 'pdp': '5', 'lll': '6', 'llp': '7', 'lpl': '8',",
"lw2 = pair_dictionary[(nt2, nt3)].lw lw3 = pair_dictionary[(nt3, nt4)].lw lw4 = pair_dictionary[(nt4, nt1)].lw for",
"nk, nl)) nmin = min(ni, nj, nk, nl) if nmin == ni: pass",
"else: builder += f' n/a' builder += f' quadruplex with {len(self.tetrads)} tetrads\\n' builder",
"-> Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]]: def is_next_by_stacking(nt1: Residue3D, nt2: Residue3D) -> bool:",
"Tuple[Residue3D, Residue3D, Residue3D, Residue3D] = field(init=False) direction: Direction = field(init=False) rise: float =",
"n1, n4, n3)] for nts2 in viable_permutations: score_stacking = [1 if is_next_by_stacking(nts1[i], nts2[i])",
"tj = tp.tetrad1, tp.tetrad2 if not helix_tetrads: helix_tetrads.append(ti) score = self.tetrad_scores[helix_tetrads[-1]][tj][0] if score",
"nk, nl = nl, ni, nj, nk order = (nj, nk, nl) if",
"orders.update({pair: order for pair in queue}) queue, removed = removed, [] order +=",
"None def __classify_by_loops(self) -> Optional[LoopClassification]: if len(self.loops) != 3 or any([loop.loop_type is None",
"t.gba_class if gba is not None: gbas.add(gba.value[:-1]) # discard 'a' or 'b' subvariant",
"nt # TODO: verify threshold of 3A between an ion and an atom",
"in self.tetrad_pairs: builder += str(tetrad_pair) builder += str(tetrad_pair.tetrad2) if self.tracts: builder += '\\n",
"in filter(lambda x: x != i, self.graph[i]): for k in filter(lambda x: x",
"= (coord[2] for coord in coords) return numpy.array((sum(xs) / len(coords), sum(ys) / len(coords),",
"class Quadruplex: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D onzm: Optional[ONZM] = field(init=False) gba_classes:",
"x not in (i, j, k) and x in self.graph[i], self.graph[k]): if Tetrad.is_valid(i,",
"ions])}]') return 'ions_outside=' + ' '.join(result) return '' @dataclass class TetradPair: tetrad1: Tetrad",
"None: return LoopType.from_value(f'propeller{sign}') logging.warning(f'Failed to classify the loop between {nt_first} and {nt_last}') return",
"= tempfile.NamedTemporaryFile('w+', suffix='.helix') helix.write(f'#{len(self.analysis.sequence) + 1}\\n') helix.write('i\\tj\\tlength\\tvalue\\n') for pair in layer: x, y",
"self.structure3d)) tetrads = list() tetrads.append(tetrad) quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) return quadruplexes def __filter_tetrad_pairs(self, tetrads:",
"= nt2_1.find_atom(\"C1'\").coordinates() - nt2_2.find_atom(\"C1'\").coordinates() v2 = v2 / numpy.linalg.norm(v2) return math.degrees(numpy.arccos(numpy.clip(numpy.dot(v1, v2), -1.0,",
"sequence, structure, shifts def __str__(self): builder = f'Chain order: {\" \".join(self.__chain_order())}\\n' for helix",
"[] for h in self.helices: for t in h.tetrads: for p in [t.pair_12,",
"GbaTetradClassification.VIa, 'saas': GbaTetradClassification.VIb, 'asss': GbaTetradClassification.VIIa, 'saaa': GbaTetradClassification.VIIb, 'aaaa': GbaTetradClassification.VIIIa, 'ssss': GbaTetradClassification.VIIIb } if",
"= self.__elimination_conflicts(layer1) _, line2, _ = self.__elimination_conflicts(layer2) return sequence, line1, line2, shifts def",
"directions 5' -> 3' as +1 or -1 counter = Counter(1 if j",
"self.__to_helix(layer1, self.analysis.canonical() if self.complete2d else []) helix2 = self.__to_helix(layer2) currdir = os.path.dirname(os.path.realpath(__file__)) output_pdf",
"= list() tetrads.append(tetrad) quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) return quadruplexes def __filter_tetrad_pairs(self, tetrads: List[Tetrad]) ->",
"TODO: verify threshold of 3A between an ion and an atom if min_distance",
"create a 4-letter string made of 's' for syn or 'a' for anti",
"nt: Residue3D) -> Optional[Tract]: for tract in self.tracts: if nt in tract.nucleotides: return",
"- {ti} while candidates: tj = max([tj for tj in candidates], key=lambda tk:",
"self.structure3d.residues)) loop_type = self.__detect_loop_type(nprev, ncur) loops.append(Loop(nts, loop_type)) return loops def __detect_loop_type(self, nt_first: Residue3D,",
"= v2 / numpy.linalg.norm(v2) return math.degrees(numpy.arccos(numpy.clip(numpy.dot(v1, v2), -1.0, 1.0))) def __str__(self): return f'",
"sequence = '' structure = '' shifts = dict() shift_value = 0 chain",
"Counter([t.onz.value[0] for t in self.tetrads]) onz, support = counter.most_common()[0] if support != len(self.tetrads):",
"from typing import Dict, Iterable, List, Tuple, Optional, Set import numpy from eltetrado.model",
"f'{self.nt1.full_name} {self.nt2.full_name} {self.nt3.full_name} {self.nt4.full_name} ' \\ f'{self.pair_12.lw.value} {self.pair_23.lw.value} {self.pair_34.lw.value} {self.pair_41.lw.value} ' \\ f'{self.onz.value}",
"def __post_init__(self): self.onzm = self.__classify_onzm() self.gba_classes = self.__classify_by_gba() self.tracts = self.__find_tracts() self.loops =",
"of a loop is in the same tetrad sign = self.__detect_loop_sign(nt_first, nt_last, tetrad_with_first)",
"check what pairs with nt_first for nt in tract_with_last.nucleotides: if nt in tetrad_with_first.nucleotides:",
"reverse check if pair.nt1 == last and pair.nt2 == first: if pair.score() <",
"GbaTetradClassification.Vb, 'assa': GbaTetradClassification.VIa, 'saas': GbaTetradClassification.VIb, 'asss': GbaTetradClassification.VIIa, 'saaa': GbaTetradClassification.VIIb, 'aaaa': GbaTetradClassification.VIIIa, 'ssss': GbaTetradClassification.VIIIb",
"field(init=False) twist: float = field(init=False) def __post_init__(self): self.tetrad2_nts_best_order = ( self.stacked[self.tetrad1.nt1], self.stacked[self.tetrad1.nt2], self.stacked[self.tetrad1.nt3],",
"@dataclass class Quadruplex: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D onzm: Optional[ONZM] = field(init=False)",
"check_tetrad(tp.tetrad2) return list(filter(check_pair, self.tetrad_pairs)) def __str__(self): builder = '' if len(self.tetrads) > 1:",
"1 for nt in self.structure3d.residues: if nt.chain not in chain_order: nt.index = i",
"and {nt_last}') return None if tetrad_with_first == tetrad_with_last: # diagonal or laterals happen",
"# in case of a tie, remove one which has the worst planarity",
"'5', 'lll': '6', 'llp': '7', 'lpl': '8', 'pll': '9', 'pdl': '10', 'ldl': '11',",
"builder += '\\n Tracts:\\n' for tract in self.tracts: builder += f'{tract}\\n' if self.loops:",
"Tuple[Residue3D, Residue3D, Residue3D, Residue3D]): if order == (self.nt1, self.nt2, self.nt3, self.nt4): pass elif",
"for nt in tetrad.nucleotides], key=lambda nt: nt.index) for i in range(1, len(tetrad_nucleotides)): nprev",
"onz.value, classifications))}') self.tetrads = self.__find_tetrads(True) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices =",
"tp.tetrad2.reorder_to_match_other_tetrad(order) def __chain_order_score(self, chain_order: Tuple[str, ...]) -> int: chain_pairs = [] for h",
"for tract in self.tracts: builder += f'{tract}\\n' if self.loops: builder += '\\n Loops:\\n'",
"if len(graph[candidates[0]]) > 0: tetrads.remove(candidates[0]) else: break return sorted(tetrads, key=lambda t: min(map(lambda nt:",
") self.direction = self.__determine_direction() self.rise = self.__calculate_rise() self.twist = self.__calculate_twist() def __determine_direction(self) ->",
"= field(init=False) direction: Direction = field(init=False) rise: float = field(init=False) twist: float =",
"self.tetrad_scores[ti][tj][1:] stacked = {nts1[i]: nts2[i] for i in range(4)} stacked.update({v: k for k,",
"self.nt4])) def __str__(self): return f' ' \\ f'{self.nt1.full_name} {self.nt2.full_name} {self.nt3.full_name} {self.nt4.full_name} ' \\",
"5'-3' order self.onz = self.__classify_onz() self.gba_class = self.__classify_by_gba() def reorder_to_match_other_tetrad(self, order: Tuple[Residue3D, Residue3D,",
"score = self.tetrad_scores[ti][tj][0] if score >= (4 - stacking_mismatch): nts1, nts2 = self.tetrad_scores[ti][tj][1:]",
"List[Atom3D] = field(default_factory=list) ions_outside: Dict[Residue3D, List[Atom3D]] = field(default_factory=dict) def __post_init__(self): self.reorder_to_match_5p_3p() self.planarity_deviation =",
"return nt1.chain == nt2.chain and abs(nt1.index - nt2.index) == 1 tetrad_scores = defaultdict(dict)",
"t.nt3.chain, t.nt4.chain])) candidates = [set(c) for c in candidates] changed = True while",
"self.pair_41, self.pair_12, self.pair_23, self.pair_34 elif order == (self.nt4, self.nt3, self.nt2, self.nt1): self.pair_12, self.pair_23,",
"tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D quadruplexes: List[Quadruplex] = field(init=False) def __post_init__(self): self.quadruplexes",
"logging.debug( f'Checking reorder: {\" \".join(permutation)} {\" \".join(map(lambda c: c.value, classifications))}') onz_score = sum(c.score()",
"= field(init=False) helices: List[Helix] = field(init=False) ions: List[Atom3D] = field(init=False) sequence: str =",
"nt in tetrad.nucleotides: for atom in nt.atoms: distance = numpy.linalg.norm(ion.coordinates() - atom.coordinates()) if",
"tetrad.chains().isdisjoint(tetrads[-1].chains()): quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) tetrads = list() tetrads.append(tetrad) quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) return quadruplexes",
"[nt.outermost_atom for nt in self.nucleotides] inner = [nt.innermost_atom for nt in self.nucleotides] return",
"to check what pairs with nt_first for nt in tract_with_last.nucleotides: if nt in",
"tetrad_with_first == tetrad_with_last: # diagonal or laterals happen when first and last nt",
"logging import math import os import string import subprocess import tempfile from collections",
"_, line2, _ = self.__elimination_conflicts(layer2) return sequence, line1, line2, shifts def __elimination_conflicts(self, pairs:",
"tetrad in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) helix1 = self.__to_helix(layer1, self.analysis.canonical() if self.complete2d",
"__str__(self): return f' {self.loop_type.value if self.loop_type else \"n/a\"} ' \\ f'{\", \".join(map(lambda nt:",
"in self.tetrads: gba = t.gba_class if gba is not None: gbas.add(gba.value[:-1]) # discard",
"= numpy.linalg.norm(ion.coordinates() - atom.coordinates()) if distance < min_distance: min_distance = distance min_tetrad =",
"else: orders.update({pair: order for pair in queue}) queue, removed = removed, [] order",
"1}\\n') helix.write('i\\tj\\tlength\\tvalue\\n') for pair in layer: x, y = pair.nt1, pair.nt2 x, y",
"field(init=False) ions_channel: List[Atom3D] = field(default_factory=list) ions_outside: Dict[Residue3D, List[Atom3D]] = field(default_factory=dict) def __post_init__(self): self.reorder_to_match_5p_3p()",
"False return True nt1: Residue3D nt2: Residue3D nt3: Residue3D nt4: Residue3D pair_12: BasePair3D",
"tract return None def __detect_loop_sign(self, first: Residue3D, last: Residue3D, tetrad: Tetrad) -> Optional[str]:",
"self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() if not self.no_reorder: self.__find_best_chain_order()",
"if order == (self.nt1, self.nt2, self.nt3, self.nt4): pass elif order == (self.nt2, self.nt3,",
"tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]} def visualize(self, prefix: str, suffix: str): fasta = tempfile.NamedTemporaryFile('w+', suffix='.fasta')",
"pair_dictionary[(nt4, nt1)].lw for lw_i, lw_j in ((lw1, lw4), (lw2, lw1), (lw3, lw2), (lw4,",
"= field(init=False) line2: str = field(init=False) shifts: Dict[Residue3D, int] = field(init=False) def __post_init__(self):",
"for nt in self.nucleotides]): return None # this will create a 4-letter string",
"c2 and c1 in chain_order and c2 in chain_order: chain_pairs.append([c1, c2]) sum_sq =",
"self.tetrad_pairs[0].tetrad1.reorder_to_match_5p_3p() for tp in self.tetrad_pairs: order = (tp.stacked[tp.tetrad1.nt1], tp.stacked[tp.tetrad1.nt2], tp.stacked[tp.tetrad1.nt3], tp.stacked[tp.tetrad1.nt4]) tp.tetrad2.reorder_to_match_5p_3p() #",
"stacked[ti.nt2], stacked[ti.nt3], stacked[ti.nt4]) tj.reorder_to_match_other_tetrad(order) return tetrad_pairs def __find_helices(self): helices = [] helix_tetrads =",
"self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) helix1 = self.__to_helix(layer1, self.analysis.canonical() if self.complete2d else [])",
"k in filter(lambda x: x not in (i, j), self.graph[j]): for l in",
"return gba_classes[fingerprint] def __calculate_planarity_deviation(self) -> float: outer = [nt.outermost_atom for nt in self.nucleotides]",
"in case of a tie, pick permutation earlier in lexicographical sense if permutation",
"2: # two in +, one in - direction return Direction.antiparallel return Direction.hybrid",
"nt in self.structure3d.residues: if nt.chain not in chain_order: nt.index = i i +=",
"'asaa': GbaTetradClassification.IIIa, 'sass': GbaTetradClassification.IIIb, 'aaas': GbaTetradClassification.IVa, 'sssa': GbaTetradClassification.IVb, 'aasa': GbaTetradClassification.Va, 'ssas': GbaTetradClassification.Vb, 'assa':",
"f' quadruplex with {len(self.tetrads)} tetrads\\n' builder += str(self.tetrad_pairs[0].tetrad1) for tetrad_pair in self.tetrad_pairs: builder",
"j, k) and x in self.graph[i], self.graph[k]): if Tetrad.is_valid(i, j, k, l, self.pair_dict):",
"numpy.linalg.norm(center_of_mass(outer) - center_of_mass(inner)) @property def nucleotides(self) -> Tuple[Residue3D, Residue3D, Residue3D, Residue3D]: return self.nt1,",
"ni != 0: ni, nj, nk, nl = nl, ni, nj, nk order",
"f' ' \\ f'{self.nt1.full_name} {self.nt2.full_name} {self.nt3.full_name} {self.nt4.full_name} ' \\ f'{self.pair_12.lw.value} {self.pair_23.lw.value} {self.pair_34.lw.value} {self.pair_41.lw.value}",
"= field(init=False) tetrads: List[Tetrad] = field(init=False) tetrad_scores: Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]] =",
"self.helices = self.__find_helices() def __group_related_chains(self) -> List[List[str]]: candidates = set() for h in",
"if Tetrad.is_valid(i, j, k, l, self.pair_dict): tetrads.add(frozenset([i, j, k, l])) if len(tetrads) >",
"builder += f' {\",\".join(map(lambda gba: gba.value, self.gba_classes))}' if self.loop_class: builder += f' {self.loop_class.value}",
"helix.tetrads for helix in helices]): helices.append(Helix([tetrad], [], self.structure3d)) return helices def __find_best_chain_order(self): chain_groups",
"for candidate in candidates: if any([group.issuperset(candidate) for group in groups]): continue groups.append(candidate) return",
"= structure3d.base_pair_dict(structure2d) def has_tetrads(self): tetrads = set() for i in self.graph: for j",
"sign is not None: return LoopType.from_value(f'lateral{sign}') return LoopType.diagonal tract_with_last = self.__find_tract_with_nt(nt_last) if tract_with_last",
"len(coords), sum(ys) / len(coords), sum(zs) / len(coords))) def eltetrado(structure2d: Structure2D, structure3d: Structure3D, strict:",
"= os.path.dirname(os.path.realpath(__file__)) output_pdf = f'{prefix}-{suffix}.pdf' run = subprocess.run([os.path.join(currdir, 'quadraw.R'), fasta.name, helix1.name, helix2.name, output_pdf],",
"(tp.stacked[tp.tetrad1.nt1], tp.stacked[tp.tetrad1.nt2], tp.stacked[tp.tetrad1.nt3], tp.stacked[tp.tetrad1.nt4]) tp.tetrad2.reorder_to_match_5p_3p() # this is required to recalculate ONZ tp.tetrad2.reorder_to_match_other_tetrad(order)",
"+= nt.one_letter_name structure += dotbracket.get(nt, '.') shifts[nt] = shift_value chain = nt.chain return",
"for pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]: # main check if pair.nt1 ==",
"if support != len(self.tetrads): onz = 'M' counter = Counter([tp.direction.value[0] for tp in",
"= i i += 1 for nt in self.structure3d.residues: if nt.chain not in",
"in viable_permutations: score_stacking = [1 if is_next_by_stacking(nts1[i], nts2[i]) else 0 for i in",
"= max([tj for tj in candidates], key=lambda tk: self.tetrad_scores[ti][tk][0]) score += self.tetrad_scores[ti][tj][0] order.append(tj)",
"__detect_loop_sign(self, first: Residue3D, last: Residue3D, tetrad: Tetrad) -> Optional[str]: for pair in [tetrad.pair_12,",
"self.nt1, self.nt2, self.nt3 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34 #",
"= dict() for pair, order in orders.items(): nt1, nt2 = sorted([pair.nt1, pair.nt2]) dotbracket[nt1]",
"return '-' return '+' # reverse check if pair.nt1 == last and pair.nt2",
"= p.nt1.chain c2 = p.nt2.chain if c1 != c2 and c1 in chain_order",
"valid in 5'-3' order self.onz = self.__classify_onz() self.gba_class = self.__classify_by_gba() def reorder_to_match_other_tetrad(self, order:",
"self.__filter_tetrad_pairs(tetrads), self.structure3d)) tetrads = list() tetrads.append(tetrad) quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) return quadruplexes def __filter_tetrad_pairs(self,",
"3) ni, nj, nk, nl = map(lambda nt: nt.index, self.nucleotides) indices = sorted((ni,",
"GbaTetradClassification, Ion, Direction, LoopType, ONZM, GbaQuadruplexClassification, LoopClassification logging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"INFO\")) @dataclass(order=True) class Tetrad: @staticmethod",
"4, ONZ.Z_PLUS: 5, ONZ.Z_MINUS: 6} nucleotides = self.analysis.structure3d.residues shifts = self.analysis.shifts helix =",
"self.tetrad_pairs: nt_dict = { tetrad_pair.tetrad1.nt1: tetrad_pair.tetrad2_nts_best_order[0], tetrad_pair.tetrad1.nt2: tetrad_pair.tetrad2_nts_best_order[1], tetrad_pair.tetrad1.nt3: tetrad_pair.tetrad2_nts_best_order[2], tetrad_pair.tetrad1.nt4: tetrad_pair.tetrad2_nts_best_order[3], }",
"Direction.antiparallel return Direction.hybrid def __calculate_rise(self) -> float: t1 = self.tetrad1.outer_and_inner_atoms() t2 = self.tetrad2.outer_and_inner_atoms()",
"= pair_dictionary[(nt4, nt1)].lw for lw_i, lw_j in ((lw1, lw4), (lw2, lw1), (lw3, lw2),",
"= { tetrad_pair.tetrad1.nt1: tetrad_pair.tetrad2_nts_best_order[0], tetrad_pair.tetrad1.nt2: tetrad_pair.tetrad2_nts_best_order[1], tetrad_pair.tetrad1.nt3: tetrad_pair.tetrad2_nts_best_order[2], tetrad_pair.tetrad1.nt4: tetrad_pair.tetrad2_nts_best_order[3], } for i",
"field(init=False) def __post_init__(self): self.quadruplexes = self.__find_quadruplexes() def __find_quadruplexes(self): if len(self.tetrad_pairs) == 0: return",
"and x in self.graph[i], self.graph[k]): if Tetrad.is_valid(i, j, k, l, self.pair_dict): tetrads.add(frozenset([i, j,",
"\\ f'{self.__ions_channel_str()} ' \\ f'{self.__ions_outside_str()}\\n' def chains(self) -> Set[str]: return set([nt.chain for nt",
"direction = 'h' counter = Counter([t.onz.value[1] for t in self.tetrads]) plus_minus, support =",
"self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34 elif order == (self.nt4, self.nt3, self.nt2, self.nt1):",
"support != len(self.tetrads): onz = 'M' counter = Counter([tp.direction.value[0] for tp in self.tetrad_pairs])",
"= nt.chain return sequence, structure, shifts def __str__(self): builder = f'Chain order: {\"",
"self.gba_classes))}' if self.loop_class: builder += f' {self.loop_class.value} {self.loop_class.loop_progression()}' else: builder += f' n/a'",
"tj.reorder_to_match_other_tetrad(order) return tetrad_pairs def __find_helices(self): helices = [] helix_tetrads = [] helix_tetrad_pairs =",
"Counter([tp.direction.value[0] for tp in self.tetrad_pairs]) direction, support = counter.most_common()[0] if support != len(self.tetrad_pairs):",
"self.nucleotides]): return None # this will create a 4-letter string made of 's'",
"ncur.index - nprev.index > 1 and ncur.chain == nprev.chain: for tract in self.tracts:",
"(best_score, nts1, best_order) tetrad_scores[tj][ti] = (best_score, best_order, nts1) return tetrad_scores def __find_tetrad_pairs(self, stacking_mismatch:",
"return '' @dataclass class TetradPair: tetrad1: Tetrad tetrad2: Tetrad stacked: Dict[Residue3D, Residue3D] tetrad2_nts_best_order:",
"self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif nmin == nk: self.nt1, self.nt2, self.nt3,",
"return sequence, line1, line2, shifts def __elimination_conflicts(self, pairs: List[BasePair3D]) -> Tuple[str, str, Dict[Residue3D,",
"tracts = [[self.tetrads[0].nt1], [self.tetrads[0].nt2], [self.tetrads[0].nt3], [self.tetrads[0].nt4]] if len(self.tetrad_pairs) > 0: for tetrad_pair in",
"return '-' return None def __classify_by_loops(self) -> Optional[LoopClassification]: if len(self.loops) != 3 or",
"is_next_sequentially(nts1[i], nts2[i]) else 0 for i in range(4)] score = sum([max(score_stacking[i], score_sequential[i]) for",
"in self.helices: for t in h.tetrads: candidates.add(frozenset([t.nt1.chain, t.nt2.chain, t.nt3.chain, t.nt4.chain])) candidates = [set(c)",
"if not qi.isdisjoint(qj): qi.update(qj) del candidates[j] changed = True break candidates = sorted(candidates,",
"'dpd' else 1].loop_type.value[-1] == '-' else 'b' return LoopClassification.from_value(f'{loop_classes[fingerprint]}{subtype}') def __str__(self): builder =",
"= None for nt in sorted(filter(lambda nt: nt.is_nucleotide, self.structure3d.residues), key=lambda nt: nt.index): if",
"-> j -> k -> l # ^--------------^ tetrads = [] for i",
"tetrad in tetrads: chains.update(tetrad.chains()) def check_tetrad(t: Tetrad) -> bool: return not t.chains().isdisjoint(chains) def",
"= self.__to_helix(layer2) currdir = os.path.dirname(os.path.realpath(__file__)) output_pdf = f'{prefix}-{suffix}.pdf' run = subprocess.run([os.path.join(currdir, 'quadraw.R'), fasta.name,",
"'II': 2, 'III': 3, 'IV': 4, 'V': 5, 'VI': 6, 'VII': 7, 'VIII':",
"i in range(4)] score_sequential = [1 if is_next_sequentially(nts1[i], nts2[i]) else 0 for i",
"self.nt3, self.nt4 = order def __classify_onz(self) -> ONZ: # transform into (0, 1,",
"f' {\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass class Loop: nucleotides: List[Residue3D] loop_type: Optional[LoopType]",
"between {nt_first} and {nt_last}') return None def __find_tetrad_with_nt(self, nt: Residue3D) -> Optional[Tetrad]: for",
"lw_i.name[1] == lw_j.name[2]: return False return True nt1: Residue3D nt2: Residue3D nt3: Residue3D",
"loop_type = self.__detect_loop_type(nprev, ncur) loops.append(Loop(nts, loop_type)) return loops def __detect_loop_type(self, nt_first: Residue3D, nt_last:",
"tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D onzm: Optional[ONZM] = field(init=False) gba_classes: List[GbaQuadruplexClassification] =",
"self.direction = self.__determine_direction() self.rise = self.__calculate_rise() self.twist = self.__calculate_twist() def __determine_direction(self) -> Direction:",
"0: print('\\nPlot:', output_pdf) else: logging.error(f'Failed to prepare visualization, reason:\\n {run.stderr.decode()}') def __to_helix(self, layer:",
"while tetrads: graph = defaultdict(list) for (ti, tj) in itertools.combinations(tetrads, 2): if not",
"reverse=True) groups = [] for candidate in candidates: if any([group.issuperset(candidate) for group in",
"planarity_deviation: float = field(init=False) ions_channel: List[Atom3D] = field(default_factory=list) ions_outside: Dict[Residue3D, List[Atom3D]] = field(default_factory=dict)",
"'llp': '7', 'lpl': '8', 'pll': '9', 'pdl': '10', 'ldl': '11', 'dpd': '12', 'ldp':",
"tetrad which conflicts the most with others # in case of a tie,",
"range(4)] score_sequential = [1 if is_next_sequentially(nts1[i], nts2[i]) else 0 for i in range(4)]",
"stacked.update({v: k for k, v in stacked.items()}) tetrad_pairs.append(TetradPair(ti, tj, stacked)) order = (stacked[ti.nt1],",
"filter(lambda x: x != i, self.graph[i]): for k in filter(lambda x: x not",
"eltetrado(structure2d: Structure2D, structure3d: Structure3D, strict: bool, no_reorder: bool, stacking_mismatch: int) -> Analysis: return",
"for i in range(4)] score = sum([max(score_stacking[i], score_sequential[i]) for i in range(4)]) score_sequential",
"nj, nk, nl)) nmin = min(ni, nj, nk, nl) if nmin == ni:",
"List[BasePair3D] = structure3d.base_pairs(structure2d) self.graph: Dict[Residue3D, List[Residue3D]] = structure3d.base_pair_graph(structure2d) self.pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] =",
"loops = [] tetrad_nucleotides = sorted([nt for tetrad in self.tetrads for nt in",
"+= f'{loop}\\n' builder += '\\n' return builder @dataclass class Helix: tetrads: List[Tetrad] tetrad_pairs:",
"= self.__generate_twoline_dotbracket() self.ions = self.__find_ions() self.__assign_ions_to_tetrads() def __find_tetrads(self, no_reorder=False) -> List[Tetrad]: # search",
"def __generate_twoline_dotbracket(self) -> Tuple[str, str, str, Dict[Residue3D, int]]: layer1, layer2 = [], []",
"ONZM, GbaQuadruplexClassification, LoopClassification logging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"INFO\")) @dataclass(order=True) class Tetrad: @staticmethod def is_valid(nt1: Residue3D, nt2:",
"for DNA Quadruplex Folding. Chemistry - A European Journal, 13(35), 9738–9745. https://doi.org/10.1002/chem.200701255 :return:",
"field(init=False) tetrad_scores: Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]] = field(init=False) tetrad_pairs: List[TetradPair] = field(init=False)",
"twist={round(self.twist, 2)}\\n' @dataclass class Tract: nucleotides: List[Residue3D] def __str__(self): return f' {\", \".join(map(lambda",
"for nt in self.structure3d.residues: if nt.chain not in chain_order: nt.index = i i",
"if len(final_order) > 1: self.__reorder_chains(final_order) classifications = [t.onz for h in self.helices for",
"- i > 0 else -1 for i, j in zip(indices1, indices2)) direction,",
"nt_first for nt in tract_with_last.nucleotides: if nt in tetrad_with_first.nucleotides: sign = self.__detect_loop_sign(nt_first, nt,",
"for c in candidates] changed = True while changed: changed = False for",
"== (1, 2, 3): return ONZ.O_PLUS elif order == (3, 2, 1): return",
"nts2 if best_score == 4: break tetrad_scores[ti][tj] = (best_score, nts1, best_order) tetrad_scores[tj][ti] =",
"= list() tetrads = list() for tetrad in [self.tetrad_pairs[0].tetrad1] + [tetrad_pair.tetrad2 for tetrad_pair",
"{}, {} ions_channel = defaultdict(list) ions_outside = defaultdict(list) for ion in self.ions: min_distance",
"= self.__classify_onzm() self.gba_classes = self.__classify_by_gba() self.tracts = self.__find_tracts() self.loops = self.__find_loops() self.loop_class =",
"sign = self.__detect_loop_sign(nt_first, nt_last, tetrad_with_first) if sign is not None: return LoopType.from_value(f'lateral{sign}') return",
"nl = nl, ni, nj, nk order = (nj, nk, nl) if order",
"tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) sequence, line1, shifts = self.__elimination_conflicts(layer1) _, line2, _ = self.__elimination_conflicts(layer2)",
"abs(nt1.index - nt2.index) == 1 tetrad_scores = defaultdict(dict) for ti, tj in itertools.combinations(self.tetrads,",
"List[Residue3D]] = structure3d.base_pair_graph(structure2d) self.pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = structure3d.base_pair_dict(structure2d) def has_tetrads(self): tetrads =",
"2, 1): return ONZ.O_MINUS elif order == (1, 3, 2): return ONZ.N_PLUS elif",
"self.__find_helices() def __group_related_chains(self) -> List[List[str]]: candidates = set() for h in self.helices: for",
"nprev.index > 1 and ncur.chain == nprev.chain: for tract in self.tracts: if nprev",
"lw2), (lw4, lw3)): if lw_i.name[1] == lw_j.name[2]: return False return True nt1: Residue3D",
"self.base_pair_dict[(l, i)] tetrads.append(Tetrad(i, j, k, l, pair_12, pair_23, pair_34, pair_41)) # build graph",
"zs = (coord[2] for coord in coords) return numpy.array((sum(xs) / len(coords), sum(ys) /",
"itertools.combinations(self.tetrads, 2): nts1 = ti.nucleotides best_score = 0 best_score_sequential = 0 best_score_stacking =",
"3 or any([loop.loop_type is None for loop in self.loops]): return None loop_classes =",
"> best_score: best_score = score best_order = order if best_score == (len(self.tetrads) -",
"in self.loops: builder += f'{loop}\\n' builder += '\\n' return builder @dataclass class Helix:",
"} if fingerprint not in gba_classes: logging.error(f'Impossible combination of syn/anti: {[nt.chi_class for nt",
"-> List[Atom3D]: return list(map(lambda residue: residue.outermost_atom, self.nucleotides)) + \\ list(map(lambda residue: residue.innermost_atom, self.nucleotides))",
"if nt.chain not in chain_order: nt.index = i i += 1 if len(self.tetrad_pairs)",
"Visualizer: analysis: Analysis tetrads: List[Tetrad] complete2d: bool onz_dict: Dict[BasePair3D, ONZ] = field(init=False) def",
"= self.__to_helix(layer1, self.analysis.canonical() if self.complete2d else []) helix2 = self.__to_helix(layer2) currdir = os.path.dirname(os.path.realpath(__file__))",
"[1 if is_next_sequentially(nts1[i], nts2[i]) else 0 for i in range(4)] score = sum([max(score_stacking[i],",
"hash(frozenset([self.nt1, self.nt2, self.nt3, self.nt4])) def __str__(self): return f' ' \\ f'{self.nt1.full_name} {self.nt2.full_name} {self.nt3.full_name}",
"return ONZ.N_PLUS elif order == (2, 3, 1): return ONZ.N_MINUS elif order ==",
"gba.value, self.gba_classes))}' if self.loop_class: builder += f' {self.loop_class.value} {self.loop_class.loop_progression()}' else: builder += f'",
"= [] for residue, ions in self.ions_outside.items(): result.append(f'{residue.full_name}: [{\",\".join([ion.atomName for ion in ions])}]')",
"self.loops]): return None loop_classes = { 'ppp': '1', 'ppl': '2', 'plp': '3', 'lpp':",
"def __ions_outside_str(self) -> str: if self.ions_outside: result = [] for residue, ions in",
"count directions 5' -> 3' as +1 or -1 counter = Counter(1 if",
"nl)) while ni != 0: ni, nj, nk, nl = nl, ni, nj,",
"__classify_by_gba(self) -> Optional[GbaTetradClassification]: \"\"\" See: <NAME>. (2007). Geometric Formalism for DNA Quadruplex Folding.",
"= 'M' counter = Counter([tp.direction.value[0] for tp in self.tetrad_pairs]) direction, support = counter.most_common()[0]",
"changed = True while changed: changed = False for i, j in itertools.combinations(range(len(candidates)),",
"not in used: ions.append(atom) used.add(coordinates) return ions def __assign_ions_to_tetrads(self) \\ -> Tuple[Dict[Tetrad, List[Atom3D]],",
"layer2.extend([tetrad.pair_23, tetrad.pair_41]) helix1 = self.__to_helix(layer1, self.analysis.canonical() if self.complete2d else []) helix2 = self.__to_helix(layer2)",
"= order def __classify_onz(self) -> ONZ: # transform into (0, 1, 2, 3)",
"Residue3D) -> Optional[LoopType]: tetrad_with_first = self.__find_tetrad_with_nt(nt_first) tetrad_with_last = self.__find_tetrad_with_nt(nt_last) if tetrad_with_first is None",
"queue = list(pairs) removed = [] while queue: conflicts = defaultdict(list) for pi,",
"nk order = (nj, nk, nl) if order == (1, 2, 3): return",
"tract.nucleotides and ncur in tract.nucleotides: break else: nts = list(filter(lambda nt: nprev.index <",
"in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]: # main check if pair.nt1 == first and",
"\\ f'{self.nt1.full_name} {self.nt2.full_name} {self.nt3.full_name} {self.nt4.full_name} ' \\ f'{self.pair_12.lw.value} {self.pair_23.lw.value} {self.pair_34.lw.value} {self.pair_41.lw.value} ' \\",
"all classes mapped to fingerprints gba_classes = { 'aass': GbaTetradClassification.Ia, 'ssaa': GbaTetradClassification.Ib, 'asas':",
"an ion and tetrad channel if min_distance < 6.0: ions_channel[min_tetrad].append(ion) continue min_distance =",
"best_order[i] score = self.tetrad_scores[ti][tj][0] if score >= (4 - stacking_mismatch): nts1, nts2 =",
"n2, n1), (n3, n2, n1, n4), (n2, n1, n4, n3)] for nts2 in",
"'\\n Loops:\\n' for loop in self.loops: builder += f'{loop}\\n' builder += '\\n' return",
"an ion and an atom if min_distance < 3.0: ions_outside[(min_tetrad, min_nt)].append(ion) continue logging.debug(f'Skipping",
"def __assign_ions_to_tetrads(self) \\ -> Tuple[Dict[Tetrad, List[Atom3D]], Dict[Tuple[Tetrad, Residue3D], List[Atom3D]]]: if len(self.tetrads) == 0:",
"3): return ONZ.O_PLUS elif order == (3, 2, 1): return ONZ.O_MINUS elif order",
"ONZ.N_MINUS elif order == (2, 1, 3): return ONZ.Z_PLUS elif order == (3,",
"self.tetrads]) onz, support = counter.most_common()[0] if support != len(self.tetrads): onz = 'M' counter",
"canonical: x, y = pair.nt1, pair.nt2 x, y = nucleotides.index(x) + 1 +",
"List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D onzm: Optional[ONZM] = field(init=False) gba_classes: List[GbaQuadruplexClassification] = field(init=False)",
"set() for i in self.graph: for j in filter(lambda x: x != i,",
"candidates], key=lambda tk: self.tetrad_scores[ti][tk][0]) score += self.tetrad_scores[ti][tj][0] order.append(tj) candidates.remove(tj) ti = tj if",
"sorted([nt for tetrad in self.tetrads for nt in tetrad.nucleotides], key=lambda nt: nt.index) for",
"best_score = 0 best_order = tetrads for ti in tetrads: score = 0",
"ti, tj = best_order[i - 1], best_order[i] score = self.tetrad_scores[ti][tj][0] if score >=",
"reorder_to_match_other_tetrad(self, order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D]): if order == (self.nt1, self.nt2, self.nt3, self.nt4):",
"self.planarity_deviation = self.__calculate_planarity_deviation() def reorder_to_match_5p_3p(self): # transform into (0, 1, 2, 3) ni,",
"k) and i in self.base_pair_graph[x], self.base_pair_graph[k]): if Tetrad.is_valid(i, j, k, l, self.base_pair_dict): pair_12",
"pair_23, pair_34, pair_41)) # build graph of tetrads while tetrads: graph = defaultdict(list)",
"nt_last: Residue3D) -> Optional[LoopType]: tetrad_with_first = self.__find_tetrad_with_nt(nt_first) tetrad_with_last = self.__find_tetrad_with_nt(nt_last) if tetrad_with_first is",
"field(init=False) base_pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = field(init=False) stacking_graph: Dict[Residue3D, List[Residue3D]] = field(init=False) tetrads:",
"self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() if not self.no_reorder: self.__find_best_chain_order() self.sequence, self.line1, self.line2,",
"self.nt2, self.nt3, self.nt4): pass elif order == (self.nt2, self.nt3, self.nt4, self.nt1): self.pair_12, self.pair_23,",
"__find_tetrad_with_nt(self, nt: Residue3D) -> Optional[Tetrad]: for tetrad in self.tetrads: if nt in tetrad.nucleotides:",
"n3, n4, n1), (n3, n4, n1, n2), (n4, n1, n2, n3), (n1, n4,",
"self.helices: for t in h.tetrads: for p in [t.pair_12, t.pair_23, t.pair_34, t.pair_41]: c1",
"import tempfile from collections import defaultdict, Counter from dataclasses import dataclass, field from",
"ions_channel.items(): tetrad.ions_channel = ions for pair, ions in ions_outside.items(): tetrad, residue = pair",
"str(helix) builder += f'{self.sequence}\\n{self.line1}\\n{self.line2}' return builder def __chain_order(self) -> List[str]: only_nucleic_acids = filter(lambda",
"to Webba da Silva or n/a \"\"\" # without all nucleotides having a",
"3, 'IV': 4, 'V': 5, 'VI': 6, 'VII': 7, 'VIII': 8} gbas =",
"min_distance: min_distance = distance min_tetrad = tetrad # TODO: verify threshold of 6A",
"= [t.onz for h in self.helices for t in h.tetrads] logging.debug(f'Selected chain order:",
"for syn or 'a' for anti fingerprint = ''.join([nt.chi_class.value[0] for nt in self.nucleotides])",
"-> str: if self.ions_outside: result = [] for residue, ions in self.ions_outside.items(): result.append(f'{residue.full_name}:",
"atom in atoms] xs = (coord[0] for coord in coords) ys = (coord[1]",
"field(init=False) def __post_init__(self): self.onz_dict = {pair: tetrad.onz for tetrad in self.tetrads for pair",
"if (score, score_sequential, score_stacking) > (best_score, best_score_sequential, best_score_stacking): best_score, best_score_sequential, best_score_stacking = score,",
"1, 2, 3) ni, nj, nk, nl = (nt.index for nt in self.nucleotides)",
"logging.error(f'Impossible combination of syn/anti: {[nt.chi_class for nt in self.nucleotides]}') return None return gba_classes[fingerprint]",
"along the tract to check what pairs with nt_first for nt in tract_with_last.nucleotides:",
"self.nt4, self.nt1, self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23 else:",
"(self.nt3, self.nt4, self.nt1, self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23",
"first and pair.nt2 == last: if pair.score() < pair.reverse().score(): return '-' return '+'",
"(self.nt1, self.nt2, self.nt3, self.nt4): pass elif order == (self.nt2, self.nt3, self.nt4, self.nt1): self.pair_12,",
"best_permutation = permutation elif score == best_score: # in case of a tie,",
"return Direction.hybrid def __calculate_rise(self) -> float: t1 = self.tetrad1.outer_and_inner_atoms() t2 = self.tetrad2.outer_and_inner_atoms() return",
"(n2, n3, n4, n1), (n3, n4, n1, n2), (n4, n1, n2, n3), (n1,",
"= {nts1[i]: nts2[i] for i in range(4)} stacked.update({v: k for k, v in",
"pass elif nmin == nj: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt2, self.nt3, self.nt4,",
"!= len(self.tetrads): plus_minus = '*' return ONZM.from_value(f'{onz}{direction}{plus_minus}') def __classify_by_gba(self) -> List[GbaQuadruplexClassification]: gbas =",
"= map(lambda nt: nt.index, self.nucleotides) indices = sorted((ni, nj, nk, nl)) ni, nj,",
"self.ions_outside: result = [] for residue, ions in self.ions_outside.items(): result.append(f'{residue.full_name}: [{\",\".join([ion.atomName for ion",
"f'{\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass class Quadruplex: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d:",
"of 3A between an ion and an atom if min_distance < 3.0: ions_outside[(min_tetrad,",
"nt_dict = { tetrad_pair.tetrad1.nt1: tetrad_pair.tetrad2_nts_best_order[0], tetrad_pair.tetrad1.nt2: tetrad_pair.tetrad2_nts_best_order[1], tetrad_pair.tetrad1.nt3: tetrad_pair.tetrad2_nts_best_order[2], tetrad_pair.tetrad1.nt4: tetrad_pair.tetrad2_nts_best_order[3], } for",
"{nts1[i]: nts2[i] for i in range(4)} stacked.update({v: k for k, v in stacked.items()})",
"nt in sorted(only_nucleic_acids, key=lambda nt: nt.index)}.keys()) def canonical(self) -> List[BasePair3D]: return [base_pair for",
"def canonical(self) -> List[BasePair3D]: return [base_pair for base_pair in self.base_pairs if base_pair.is_canonical()] @dataclass",
"= self.tetrad1.outer_and_inner_atoms() t2 = self.tetrad2.outer_and_inner_atoms() return numpy.linalg.norm(center_of_mass(t1) - center_of_mass(t2)) def __calculate_twist(self) -> float:",
"{ONZ.O_PLUS: 1, ONZ.O_MINUS: 2, ONZ.N_PLUS: 3, ONZ.N_MINUS: 4, ONZ.Z_PLUS: 5, ONZ.Z_MINUS: 6} nucleotides",
"= permutation final_order.extend(best_permutation) if len(final_order) > 1: self.__reorder_chains(final_order) classifications = [t.onz for h",
"nj, nk, nl = map(lambda nt: nt.index, self.nucleotides) indices = sorted((ni, nj, nk,",
"self.pair_34 # flip order if necessary if self.pair_12.score() > self.pair_41.reverse().score(): self.nt1, self.nt2, self.nt3,",
"dict() shift_value = 0 chain = None for nt in sorted(filter(lambda nt: nt.is_nucleotide,",
"lw1 = pair_dictionary[(nt1, nt2)].lw lw2 = pair_dictionary[(nt2, nt3)].lw lw3 = pair_dictionary[(nt3, nt4)].lw lw4",
"j in filter(lambda x: x != i, self.base_pair_graph[i]): for k in filter(lambda x:",
"[self.tetrad_pairs[0].tetrad1] + [tetrad_pair.tetrad2 for tetrad_pair in self.tetrad_pairs]: if tetrads: if tetrad.chains().isdisjoint(tetrads[-1].chains()): quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads),",
"0: ni, nj, nk, nl = nl, ni, nj, nk order = (nj,",
"2)}\\n' @dataclass class Tract: nucleotides: List[Residue3D] def __str__(self): return f' {\", \".join(map(lambda nt:",
"== 1: return [] loops = [] tetrad_nucleotides = sorted([nt for tetrad in",
"None def __find_tract_with_nt(self, nt: Residue3D) -> Optional[Tract]: for tract in self.tracts: if nt",
"structure, shifts def __str__(self): builder = f'Chain order: {\" \".join(self.__chain_order())}\\n' for helix in",
"min_nt)].append(ion) continue logging.debug(f'Skipping an ion, because it is too far from any tetrad",
"# remove tetrad which conflicts the most with others # in case of",
"False def center_of_mass(atoms): coords = [atom.coordinates() for atom in atoms] xs = (coord[0]",
"sorted(gbas, key=lambda gba: roman_numerals.get(gba, 100)) return list(map(lambda x: GbaQuadruplexClassification[x], gbas)) def __find_tracts(self) ->",
"pair_12: BasePair3D pair_23: BasePair3D pair_34: BasePair3D pair_41: BasePair3D onz: ONZ = field(init=False) gba_class:",
"self.__classify_by_gba() def reorder_to_match_other_tetrad(self, order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D]): if order == (self.nt1, self.nt2,",
"int: chain_pairs = [] for h in self.helices: for t in h.tetrads: for",
"pair.nt2 == last: if pair.score() < pair.reverse().score(): return '-' return '+' # reverse",
"t.chains().isdisjoint(chains) def check_pair(tp: TetradPair) -> bool: return check_tetrad(tp.tetrad1) and check_tetrad(tp.tetrad2) return list(filter(check_pair, self.tetrad_pairs))",
"if any([t.onz is None for t in self.tetrads]): return None counter = Counter([t.onz.value[0]",
"self.nt2, self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse() elif order",
"list(map(lambda residue: residue.outermost_atom, self.nucleotides)) + \\ list(map(lambda residue: residue.innermost_atom, self.nucleotides)) def __ions_channel_str(self) ->",
"self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() else: raise RuntimeError(f'Cannot apply order:",
"= field(init=False) base_pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = field(init=False) stacking_graph: Dict[Residue3D, List[Residue3D]] = field(init=False)",
"List[BasePair3D]) -> Tuple[str, str, Dict[Residue3D, int]]: orders = dict() order = 0 queue",
"2): if not ti.is_disjoint(tj): graph[ti].append(tj) graph[tj].append(ti) # remove tetrad which conflicts the most",
"gba: gba.value, self.gba_classes))}' if self.loop_class: builder += f' {self.loop_class.value} {self.loop_class.loop_progression()}' else: builder +=",
"def eltetrado(structure2d: Structure2D, structure3d: Structure3D, strict: bool, no_reorder: bool, stacking_mismatch: int) -> Analysis:",
"not None: return LoopType.from_value(f'propeller{sign}') logging.warning(f'Failed to classify the loop between {nt_first} and {nt_last}')",
"= self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse() elif order == (self.nt2, self.nt1, self.nt4, self.nt3): self.pair_12,",
"1: self.__reorder_chains(final_order) classifications = [t.onz for h in self.helices for t in h.tetrads]",
"'ppl': '2', 'plp': '3', 'lpp': '4', 'pdp': '5', 'lll': '6', 'llp': '7', 'lpl':",
"for t in self.tetrads]) plus_minus, support = counter.most_common()[0] if support != len(self.tetrads): plus_minus",
"this will create a 4-letter string made of 's' for syn or 'a'",
"are valid in 5'-3' order self.onz = self.__classify_onz() self.gba_class = self.__classify_by_gba() def reorder_to_match_other_tetrad(self,",
"= (tp.stacked[tp.tetrad1.nt1], tp.stacked[tp.tetrad1.nt2], tp.stacked[tp.tetrad1.nt3], tp.stacked[tp.tetrad1.nt4]) tp.tetrad2.reorder_to_match_5p_3p() # this is required to recalculate ONZ",
"in self.base_pairs if base_pair.is_canonical()] @dataclass class Visualizer: analysis: Analysis tetrads: List[Tetrad] complete2d: bool",
"self.nt1, self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23 elif order",
"candidates = sorted(candidates, key=lambda x: len(x), reverse=True) groups = [] for candidate in",
"f'{self.onz.value} {self.gba_class.value} ' \\ f'planarity={round(self.planarity_deviation, 2)} ' \\ f'{self.__ions_channel_str()} ' \\ f'{self.__ions_outside_str()}\\n' def",
"nts2[i] for i in range(4)} stacked.update({v: k for k, v in stacked.items()}) tetrad_pairs.append(TetradPair(ti,",
"Structure2D structure3d: Structure3D strict: bool no_reorder: bool stacking_mismatch: int base_pairs: List[BasePair3D] = field(init=False)",
"self.ions_outside.items(): result.append(f'{residue.full_name}: [{\",\".join([ion.atomName for ion in ions])}]') return 'ions_outside=' + ' '.join(result) return",
"self.__find_tetrads(True) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() def __group_related_chains(self) ->",
"builder += f' {self.onzm.value if self.onzm is not None else \"R\"}' builder +=",
"+= '-' structure += '-' shift_value += 1 sequence += nt.one_letter_name structure +=",
"line1: str = field(init=False) line2: str = field(init=False) shifts: Dict[Residue3D, int] = field(init=False)",
"elif len(self.tetrads) == 1: builder += 'single tetrad without stacking\\n' builder += str(self.tetrads[0])",
"for tetrad in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) sequence, line1, shifts = self.__elimination_conflicts(layer1)",
"not ti.is_disjoint(tj): graph[ti].append(tj) graph[tj].append(ti) # remove tetrad which conflicts the most with others",
"for i in range(1, len(tetrad_nucleotides)): nprev = tetrad_nucleotides[i - 1] ncur = tetrad_nucleotides[i]",
"self.graph[k]): if Tetrad.is_valid(i, j, k, l, self.pair_dict): tetrads.add(frozenset([i, j, k, l])) if len(tetrads)",
"= opening[order] dotbracket[nt2] = closing[order] sequence = '' structure = '' shifts =",
"< ncur.index, self.structure3d.residues)) loop_type = self.__detect_loop_type(nprev, ncur) loops.append(Loop(nts, loop_type)) return loops def __detect_loop_type(self,",
"support = counter.most_common()[0] if support != len(self.tetrads): plus_minus = '*' return ONZM.from_value(f'{onz}{direction}{plus_minus}') def",
"order: {order}') self.nt1, self.nt2, self.nt3, self.nt4 = order def __classify_onz(self) -> ONZ: #",
"4, 'V': 5, 'VI': 6, 'VII': 7, 'VIII': 8} gbas = sorted(gbas, key=lambda",
"for tract in self.tracts: if nt in tract.nucleotides: return tract return None def",
"-> l # ^--------------^ tetrads = [] for i in self.base_pair_graph: for j",
"0 chain = None for nt in sorted(filter(lambda nt: nt.is_nucleotide, self.structure3d.residues), key=lambda nt:",
"layer: List[BasePair3D], canonical: Optional[List[BasePair3D]] = None) -> tempfile.NamedTemporaryFile(): onz_value = {ONZ.O_PLUS: 1, ONZ.O_MINUS:",
"Analysis: return Analysis(structure2d, structure3d, strict, no_reorder, stacking_mismatch) def has_tetrad(structure2d: Structure2D, structure3d: Structure3D) ->",
"score = 0 order = [ti] candidates = set(self.tetrads) - {ti} while candidates:",
"[set(c) for c in candidates] changed = True while changed: changed = False",
"1].loop_type.value[-1] == '-' else 'b' return LoopClassification.from_value(f'{loop_classes[fingerprint]}{subtype}') def __str__(self): builder = '' if",
"== 4: break tetrad_scores[ti][tj] = (best_score, nts1, best_order) tetrad_scores[tj][ti] = (best_score, best_order, nts1)",
"self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse() elif order ==",
"i in range(1, len(best_order)): ti, tj = best_order[i - 1], best_order[i] score =",
"helix_tetrads.append(ti) score = self.tetrad_scores[helix_tetrads[-1]][tj][0] if score >= (4 - self.stacking_mismatch): helix_tetrads.append(tj) helix_tetrad_pairs.append(tp) else:",
"helices]): helices.append(Helix([tetrad], [], self.structure3d)) return helices def __find_best_chain_order(self): chain_groups = self.__group_related_chains() final_order =",
"support != len(self.tetrad_pairs): direction = 'h' counter = Counter([t.onz.value[1] for t in self.tetrads])",
"self.reorder_to_match_5p_3p() self.planarity_deviation = self.__calculate_planarity_deviation() def reorder_to_match_5p_3p(self): # transform into (0, 1, 2, 3)",
"None return gba_classes[fingerprint] def __calculate_planarity_deviation(self) -> float: outer = [nt.outermost_atom for nt in",
"j in filter(lambda x: x != i, self.graph[i]): for k in filter(lambda x:",
"self.ions_channel: return 'ions_channel=' + ','.join([atom.atomName for atom in self.ions_channel]) return '' def __ions_outside_str(self)",
"== (2, 1, 3): return ONZ.Z_PLUS elif order == (3, 1, 2): return",
"tetrad in self.tetrads for nt in tetrad.nucleotides], key=lambda nt: nt.index) for i in",
"in [t.pair_12, t.pair_23, t.pair_34, t.pair_41]: c1 = p.nt1.chain c2 = p.nt2.chain if c1",
"= list(pairs) removed = [] while queue: conflicts = defaultdict(list) for pi, pj",
"necessary if self.pair_12.score() > self.pair_41.reverse().score(): self.nt1, self.nt2, self.nt3, self.nt4 = self.nt1, self.nt4, self.nt3,",
"classification is impossible if not all([nt.chi_class in (GlycosidicBond.syn, GlycosidicBond.anti) for nt in self.nucleotides]):",
"List[Atom3D]: return list(map(lambda residue: residue.outermost_atom, self.nucleotides)) + \\ list(map(lambda residue: residue.innermost_atom, self.nucleotides)) def",
"nts1, nts2 = self.tetrad_scores[ti][tj][1:] stacked = {nts1[i]: nts2[i] for i in range(4)} stacked.update({v:",
"if not ti.is_disjoint(tj): graph[ti].append(tj) graph[tj].append(ti) # remove tetrad which conflicts the most with",
"Tuple[int, Tuple, Tuple]]]: def is_next_by_stacking(nt1: Residue3D, nt2: Residue3D) -> bool: return nt2 in",
"LoopClassification logging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"INFO\")) @dataclass(order=True) class Tetrad: @staticmethod def is_valid(nt1: Residue3D, nt2: Residue3D, nt3:",
"(2, 3, 1): return ONZ.N_MINUS elif order == (2, 1, 3): return ONZ.Z_PLUS",
"f'Checking reorder: {\" \".join(permutation)} {\" \".join(map(lambda c: c.value, classifications))}') onz_score = sum(c.score() for",
"shifts = self.analysis.shifts helix = tempfile.NamedTemporaryFile('w+', suffix='.helix') helix.write(f'#{len(self.analysis.sequence) + 1}\\n') helix.write('i\\tj\\tlength\\tvalue\\n') for pair",
"' \\ f'{\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass class Quadruplex: tetrads: List[Tetrad] tetrad_pairs:",
"best_order, nts1) return tetrad_scores def __find_tetrad_pairs(self, stacking_mismatch: int) -> List[TetradPair]: tetrads = list(self.tetrads)",
"candidates] changed = True while changed: changed = False for i, j in",
"False for i, j in itertools.combinations(range(len(candidates)), 2): qi, qj = candidates[i], candidates[j] if",
"= min_tetrad.nt1 for tetrad in self.tetrads: for nt in tetrad.nucleotides: for atom in",
"ONZ, \\ GbaTetradClassification, Ion, Direction, LoopType, ONZM, GbaQuadruplexClassification, LoopClassification logging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"INFO\")) @dataclass(order=True) class",
"this classification is impossible if not all([nt.chi_class in (GlycosidicBond.syn, GlycosidicBond.anti) for nt in",
"in (ni, nj, nk, nl)) nmin = min(ni, nj, nk, nl) if nmin",
"Optional[LoopType] def __str__(self): return f' {self.loop_type.value if self.loop_type else \"n/a\"} ' \\ f'{\",",
"self.pair_12, self.pair_23, self.pair_34 elif order == (self.nt4, self.nt3, self.nt2, self.nt1): self.pair_12, self.pair_23, self.pair_34,",
"+= f' quadruplex with {len(self.tetrads)} tetrads\\n' builder += str(self.tetrad_pairs[0].tetrad1) for tetrad_pair in self.tetrad_pairs:",
"if support != len(self.tetrads): plus_minus = '*' return ONZM.from_value(f'{onz}{direction}{plus_minus}') def __classify_by_gba(self) -> List[GbaQuadruplexClassification]:",
"any([loop.loop_type is None for loop in self.loops]): return None loop_classes = { 'ppp':",
"in tetrad.nucleotides: for atom in nt.atoms: distance = numpy.linalg.norm(ion.coordinates() - atom.coordinates()) if distance",
"according to Webba da Silva or n/a \"\"\" # without all nucleotides having",
"self.loops[0 if fingerprint != 'dpd' else 1].loop_type.value[-1] == '-' else 'b' return LoopClassification.from_value(f'{loop_classes[fingerprint]}{subtype}')",
"(score, score_sequential, score_stacking) > (best_score, best_score_sequential, best_score_stacking): best_score, best_score_sequential, best_score_stacking = score, score_sequential,",
"= [] for tp in self.tetrad_pairs: ti, tj = tp.tetrad1, tp.tetrad2 if not",
"return sum_sq def __find_ions(self) -> List[Atom3D]: metal_atom_names = set([ion.value.upper() for ion in Ion])",
"nt1)].lw for lw_i, lw_j in ((lw1, lw4), (lw2, lw1), (lw3, lw2), (lw4, lw3)):",
"stacking_mismatch) def has_tetrad(structure2d: Structure2D, structure3d: Structure3D) -> bool: structure = AnalysisSimple(structure2d, structure3d) return",
"= order if best_score == (len(self.tetrads) - 1) * 4: break tetrad_pairs =",
"self.pair_23, self.pair_34 # flip order if necessary if self.pair_12.score() > self.pair_41.reverse().score(): self.nt1, self.nt2,",
"helix.write('i\\tj\\tlength\\tvalue\\n') for pair in layer: x, y = pair.nt1, pair.nt2 x, y =",
"lw_j in ((lw1, lw4), (lw2, lw1), (lw3, lw2), (lw4, lw3)): if lw_i.name[1] ==",
"return builder @dataclass class Analysis: structure2d: Structure2D structure3d: Structure3D strict: bool no_reorder: bool",
"+= str(tetrad_pair) builder += str(tetrad_pair.tetrad2) if self.tracts: builder += '\\n Tracts:\\n' for tract",
"def __classify_onzm(self) -> Optional[ONZM]: if len(self.tetrads) == 1: return None if any([t.onz is",
"min_distance = math.inf min_tetrad = self.tetrads[0] min_nt = min_tetrad.nt1 for tetrad in self.tetrads:",
"structure = '' shifts = dict() shift_value = 0 chain = None for",
"@dataclass class Helix: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D quadruplexes: List[Quadruplex] = field(init=False)",
"return [base_pair for base_pair in self.base_pairs if base_pair.is_canonical()] @dataclass class Visualizer: analysis: Analysis",
"tetrad channel if min_distance < 6.0: ions_channel[min_tetrad].append(ion) continue min_distance = math.inf min_tetrad =",
"indices2)) direction, count = counter.most_common()[0] if count == 4: # all in the",
"self.base_pairs = self.structure3d.base_pairs(self.structure2d) self.base_pair_graph = self.structure3d.base_pair_graph(self.structure2d, self.strict) self.base_pair_dict = self.structure3d.base_pair_dict(self.structure2d, self.strict) self.stacking_graph =",
"tracts] def __find_loops(self) -> List[Loop]: if len(self.tetrads) == 1: return [] loops =",
"self.pair_34, self.pair_41, self.pair_12, self.pair_23 elif order == (self.nt4, self.nt1, self.nt2, self.nt3): self.pair_12, self.pair_23,",
"nt2: Residue3D) -> bool: return nt2 in self.stacking_graph.get(nt1, []) def is_next_sequentially(nt1: Residue3D, nt2:",
"n2), (n4, n3, n2, n1), (n3, n2, n1, n4), (n2, n1, n4, n3)]",
"== (self.nt1, self.nt4, self.nt3, self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(),",
"Structure3D strict: bool no_reorder: bool stacking_mismatch: int base_pairs: List[BasePair3D] = field(init=False) base_pair_graph: Dict[Residue3D,",
"nt1_2, _, _ = self.tetrad1.nucleotides nt2_1, nt2_2, _, _ = self.tetrad2_nts_best_order v1 =",
"sum(score_sequential) score_stacking = sum(score_stacking) if (score, score_sequential, score_stacking) > (best_score, best_score_sequential, best_score_stacking): best_score,",
"for i in range(4)} stacked.update({v: k for k, v in stacked.items()}) tetrad_pairs.append(TetradPair(ti, tj,",
"[], [] for tetrad in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) sequence, line1, shifts",
"shifts[y] helix.write(f'{x}\\t{y}\\t1\\t8\\n') helix.flush() return helix class AnalysisSimple: def __init__(self, structure2d: Structure2D, structure3d: Structure3D):",
"in tetrads: chains.update(tetrad.chains()) def check_tetrad(t: Tetrad) -> bool: return not t.chains().isdisjoint(chains) def check_pair(tp:",
"not in (i, j), self.graph[j]): for l in filter(lambda x: x not in",
"List[Atom3D]] = field(default_factory=dict) def __post_init__(self): self.reorder_to_match_5p_3p() self.planarity_deviation = self.__calculate_planarity_deviation() def reorder_to_match_5p_3p(self): # transform",
"in range(4)] score_sequential = [1 if is_next_sequentially(nts1[i], nts2[i]) else 0 for i in",
"(self.nt2, self.nt1, self.nt4, self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse()",
"GbaTetradClassification.VIIb, 'aaaa': GbaTetradClassification.VIIIa, 'ssss': GbaTetradClassification.VIIIb } if fingerprint not in gba_classes: logging.error(f'Impossible combination",
"} for i in range(4): tracts[i].append(nt_dict[tracts[i][-1]]) return [Tract(nts) for nts in tracts] def",
"in helix.tetrads for helix in helices]): helices.append(Helix([tetrad], [], self.structure3d)) return helices def __find_best_chain_order(self):",
"for h in self.helices: for t in h.tetrads: candidates.add(frozenset([t.nt1.chain, t.nt2.chain, t.nt3.chain, t.nt4.chain])) candidates",
"required to recalculate ONZ tp.tetrad2.reorder_to_match_other_tetrad(order) def __chain_order_score(self, chain_order: Tuple[str, ...]) -> int: chain_pairs",
"key=lambda nt: nt.index): if chain and chain != nt.chain: sequence += '-' structure",
"shifts[x], nucleotides.index(y) + 1 + shifts[y] onz = self.onz_dict[pair] helix.write(f'{x}\\t{y}\\t1\\t{onz_value.get(onz, 7)}\\n') if canonical:",
"Set import numpy from eltetrado.model import Atom3D, Structure3D, Structure2D, BasePair3D, Residue3D, GlycosidicBond, ONZ,",
"ni: pass elif nmin == nj: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt2, self.nt3,",
"- stacking_mismatch): nts1, nts2 = self.tetrad_scores[ti][tj][1:] stacked = {nts1[i]: nts2[i] for i in",
"(self.nt3, self.nt2, self.nt1, self.nt4): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse()",
"and c1 in chain_order and c2 in chain_order: chain_pairs.append([c1, c2]) sum_sq = 0",
"== 0: print('\\nPlot:', output_pdf) else: logging.error(f'Failed to prepare visualization, reason:\\n {run.stderr.decode()}') def __to_helix(self,",
"nt4)].lw lw4 = pair_dictionary[(nt4, nt1)].lw for lw_i, lw_j in ((lw1, lw4), (lw2, lw1),",
"tetrads = set() for i in self.graph: for j in filter(lambda x: x",
"5' -> 3' as +1 or -1 counter = Counter(1 if j -",
"def __find_tracts(self) -> List[Tract]: tracts = [[self.tetrads[0].nt1], [self.tetrads[0].nt2], [self.tetrads[0].nt3], [self.tetrads[0].nt4]] if len(self.tetrad_pairs) >",
"Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]]: def is_next_by_stacking(nt1: Residue3D, nt2: Residue3D) -> bool: return",
"if self.ions_outside: result = [] for residue, ions in self.ions_outside.items(): result.append(f'{residue.full_name}: [{\",\".join([ion.atomName for",
"permutation < best_permutation: best_permutation = permutation final_order.extend(best_permutation) if len(final_order) > 1: self.__reorder_chains(final_order) classifications",
"self.__elimination_conflicts(layer1) _, line2, _ = self.__elimination_conflicts(layer2) return sequence, line1, line2, shifts def __elimination_conflicts(self,",
"i, self.graph[i]): for k in filter(lambda x: x not in (i, j), self.graph[j]):",
"Folding. Chemistry - A European Journal, 13(35), 9738–9745. https://doi.org/10.1002/chem.200701255 :return: Classification according to",
"if helix_tetrads: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) for tetrad in self.tetrads: if not any([tetrad in",
"for pair, order in orders.items(): nt1, nt2 = sorted([pair.nt1, pair.nt2]) dotbracket[nt1] = opening[order]",
"= shift_value chain = nt.chain return sequence, structure, shifts def __str__(self): builder =",
"self.loops: builder += f'{loop}\\n' builder += '\\n' return builder @dataclass class Helix: tetrads:",
"tetrad_pairs def __find_helices(self): helices = [] helix_tetrads = [] helix_tetrad_pairs = [] for",
"else: logging.error(f'Failed to prepare visualization, reason:\\n {run.stderr.decode()}') def __to_helix(self, layer: List[BasePair3D], canonical: Optional[List[BasePair3D]]",
"# reverse check if pair.nt1 == last and pair.nt2 == first: if pair.score()",
"for tetrad in tetrads: chains.update(tetrad.chains()) def check_tetrad(t: Tetrad) -> bool: return not t.chains().isdisjoint(chains)",
"if score >= (4 - stacking_mismatch): nts1, nts2 = self.tetrad_scores[ti][tj][1:] stacked = {nts1[i]:",
"if base_pair.is_canonical()] @dataclass class Visualizer: analysis: Analysis tetrads: List[Tetrad] complete2d: bool onz_dict: Dict[BasePair3D,",
"tetrads: if tetrad.chains().isdisjoint(tetrads[-1].chains()): quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) tetrads = list() tetrads.append(tetrad) quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d))",
"order = [ti] candidates = set(self.tetrads) - {ti} while candidates: tj = max([tj",
"self.pair_41.reverse() elif order == (self.nt3, self.nt2, self.nt1, self.nt4): self.pair_12, self.pair_23, self.pair_34, self.pair_41 =",
"- nt2_2.find_atom(\"C1'\").coordinates() v2 = v2 / numpy.linalg.norm(v2) return math.degrees(numpy.arccos(numpy.clip(numpy.dot(v1, v2), -1.0, 1.0))) def",
"{self.nt2.full_name} {self.nt3.full_name} {self.nt4.full_name} ' \\ f'{self.pair_12.lw.value} {self.pair_23.lw.value} {self.pair_34.lw.value} {self.pair_41.lw.value} ' \\ f'{self.onz.value} {self.gba_class.value}",
"if any([group.issuperset(candidate) for group in groups]): continue groups.append(candidate) return sorted([sorted(group) for group in",
"nt in tetrad.nucleotides], key=lambda nt: nt.index) for i in range(1, len(tetrad_nucleotides)): nprev =",
"+ ','.join([atom.atomName for atom in self.ions_channel]) return '' def __ions_outside_str(self) -> str: if",
"classifications))}') self.tetrads = self.__find_tetrads(True) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices()",
"nt in tract.nucleotides: return tract return None def __detect_loop_sign(self, first: Residue3D, last: Residue3D,",
"def __calculate_planarity_deviation(self) -> float: outer = [nt.outermost_atom for nt in self.nucleotides] inner =",
"Dict[Tetrad, Tuple[int, Tuple, Tuple]]]: def is_next_by_stacking(nt1: Residue3D, nt2: Residue3D) -> bool: return nt2",
"GlycosidicBond.anti) for nt in self.nucleotides]): return None # this will create a 4-letter",
"k for k, v in stacked.items()}) tetrad_pairs.append(TetradPair(ti, tj, stacked)) order = (stacked[ti.nt1], stacked[ti.nt2],",
"# flip order if necessary if self.pair_12.score() > self.pair_41.reverse().score(): self.nt1, self.nt2, self.nt3, self.nt4",
"See: <NAME>. (2007). Geometric Formalism for DNA Quadruplex Folding. Chemistry - A European",
"min_distance < 3.0: ions_outside[(min_tetrad, min_nt)].append(ion) continue logging.debug(f'Skipping an ion, because it is too",
"score best_order = order if best_score == (len(self.tetrads) - 1) * 4: break",
"A European Journal, 13(35), 9738–9745. https://doi.org/10.1002/chem.200701255 :return: Classification according to Webba da Silva",
"nt in self.nucleotides]): return None # this will create a 4-letter string made",
"'saas': GbaTetradClassification.VIb, 'asss': GbaTetradClassification.VIIa, 'saaa': GbaTetradClassification.VIIb, 'aaaa': GbaTetradClassification.VIIIa, 'ssss': GbaTetradClassification.VIIIb } if fingerprint",
"return f' {\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass class Loop: nucleotides: List[Residue3D] loop_type:",
"in self.nucleotides]) # this dict has all classes mapped to fingerprints gba_classes =",
"last: if pair.score() < pair.reverse().score(): return '-' return '+' # reverse check if",
"order == (self.nt4, self.nt3, self.nt2, self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34.reverse(), self.pair_23.reverse(),",
"n4, n1), (n3, n4, n1, n2), (n4, n1, n2, n3), (n1, n4, n3,",
"(best_score, best_order, nts1) return tetrad_scores def __find_tetrad_pairs(self, stacking_mismatch: int) -> List[TetradPair]: tetrads =",
"= 0 order = [ti] candidates = set(self.tetrads) - {ti} while candidates: tj",
"self.nt3, self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() else: raise",
"== chain: nt.index = i i += 1 for nt in self.structure3d.residues: if",
"pair.nt2 x, y = nucleotides.index(x) + 1 + shifts[x], nucleotides.index(y) + 1 +",
"f'{self.sequence}\\n{self.line1}\\n{self.line2}' return builder def __chain_order(self) -> List[str]: only_nucleic_acids = filter(lambda nt: nt.is_nucleotide, self.structure3d.residues)",
"Dict[Tuple[Residue3D, Residue3D], BasePair3D]) -> bool: lw1 = pair_dictionary[(nt1, nt2)].lw lw2 = pair_dictionary[(nt2, nt3)].lw",
"for tetrad in self.tetrads: for nt in tetrad.nucleotides: for atom in nt.atoms: distance",
"-> Direction: indices1 = list(map(lambda nt: nt.index, self.tetrad1.nucleotides)) indices2 = list(map(lambda nt: nt.index,",
"= self.tetrads[0] min_nt = min_tetrad.nt1 for tetrad in self.tetrads: for nt in tetrad.nucleotides:",
"== 2: # two in +, one in - direction return Direction.antiparallel return",
"__find_tracts(self) -> List[Tract]: tracts = [[self.tetrads[0].nt1], [self.tetrads[0].nt2], [self.tetrads[0].nt3], [self.tetrads[0].nt4]] if len(self.tetrad_pairs) > 0:",
"== last: if pair.score() < pair.reverse().score(): return '-' return '+' # reverse check",
"center_of_mass(t2)) def __calculate_twist(self) -> float: nt1_1, nt1_2, _, _ = self.tetrad1.nucleotides nt2_1, nt2_2,",
"Residue3D, nt_last: Residue3D) -> Optional[LoopType]: tetrad_with_first = self.__find_tetrad_with_nt(nt_first) tetrad_with_last = self.__find_tetrad_with_nt(nt_last) if tetrad_with_first",
"= self.structure3d.stacking_graph(self.structure2d) self.tetrads = self.__find_tetrads(self.no_reorder) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices =",
"rise={round(self.rise, 2)} twist={round(self.twist, 2)}\\n' @dataclass class Tract: nucleotides: List[Residue3D] def __str__(self): return f'",
"nt of a loop is in the same tetrad sign = self.__detect_loop_sign(nt_first, nt_last,",
"> 0: tetrads.remove(candidates[0]) else: break return sorted(tetrads, key=lambda t: min(map(lambda nt: nt.index, t.nucleotides)))",
"= tetrads for ti in tetrads: score = 0 order = [ti] candidates",
"for group in groups], key=lambda x: x[0]) def __reorder_chains(self, chain_order: Iterable[str]): i =",
"== 0: return [Quadruplex(self.tetrads, [], self.structure3d)] quadruplexes = list() tetrads = list() for",
"in tetrad.nucleotides: return tetrad return None def __find_tract_with_nt(self, nt: Residue3D) -> Optional[Tract]: for",
"for nt in self.nucleotides]) # this dict has all classes mapped to fingerprints",
"for pair in layer: x, y = pair.nt1, pair.nt2 x, y = nucleotides.index(x)",
"Residue3D, Residue3D, Residue3D]): if order == (self.nt1, self.nt2, self.nt3, self.nt4): pass elif order",
"str(tetrad_pair) builder += str(tetrad_pair.tetrad2) if self.tracts: builder += '\\n Tracts:\\n' for tract in",
"qj = candidates[i], candidates[j] if not qi.isdisjoint(qj): qi.update(qj) del candidates[j] changed = True",
"0 for i in range(4)] score_sequential = [1 if is_next_sequentially(nts1[i], nts2[i]) else 0",
"nt2 in self.stacking_graph.get(nt1, []) def is_next_sequentially(nt1: Residue3D, nt2: Residue3D) -> bool: return nt1.chain",
"del candidates[j] changed = True break candidates = sorted(candidates, key=lambda x: len(x), reverse=True)",
"pair.reverse().score(): return '+' return '-' return None def __classify_by_loops(self) -> Optional[LoopClassification]: if len(self.loops)",
"> 1: for permutation in itertools.permutations(chains): self.__reorder_chains(permutation) classifications = [t.onz for h in",
"'12', 'ldp': '13' } fingerprint = ''.join([loop.loop_type.value[0] for loop in self.loops]) if fingerprint",
"best_score: best_score = score best_permutation = permutation elif score == best_score: # in",
"2, 3): return ONZ.O_PLUS elif order == (3, 2, 1): return ONZ.O_MINUS elif",
"self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif order == (self.nt3, self.nt4, self.nt1, self.nt2):",
"= field(init=False) def __post_init__(self): self.onzm = self.__classify_onzm() self.gba_classes = self.__classify_by_gba() self.tracts = self.__find_tracts()",
"if count == 4: # all in the same direction return Direction.parallel elif",
"chain_groups: best_permutation, best_score = chains, (1e10, 1e10) if len(chains) > 1: for permutation",
"analysis: Analysis tetrads: List[Tetrad] complete2d: bool onz_dict: Dict[BasePair3D, ONZ] = field(init=False) def __post_init__(self):",
"{run.stderr.decode()}') def __to_helix(self, layer: List[BasePair3D], canonical: Optional[List[BasePair3D]] = None) -> tempfile.NamedTemporaryFile(): onz_value =",
"self.nt4 def __hash__(self): return hash(frozenset([self.nt1, self.nt2, self.nt3, self.nt4])) def __str__(self): return f' '",
"k, l, self.pair_dict): tetrads.add(frozenset([i, j, k, l])) if len(tetrads) > 1: return True",
"support = counter.most_common()[0] if support != len(self.tetrads): onz = 'M' counter = Counter([tp.direction.value[0]",
"structure3d.base_pair_graph(structure2d) self.pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = structure3d.base_pair_dict(structure2d) def has_tetrads(self): tetrads = set() for",
"result.append(f'{residue.full_name}: [{\",\".join([ion.atomName for ion in ions])}]') return 'ions_outside=' + ' '.join(result) return ''",
"chain_pairs: sum_sq += (chain_order.index(c1) - chain_order.index(c2)) ** 2 return sum_sq def __find_ions(self) ->",
"f'planarity={round(self.planarity_deviation, 2)} ' \\ f'{self.__ions_channel_str()} ' \\ f'{self.__ions_outside_str()}\\n' def chains(self) -> Set[str]: return",
"return numpy.linalg.norm(center_of_mass(t1) - center_of_mass(t2)) def __calculate_twist(self) -> float: nt1_1, nt1_2, _, _ =",
"if distance < min_distance: min_distance = distance min_tetrad = tetrad # TODO: verify",
"pair_23: BasePair3D pair_34: BasePair3D pair_41: BasePair3D onz: ONZ = field(init=False) gba_class: Optional[GbaTetradClassification] =",
"tract_with_last.nucleotides: if nt in tetrad_with_first.nucleotides: sign = self.__detect_loop_sign(nt_first, nt, tetrad_with_first) if sign is",
"[base_pair for base_pair in self.base_pairs if base_pair.is_canonical()] @dataclass class Visualizer: analysis: Analysis tetrads:",
"self.pair_12, self.pair_23 elif order == (self.nt4, self.nt1, self.nt2, self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41",
"residue.outermost_atom, self.nucleotides)) + \\ list(map(lambda residue: residue.innermost_atom, self.nucleotides)) def __ions_channel_str(self) -> str: if",
"self.helices for t in h.tetrads] logging.debug(f'Selected chain order: {\" \".join(final_order)} ' f'{\" \".join(map(lambda",
"def center_of_mass(atoms): coords = [atom.coordinates() for atom in atoms] xs = (coord[0] for",
"for atom in atoms] xs = (coord[0] for coord in coords) ys =",
"1, 3): return ONZ.Z_PLUS elif order == (3, 1, 2): return ONZ.Z_MINUS raise",
"< min_distance: min_distance = distance min_tetrad = tetrad min_nt = nt # TODO:",
"in 5'-3' order self.onz = self.__classify_onz() self.gba_class = self.__classify_by_gba() def reorder_to_match_other_tetrad(self, order: Tuple[Residue3D,",
"= [] helix_tetrads = [] helix_tetrad_pairs = [] for tp in self.tetrad_pairs: ti,",
"gbas)) def __find_tracts(self) -> List[Tract]: tracts = [[self.tetrads[0].nt1], [self.tetrads[0].nt2], [self.tetrads[0].nt3], [self.tetrads[0].nt4]] if len(self.tetrad_pairs)",
"self.nt1, self.nt2, self.nt3, self.nt4 = self.nt4, self.nt1, self.nt2, self.nt3 self.pair_12, self.pair_23, self.pair_34, self.pair_41",
"for nt in sorted(filter(lambda nt: nt.is_nucleotide, self.structure3d.residues), key=lambda nt: nt.index): if chain and",
"x in (ni, nj, nk, nl)) nmin = min(ni, nj, nk, nl) if",
"not in gba_classes: logging.error(f'Impossible combination of syn/anti: {[nt.chi_class for nt in self.nucleotides]}') return",
"used: ions.append(atom) used.add(coordinates) return ions def __assign_ions_to_tetrads(self) \\ -> Tuple[Dict[Tetrad, List[Atom3D]], Dict[Tuple[Tetrad, Residue3D],",
"stacked: Dict[Residue3D, Residue3D] tetrad2_nts_best_order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D] = field(init=False) direction: Direction =",
"BasePair3D pair_34: BasePair3D pair_41: BasePair3D onz: ONZ = field(init=False) gba_class: Optional[GbaTetradClassification] = field(init=False)",
"== (self.nt3, self.nt2, self.nt1, self.nt4): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse(),",
"because it is too far from any tetrad (distance={min_distance})') for tetrad, ions in",
"dict has all classes mapped to fingerprints gba_classes = { 'aass': GbaTetradClassification.Ia, 'ssaa':",
"in itertools.combinations(tetrads, 2): if not ti.is_disjoint(tj): graph[ti].append(tj) graph[tj].append(ti) # remove tetrad which conflicts",
"for j in filter(lambda x: x != i, self.graph[i]): for k in filter(lambda",
"n2, n3), (n1, n4, n3, n2), (n4, n3, n2, n1), (n3, n2, n1,",
"self.__to_helix(layer2) currdir = os.path.dirname(os.path.realpath(__file__)) output_pdf = f'{prefix}-{suffix}.pdf' run = subprocess.run([os.path.join(currdir, 'quadraw.R'), fasta.name, helix1.name,",
"nt.chain == chain: nt.index = i i += 1 for nt in self.structure3d.residues:",
"= counter.most_common()[0] if support != len(self.tetrad_pairs): direction = 'h' counter = Counter([t.onz.value[1] for",
"= (best_score, best_order, nts1) return tetrad_scores def __find_tetrad_pairs(self, stacking_mismatch: int) -> List[TetradPair]: tetrads",
"== (self.nt4, self.nt3, self.nt2, self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse(),",
"= counter.most_common()[0] if count == 4: # all in the same direction return",
"range(4): tracts[i].append(nt_dict[tracts[i][-1]]) return [Tract(nts) for nts in tracts] def __find_loops(self) -> List[Loop]: if",
"None loop_classes = { 'ppp': '1', 'ppl': '2', 'plp': '3', 'lpp': '4', 'pdp':",
"in metal_atom_names: coordinates = tuple(atom.coordinates()) if coordinates not in used: ions.append(atom) used.add(coordinates) return",
"pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]: # main check if pair.nt1 == first",
"nucleotides having a valid syn/anti, this classification is impossible if not all([nt.chi_class in",
"queue, removed = removed, [] order += 1 opening = '([{<' + string.ascii_uppercase",
"nt in self.nucleotides]}') return None return gba_classes[fingerprint] def __calculate_planarity_deviation(self) -> float: outer =",
"score = (onz_score, chain_order_score) if score < best_score: best_score = score best_permutation =",
"if score < best_score: best_score = score best_permutation = permutation elif score ==",
"\".join(self.__chain_order())}\\n' for helix in self.helices: builder += str(helix) builder += f'{self.sequence}\\n{self.line1}\\n{self.line2}' return builder",
"= field(init=False) def __post_init__(self): self.base_pairs = self.structure3d.base_pairs(self.structure2d) self.base_pair_graph = self.structure3d.base_pair_graph(self.structure2d, self.strict) self.base_pair_dict =",
"tetrad in self.tetrads: for nt in tetrad.nucleotides: for atom in nt.atoms: distance =",
"= self.__find_quadruplexes() def __find_quadruplexes(self): if len(self.tetrad_pairs) == 0: return [Quadruplex(self.tetrads, [], self.structure3d)] quadruplexes",
"self.__find_tetrad_with_nt(nt_first) tetrad_with_last = self.__find_tetrad_with_nt(nt_last) if tetrad_with_first is None or tetrad_with_last is None: logging.warning(f'Failed",
"h.tetrads: candidates.add(frozenset([t.nt1.chain, t.nt2.chain, t.nt3.chain, t.nt4.chain])) candidates = [set(c) for c in candidates] changed",
"= ions def __generate_twoline_dotbracket(self) -> Tuple[str, str, str, Dict[Residue3D, int]]: layer1, layer2 =",
"residue in self.structure3d.residues: for atom in residue.atoms: if atom.atomName.upper() in metal_atom_names: coordinates =",
"Tetrad.is_valid(i, j, k, l, self.pair_dict): tetrads.add(frozenset([i, j, k, l])) if len(tetrads) > 1:",
"nl = map(lambda nt: nt.index, self.nucleotides) indices = sorted((ni, nj, nk, nl)) ni,",
"'ssas': GbaTetradClassification.Vb, 'assa': GbaTetradClassification.VIa, 'saas': GbaTetradClassification.VIb, 'asss': GbaTetradClassification.VIIa, 'saaa': GbaTetradClassification.VIIb, 'aaaa': GbaTetradClassification.VIIIa, 'ssss':",
"in ions_channel.items(): tetrad.ions_channel = ions for pair, ions in ions_outside.items(): tetrad, residue =",
"def __calculate_tetrad_scores(self) \\ -> Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]]: def is_next_by_stacking(nt1: Residue3D, nt2:",
"i > 0 else -1 for i, j in zip(indices1, indices2)) direction, count",
"bool: return frozenset(self.nucleotides).isdisjoint(frozenset(other.nucleotides)) def center(self) -> numpy.ndarray: return center_of_mass(self.outer_and_inner_atoms()) def outer_and_inner_atoms(self) -> List[Atom3D]:",
"math.degrees(numpy.arccos(numpy.clip(numpy.dot(v1, v2), -1.0, 1.0))) def __str__(self): return f' direction={self.direction.value} rise={round(self.rise, 2)} twist={round(self.twist, 2)}\\n'",
"< min_distance: min_distance = distance min_tetrad = tetrad # TODO: verify threshold of",
"Structure3D): self.pairs: List[BasePair3D] = structure3d.base_pairs(structure2d) self.graph: Dict[Residue3D, List[Residue3D]] = structure3d.base_pair_graph(structure2d) self.pair_dict: Dict[Tuple[Residue3D, Residue3D],",
"__str__(self): return f' {\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass class Loop: nucleotides: List[Residue3D]",
"in self.tracts: if nt in tract.nucleotides: return tract return None def __detect_loop_sign(self, first:",
"(4 - self.stacking_mismatch): helix_tetrads.append(tj) helix_tetrad_pairs.append(tp) else: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) helix_tetrads = [ti, tj]",
"in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) helix1 = self.__to_helix(layer1, self.analysis.canonical() if self.complete2d else",
"/ numpy.linalg.norm(v1) v2 = nt2_1.find_atom(\"C1'\").coordinates() - nt2_2.find_atom(\"C1'\").coordinates() v2 = v2 / numpy.linalg.norm(v2) return",
"self.pair_34.reverse() elif order == (self.nt2, self.nt1, self.nt4, self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41 =",
"sorted([pair.nt1, pair.nt2]) dotbracket[nt1] = opening[order] dotbracket[nt2] = closing[order] sequence = '' structure =",
"for i in range(4): tracts[i].append(nt_dict[tracts[i][-1]]) return [Tract(nts) for nts in tracts] def __find_loops(self)",
"from dataclasses import dataclass, field from typing import Dict, Iterable, List, Tuple, Optional,",
"return LoopType.diagonal tract_with_last = self.__find_tract_with_nt(nt_last) if tract_with_last is not None: # search along",
"Residue3D) -> bool: return nt2 in self.stacking_graph.get(nt1, []) def is_next_sequentially(nt1: Residue3D, nt2: Residue3D)",
"center_of_mass(atoms): coords = [atom.coordinates() for atom in atoms] xs = (coord[0] for coord",
"score best_permutation = permutation elif score == best_score: # in case of a",
"for nts2 in viable_permutations: score_stacking = [1 if is_next_by_stacking(nts1[i], nts2[i]) else 0 for",
"field from typing import Dict, Iterable, List, Tuple, Optional, Set import numpy from",
"= self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse() elif order == (self.nt1, self.nt4, self.nt3, self.nt2): self.pair_12,",
"for l in filter(lambda x: x not in (i, j, k) and x",
"= self.base_pair_dict[(k, l)] pair_41 = self.base_pair_dict[(l, i)] tetrads.append(Tetrad(i, j, k, l, pair_12, pair_23,",
"self.pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = structure3d.base_pair_dict(structure2d) def has_tetrads(self): tetrads = set() for i",
"chain_order.index(c2)) ** 2 return sum_sq def __find_ions(self) -> List[Atom3D]: metal_atom_names = set([ion.value.upper() for",
"verify threshold of 3A between an ion and an atom if min_distance <",
"all nucleotides having a valid syn/anti, this classification is impossible if not all([nt.chi_class",
"for nt in self.structure3d.residues: if nt.chain == chain: nt.index = i i +=",
"search for a tetrad: i -> j -> k -> l # ^--------------^",
"for tetrad, ions in ions_channel.items(): tetrad.ions_channel = ions for pair, ions in ions_outside.items():",
"math.inf min_tetrad = self.tetrads[0] for tetrad in self.tetrads: distance = numpy.linalg.norm(ion.coordinates() - tetrad.center())",
"True nt1: Residue3D nt2: Residue3D nt3: Residue3D nt4: Residue3D pair_12: BasePair3D pair_23: BasePair3D",
"'VII': 7, 'VIII': 8} gbas = sorted(gbas, key=lambda gba: roman_numerals.get(gba, 100)) return list(map(lambda",
"return [Tract(nts) for nts in tracts] def __find_loops(self) -> List[Loop]: if len(self.tetrads) ==",
"{nt_last}') return None def __find_tetrad_with_nt(self, nt: Residue3D) -> Optional[Tetrad]: for tetrad in self.tetrads:",
"in self.helices for t in h.tetrads] logging.debug( f'Checking reorder: {\" \".join(permutation)} {\" \".join(map(lambda",
"-> numpy.ndarray: return center_of_mass(self.outer_and_inner_atoms()) def outer_and_inner_atoms(self) -> List[Atom3D]: return list(map(lambda residue: residue.outermost_atom, self.nucleotides))",
"nt.chain not in chain_order: nt.index = i i += 1 if len(self.tetrad_pairs) >",
"int base_pairs: List[BasePair3D] = field(init=False) base_pair_graph: Dict[Residue3D, List[Residue3D]] = field(init=False) base_pair_dict: Dict[Tuple[Residue3D, Residue3D],",
"BasePair3D]) -> bool: lw1 = pair_dictionary[(nt1, nt2)].lw lw2 = pair_dictionary[(nt2, nt3)].lw lw3 =",
"(3, 2, 1): return ONZ.O_MINUS elif order == (1, 3, 2): return ONZ.N_PLUS",
"\\ f'{\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass class Quadruplex: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair]",
"len(self.tetrad_pairs) > 0: for tetrad_pair in self.tetrad_pairs: nt_dict = { tetrad_pair.tetrad1.nt1: tetrad_pair.tetrad2_nts_best_order[0], tetrad_pair.tetrad1.nt2:",
"a tetrad: i -> j -> k -> l # ^--------------^ tetrads =",
"Tetrad stacked: Dict[Residue3D, Residue3D] tetrad2_nts_best_order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D] = field(init=False) direction: Direction",
"raise RuntimeError(f'Impossible combination: {ni} {nj} {nk} {nl}') def __classify_by_gba(self) -> Optional[GbaTetradClassification]: \"\"\" See:",
"for atom in self.ions_channel]) return '' def __ions_outside_str(self) -> str: if self.ions_outside: result",
"_ = self.__elimination_conflicts(layer2) return sequence, line1, line2, shifts def __elimination_conflicts(self, pairs: List[BasePair3D]) ->",
"return [] loops = [] tetrad_nucleotides = sorted([nt for tetrad in self.tetrads for",
"and ncur in tract.nucleotides: break else: nts = list(filter(lambda nt: nprev.index < nt.index",
"(0, 1, 2, 3) ni, nj, nk, nl = map(lambda nt: nt.index, self.nucleotides)",
"')]}>' + string.ascii_lowercase dotbracket = dict() for pair, order in orders.items(): nt1, nt2",
"self.graph[i]): for k in filter(lambda x: x not in (i, j), self.graph[j]): for",
"is_valid(nt1: Residue3D, nt2: Residue3D, nt3: Residue3D, nt4: Residue3D, pair_dictionary: Dict[Tuple[Residue3D, Residue3D], BasePair3D]) ->",
"- A European Journal, 13(35), 9738–9745. https://doi.org/10.1002/chem.200701255 :return: Classification according to Webba da",
"tetrad_with_first) if sign is not None: return LoopType.from_value(f'lateral{sign}') return LoopType.diagonal tract_with_last = self.__find_tract_with_nt(nt_last)",
"is None for loop in self.loops]): return None loop_classes = { 'ppp': '1',",
"x: x[0]) def __reorder_chains(self, chain_order: Iterable[str]): i = 1 for chain in chain_order:",
"= (nj, nk, nl) if order == (1, 2, 3): return ONZ.O_PLUS elif",
"2): return ONZ.Z_MINUS raise RuntimeError(f'Impossible combination: {ni} {nj} {nk} {nl}') def __classify_by_gba(self) ->",
"Optional[Tract]: for tract in self.tracts: if nt in tract.nucleotides: return tract return None",
"1], best_order[i] score = self.tetrad_scores[ti][tj][0] if score >= (4 - stacking_mismatch): nts1, nts2",
"groups], key=lambda x: x[0]) def __reorder_chains(self, chain_order: Iterable[str]): i = 1 for chain",
"[], self.structure3d)] quadruplexes = list() tetrads = list() for tetrad in [self.tetrad_pairs[0].tetrad1] +",
"ONZ.N_PLUS: 3, ONZ.N_MINUS: 4, ONZ.Z_PLUS: 5, ONZ.Z_MINUS: 6} nucleotides = self.analysis.structure3d.residues shifts =",
"/ len(coords), sum(ys) / len(coords), sum(zs) / len(coords))) def eltetrado(structure2d: Structure2D, structure3d: Structure3D,",
"tetrad in [self.tetrad_pairs[0].tetrad1] + [tetrad_pair.tetrad2 for tetrad_pair in self.tetrad_pairs]: if tetrads: if tetrad.chains().isdisjoint(tetrads[-1].chains()):",
"\"R\"}' builder += f' {\",\".join(map(lambda gba: gba.value, self.gba_classes))}' if self.loop_class: builder += f'",
"0: tetrads.remove(candidates[0]) else: break return sorted(tetrads, key=lambda t: min(map(lambda nt: nt.index, t.nucleotides))) def",
"GbaTetradClassification.IVb, 'aasa': GbaTetradClassification.Va, 'ssas': GbaTetradClassification.Vb, 'assa': GbaTetradClassification.VIa, 'saas': GbaTetradClassification.VIb, 'asss': GbaTetradClassification.VIIa, 'saaa': GbaTetradClassification.VIIb,",
"# search for a tetrad: i -> j -> k -> l #",
"{self.loop_type.value if self.loop_type else \"n/a\"} ' \\ f'{\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass",
"LoopType, ONZM, GbaQuadruplexClassification, LoopClassification logging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"INFO\")) @dataclass(order=True) class Tetrad: @staticmethod def is_valid(nt1: Residue3D,",
"[self.tetrads[0].nt4]] if len(self.tetrad_pairs) > 0: for tetrad_pair in self.tetrad_pairs: nt_dict = { tetrad_pair.tetrad1.nt1:",
"ni, nj, nk order = (nj, nk, nl) if order == (1, 2,",
"order == (2, 1, 3): return ONZ.Z_PLUS elif order == (3, 1, 2):",
"for anti fingerprint = ''.join([nt.chi_class.value[0] for nt in self.nucleotides]) # this dict has",
"graph[tj].append(ti) # remove tetrad which conflicts the most with others # in case",
"of 6A between an ion and tetrad channel if min_distance < 6.0: ions_channel[min_tetrad].append(ion)",
"> 1: builder += f'n4-helix with {len(self.tetrads)} tetrads\\n' for quadruplex in self.quadruplexes: builder",
"if not helix_tetrads: helix_tetrads.append(ti) score = self.tetrad_scores[helix_tetrads[-1]][tj][0] if score >= (4 - self.stacking_mismatch):",
"plus_minus, support = counter.most_common()[0] if support != len(self.tetrads): plus_minus = '*' return ONZM.from_value(f'{onz}{direction}{plus_minus}')",
"chain_order: Iterable[str]): i = 1 for chain in chain_order: for nt in self.structure3d.residues:",
"in queue}) queue, removed = removed, [] order += 1 opening = '([{<'",
"float = field(init=False) ions_channel: List[Atom3D] = field(default_factory=list) ions_outside: Dict[Residue3D, List[Atom3D]] = field(default_factory=dict) def",
"in tetrad_with_first.nucleotides: sign = self.__detect_loop_sign(nt_first, nt, tetrad_with_first) if sign is not None: return",
"tetrad_with_first.nucleotides: sign = self.__detect_loop_sign(nt_first, nt, tetrad_with_first) if sign is not None: return LoopType.from_value(f'propeller{sign}')",
"'aaaa': GbaTetradClassification.VIIIa, 'ssss': GbaTetradClassification.VIIIb } if fingerprint not in gba_classes: logging.error(f'Impossible combination of",
"# count directions 5' -> 3' as +1 or -1 counter = Counter(1",
"tetrad2_nts_best_order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D] = field(init=False) direction: Direction = field(init=False) rise: float",
"if self.loop_class: builder += f' {self.loop_class.value} {self.loop_class.loop_progression()}' else: builder += f' n/a' builder",
"numpy from eltetrado.model import Atom3D, Structure3D, Structure2D, BasePair3D, Residue3D, GlycosidicBond, ONZ, \\ GbaTetradClassification,",
"list(map(lambda residue: residue.innermost_atom, self.nucleotides)) def __ions_channel_str(self) -> str: if self.ions_channel: return 'ions_channel=' +",
"self.tetrads]): return None counter = Counter([t.onz.value[0] for t in self.tetrads]) onz, support =",
"nts in tracts] def __find_loops(self) -> List[Loop]: if len(self.tetrads) == 1: return []",
"self.pair_23, self.pair_34 elif order == (self.nt4, self.nt3, self.nt2, self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41",
"!= i, self.base_pair_graph[i]): for k in filter(lambda x: x not in (i, j),",
"best_score = score best_permutation = permutation elif score == best_score: # in case",
"-> Tuple[str, str, Dict[Residue3D, int]]: orders = dict() order = 0 queue =",
"order = 0 queue = list(pairs) removed = [] while queue: conflicts =",
"pair.nt1 == last and pair.nt2 == first: if pair.score() < pair.reverse().score(): return '+'",
"opening[order] dotbracket[nt2] = closing[order] sequence = '' structure = '' shifts = dict()",
"shifts def __str__(self): builder = f'Chain order: {\" \".join(self.__chain_order())}\\n' for helix in self.helices:",
"= self.__find_tetrad_with_nt(nt_first) tetrad_with_last = self.__find_tetrad_with_nt(nt_last) if tetrad_with_first is None or tetrad_with_last is None:",
"check_pair(tp: TetradPair) -> bool: return check_tetrad(tp.tetrad1) and check_tetrad(tp.tetrad2) return list(filter(check_pair, self.tetrad_pairs)) def __str__(self):",
"in zip(indices1, indices2)) direction, count = counter.most_common()[0] if count == 4: # all",
"5, 'VI': 6, 'VII': 7, 'VIII': 8} gbas = sorted(gbas, key=lambda gba: roman_numerals.get(gba,",
"= field(init=False) stacking_graph: Dict[Residue3D, List[Residue3D]] = field(init=False) tetrads: List[Tetrad] = field(init=False) tetrad_scores: Dict[Tetrad,",
"flip order if necessary if self.pair_12.score() > self.pair_41.reverse().score(): self.nt1, self.nt2, self.nt3, self.nt4 =",
"def __post_init__(self): self.base_pairs = self.structure3d.base_pairs(self.structure2d) self.base_pair_graph = self.structure3d.base_pair_graph(self.structure2d, self.strict) self.base_pair_dict = self.structure3d.base_pair_dict(self.structure2d, self.strict)",
"for h in self.helices: for t in h.tetrads: for p in [t.pair_12, t.pair_23,",
"tj in candidates], key=lambda tk: self.tetrad_scores[ti][tk][0]) score += self.tetrad_scores[ti][tj][0] order.append(tj) candidates.remove(tj) ti =",
"between an ion and tetrad channel if min_distance < 6.0: ions_channel[min_tetrad].append(ion) continue min_distance",
"self.__generate_twoline_dotbracket() self.ions = self.__find_ions() self.__assign_ions_to_tetrads() def __find_tetrads(self, no_reorder=False) -> List[Tetrad]: # search for",
"a tie, remove one which has the worst planarity deviation candidates = sorted(tetrads,",
"None else \"R\"}' builder += f' {\",\".join(map(lambda gba: gba.value, self.gba_classes))}' if self.loop_class: builder",
"self.nt2, self.nt3, self.nt4])) def __str__(self): return f' ' \\ f'{self.nt1.full_name} {self.nt2.full_name} {self.nt3.full_name} {self.nt4.full_name}",
"nt: nprev.index < nt.index < ncur.index, self.structure3d.residues)) loop_type = self.__detect_loop_type(nprev, ncur) loops.append(Loop(nts, loop_type))",
"if fingerprint not in loop_classes: logging.error(f'Unknown loop classification: {fingerprint}') return None subtype =",
"self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34 # flip order if necessary if self.pair_12.score()",
"field(init=False) def __post_init__(self): self.tetrad2_nts_best_order = ( self.stacked[self.tetrad1.nt1], self.stacked[self.tetrad1.nt2], self.stacked[self.tetrad1.nt3], self.stacked[self.tetrad1.nt4] ) self.direction =",
"nj, nk, nl = nl, ni, nj, nk order = (nj, nk, nl)",
"nt: nt.index, self.tetrad1.nucleotides)) indices2 = list(map(lambda nt: nt.index, self.tetrad2_nts_best_order)) # count directions 5'",
"tetrad_pair.tetrad2_nts_best_order[3], } for i in range(4): tracts[i].append(nt_dict[tracts[i][-1]]) return [Tract(nts) for nts in tracts]",
"c1 in chain_order and c2 in chain_order: chain_pairs.append([c1, c2]) sum_sq = 0 for",
"in itertools.permutations(chains): self.__reorder_chains(permutation) classifications = [t.onz for h in self.helices for t in",
"between an ion and an atom if min_distance < 3.0: ions_outside[(min_tetrad, min_nt)].append(ion) continue",
"= self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse() elif order == (self.nt3, self.nt2, self.nt1, self.nt4): self.pair_12,",
":return: Classification according to Webba da Silva or n/a \"\"\" # without all",
"# main check if pair.nt1 == first and pair.nt2 == last: if pair.score()",
"f' {self.loop_type.value if self.loop_type else \"n/a\"} ' \\ f'{\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}'",
"str = field(init=False) line2: str = field(init=False) shifts: Dict[Residue3D, int] = field(init=False) def",
"== lw_j.name[2]: return False return True nt1: Residue3D nt2: Residue3D nt3: Residue3D nt4:",
"what pairs with nt_first for nt in tract_with_last.nucleotides: if nt in tetrad_with_first.nucleotides: sign",
"-> bool: return frozenset(self.nucleotides).isdisjoint(frozenset(other.nucleotides)) def center(self) -> numpy.ndarray: return center_of_mass(self.outer_and_inner_atoms()) def outer_and_inner_atoms(self) ->",
"self.nt2, self.nt3, self.nt4 = self.nt4, self.nt1, self.nt2, self.nt3 self.pair_12, self.pair_23, self.pair_34, self.pair_41 =",
"str(tetrad_pair.tetrad2) if self.tracts: builder += '\\n Tracts:\\n' for tract in self.tracts: builder +=",
"lw3 = pair_dictionary[(nt3, nt4)].lw lw4 = pair_dictionary[(nt4, nt1)].lw for lw_i, lw_j in ((lw1,",
"{self.onzm.value if self.onzm is not None else \"R\"}' builder += f' {\",\".join(map(lambda gba:",
"List[Tetrad] = field(init=False) tetrad_scores: Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]] = field(init=False) tetrad_pairs: List[TetradPair]",
"t.nt4.chain])) candidates = [set(c) for c in candidates] changed = True while changed:",
"= 0 best_score_stacking = 0 best_order = tj.nucleotides n1, n2, n3, n4 =",
"'1', 'ppl': '2', 'plp': '3', 'lpp': '4', 'pdp': '5', 'lll': '6', 'llp': '7',",
"min_distance = distance min_tetrad = tetrad min_nt = nt # TODO: verify threshold",
"builder += str(helix) builder += f'{self.sequence}\\n{self.line1}\\n{self.line2}' return builder def __chain_order(self) -> List[str]: only_nucleic_acids",
"used = set() for residue in self.structure3d.residues: for atom in residue.atoms: if atom.atomName.upper()",
"+= str(self.tetrad_pairs[0].tetrad1) for tetrad_pair in self.tetrad_pairs: builder += str(tetrad_pair) builder += str(tetrad_pair.tetrad2) if",
"+= f' {\",\".join(map(lambda gba: gba.value, self.gba_classes))}' if self.loop_class: builder += f' {self.loop_class.value} {self.loop_class.loop_progression()}'",
"when first and last nt of a loop is in the same tetrad",
"return '+' return '-' return None def __classify_by_loops(self) -> Optional[LoopClassification]: if len(self.loops) !=",
"str(quadruplex) elif len(self.tetrads) == 1: builder += 'single tetrad without stacking\\n' builder +=",
"< 3.0: ions_outside[(min_tetrad, min_nt)].append(ion) continue logging.debug(f'Skipping an ion, because it is too far",
"for coord in coords) ys = (coord[1] for coord in coords) zs =",
"# this will create a 4-letter string made of 's' for syn or",
"in filter(lambda x: x not in (i, j), self.base_pair_graph[j]): for l in filter(lambda",
"filter(lambda nt: nt.is_nucleotide, self.structure3d.residues) return list({nt.chain: 0 for nt in sorted(only_nucleic_acids, key=lambda nt:",
"= field(init=False) gba_class: Optional[GbaTetradClassification] = field(init=False) planarity_deviation: float = field(init=False) ions_channel: List[Atom3D] =",
"Residue3D] = field(init=False) direction: Direction = field(init=False) rise: float = field(init=False) twist: float",
"nt1_2.find_atom(\"C1'\").coordinates() v1 = v1 / numpy.linalg.norm(v1) v2 = nt2_1.find_atom(\"C1'\").coordinates() - nt2_2.find_atom(\"C1'\").coordinates() v2 =",
"{nt_first} and {nt_last}') return None def __find_tetrad_with_nt(self, nt: Residue3D) -> Optional[Tetrad]: for tetrad",
"self.line2, self.shifts = self.__generate_twoline_dotbracket() self.ions = self.__find_ions() self.__assign_ions_to_tetrads() def __find_tetrads(self, no_reorder=False) -> List[Tetrad]:",
"== 0: return {}, {} ions_channel = defaultdict(list) ions_outside = defaultdict(list) for ion",
"shifts[x], nucleotides.index(y) + 1 + shifts[y] helix.write(f'{x}\\t{y}\\t1\\t8\\n') helix.flush() return helix class AnalysisSimple: def",
"__reorder_chains(self, chain_order: Iterable[str]): i = 1 for chain in chain_order: for nt in",
"List[Quadruplex] = field(init=False) def __post_init__(self): self.quadruplexes = self.__find_quadruplexes() def __find_quadruplexes(self): if len(self.tetrad_pairs) ==",
"(self.nt4, self.nt1, self.nt2, self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34",
"9738–9745. https://doi.org/10.1002/chem.200701255 :return: Classification according to Webba da Silva or n/a \"\"\" #",
"'V': 5, 'VI': 6, 'VII': 7, 'VIII': 8} gbas = sorted(gbas, key=lambda gba:",
"da Silva or n/a \"\"\" # without all nucleotides having a valid syn/anti,",
"tj] helix_tetrad_pairs = [tp] if helix_tetrads: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) for tetrad in self.tetrads:",
"nt2_1.find_atom(\"C1'\").coordinates() - nt2_2.find_atom(\"C1'\").coordinates() v2 = v2 / numpy.linalg.norm(v2) return math.degrees(numpy.arccos(numpy.clip(numpy.dot(v1, v2), -1.0, 1.0)))",
"this is required to recalculate ONZ tp.tetrad2.reorder_to_match_other_tetrad(order) def __chain_order_score(self, chain_order: Tuple[str, ...]) ->",
"ONZ: # transform into (0, 1, 2, 3) ni, nj, nk, nl =",
"List[str]: only_nucleic_acids = filter(lambda nt: nt.is_nucleotide, self.structure3d.residues) return list({nt.chain: 0 for nt in",
"len(self.tetrads) == 1: return [] loops = [] tetrad_nucleotides = sorted([nt for tetrad",
"if necessary if self.pair_12.score() > self.pair_41.reverse().score(): self.nt1, self.nt2, self.nt3, self.nt4 = self.nt1, self.nt4,",
"ions_channel: List[Atom3D] = field(default_factory=list) ions_outside: Dict[Residue3D, List[Atom3D]] = field(default_factory=dict) def __post_init__(self): self.reorder_to_match_5p_3p() self.planarity_deviation",
"(indices.index(x) for x in (ni, nj, nk, nl)) nmin = min(ni, nj, nk,",
"\".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass class Quadruplex: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D",
"else 1].loop_type.value[-1] == '-' else 'b' return LoopClassification.from_value(f'{loop_classes[fingerprint]}{subtype}') def __str__(self): builder = ''",
"tetrad\\n' builder += str(self.tetrads[0]) else: builder += f' {self.onzm.value if self.onzm is not",
"layer2 = [], [] for tetrad in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) sequence,",
"loops def __detect_loop_type(self, nt_first: Residue3D, nt_last: Residue3D) -> Optional[LoopType]: tetrad_with_first = self.__find_tetrad_with_nt(nt_first) tetrad_with_last",
"nt.index): if chain and chain != nt.chain: sequence += '-' structure += '-'",
"> 0: self.tetrad_pairs[0].tetrad1.reorder_to_match_5p_3p() for tp in self.tetrad_pairs: order = (tp.stacked[tp.tetrad1.nt1], tp.stacked[tp.tetrad1.nt2], tp.stacked[tp.tetrad1.nt3], tp.stacked[tp.tetrad1.nt4])",
"if len(tetrads) > 1: return True return False def center_of_mass(atoms): coords = [atom.coordinates()",
"str: if self.ions_outside: result = [] for residue, ions in self.ions_outside.items(): result.append(f'{residue.full_name}: [{\",\".join([ion.atomName",
"@staticmethod def is_valid(nt1: Residue3D, nt2: Residue3D, nt3: Residue3D, nt4: Residue3D, pair_dictionary: Dict[Tuple[Residue3D, Residue3D],",
"order if necessary if self.pair_12.score() > self.pair_41.reverse().score(): self.nt1, self.nt2, self.nt3, self.nt4 = self.nt1,",
"Residue3D, Residue3D, Residue3D]: return self.nt1, self.nt2, self.nt3, self.nt4 def __hash__(self): return hash(frozenset([self.nt1, self.nt2,",
"tetrad_scores[tj][ti] = (best_score, best_order, nts1) return tetrad_scores def __find_tetrad_pairs(self, stacking_mismatch: int) -> List[TetradPair]:",
"self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34 elif order == (self.nt4, self.nt3,",
"7, 'VIII': 8} gbas = sorted(gbas, key=lambda gba: roman_numerals.get(gba, 100)) return list(map(lambda x:",
"in canonical: x, y = pair.nt1, pair.nt2 x, y = nucleotides.index(x) + 1",
"sum_sq = 0 for c1, c2 in chain_pairs: sum_sq += (chain_order.index(c1) - chain_order.index(c2))",
"self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34 # flip order if necessary",
"= pair tetrad.ions_outside[residue] = ions def __generate_twoline_dotbracket(self) -> Tuple[str, str, str, Dict[Residue3D, int]]:",
"elif score == best_score: # in case of a tie, pick permutation earlier",
"Dict, Iterable, List, Tuple, Optional, Set import numpy from eltetrado.model import Atom3D, Structure3D,",
"== 1 tetrad_scores = defaultdict(dict) for ti, tj in itertools.combinations(self.tetrads, 2): nts1 =",
"if coordinates not in used: ions.append(atom) used.add(coordinates) return ions def __assign_ions_to_tetrads(self) \\ ->",
"prepare visualization, reason:\\n {run.stderr.decode()}') def __to_helix(self, layer: List[BasePair3D], canonical: Optional[List[BasePair3D]] = None) ->",
"Optional[str]: for pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]: # main check if pair.nt1",
"nl) if nmin == ni: pass elif nmin == nj: self.nt1, self.nt2, self.nt3,",
"self.structure3d.residues: if nt.chain not in chain_order: nt.index = i i += 1 if",
"best_score == (len(self.tetrads) - 1) * 4: break tetrad_pairs = [] for i",
"nt.index, self.tetrad1.nucleotides)) indices2 = list(map(lambda nt: nt.index, self.tetrad2_nts_best_order)) # count directions 5' ->",
"loops: List[Loop] = field(init=False) loop_class: Optional[LoopClassification] = field(init=False) def __post_init__(self): self.onzm = self.__classify_onzm()",
"helices def __find_best_chain_order(self): chain_groups = self.__group_related_chains() final_order = [] for chains in chain_groups:",
"[] for tp in self.tetrad_pairs: ti, tj = tp.tetrad1, tp.tetrad2 if not helix_tetrads:",
"order == (self.nt1, self.nt4, self.nt3, self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(),",
"'6', 'llp': '7', 'lpl': '8', 'pll': '9', 'pdl': '10', 'ldl': '11', 'dpd': '12',",
"= self.structure3d.base_pair_dict(self.structure2d, self.strict) self.stacking_graph = self.structure3d.stacking_graph(self.structure2d) self.tetrads = self.__find_tetrads(self.no_reorder) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs",
"self.pair_12.score() > self.pair_41.reverse().score(): self.nt1, self.nt2, self.nt3, self.nt4 = self.nt1, self.nt4, self.nt3, self.nt2 self.pair_12,",
"self.nt2, self.nt3, self.nt4 = self.nt1, self.nt4, self.nt3, self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41 =",
"self.__classify_by_loops() def __classify_onzm(self) -> Optional[ONZM]: if len(self.tetrads) == 1: return None if any([t.onz",
"distance < min_distance: min_distance = distance min_tetrad = tetrad min_nt = nt #",
"orders.items(): nt1, nt2 = sorted([pair.nt1, pair.nt2]) dotbracket[nt1] = opening[order] dotbracket[nt2] = closing[order] sequence",
"nt2 = sorted([pair.nt1, pair.nt2]) dotbracket[nt1] = opening[order] dotbracket[nt2] = closing[order] sequence = ''",
"helix in self.helices: builder += str(helix) builder += f'{self.sequence}\\n{self.line1}\\n{self.line2}' return builder def __chain_order(self)",
"'' if len(self.tetrads) == 1: builder += ' single tetrad\\n' builder += str(self.tetrads[0])",
"fasta.write(f'>{prefix}-{suffix}\\n') fasta.write(self.analysis.sequence) fasta.flush() layer1, layer2 = [], [] for tetrad in self.tetrads: layer1.extend([tetrad.pair_12,",
"= {ONZ.O_PLUS: 1, ONZ.O_MINUS: 2, ONZ.N_PLUS: 3, ONZ.N_MINUS: 4, ONZ.Z_PLUS: 5, ONZ.Z_MINUS: 6}",
"indices = sorted((ni, nj, nk, nl)) ni, nj, nk, nl = (indices.index(x) for",
"-> List[Loop]: if len(self.tetrads) == 1: return [] loops = [] tetrad_nucleotides =",
"is_next_sequentially(nt1: Residue3D, nt2: Residue3D) -> bool: return nt1.chain == nt2.chain and abs(nt1.index -",
"list() tetrads.append(tetrad) quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) return quadruplexes def __filter_tetrad_pairs(self, tetrads: List[Tetrad]) -> List[TetradPair]:",
"List[Atom3D]]]: if len(self.tetrads) == 0: return {}, {} ions_channel = defaultdict(list) ions_outside =",
"order == (self.nt2, self.nt1, self.nt4, self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_12.reverse(), self.pair_41.reverse(),",
"def __str__(self): return f' ' \\ f'{self.nt1.full_name} {self.nt2.full_name} {self.nt3.full_name} {self.nt4.full_name} ' \\ f'{self.pair_12.lw.value}",
"Residue3D, pair_dictionary: Dict[Tuple[Residue3D, Residue3D], BasePair3D]) -> bool: lw1 = pair_dictionary[(nt1, nt2)].lw lw2 =",
"6A between an ion and tetrad channel if min_distance < 6.0: ions_channel[min_tetrad].append(ion) continue",
"= list(filter(lambda nt: nprev.index < nt.index < ncur.index, self.structure3d.residues)) loop_type = self.__detect_loop_type(nprev, ncur)",
"pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]} def visualize(self, prefix: str, suffix: str): fasta",
"l in filter(lambda x: x not in (i, j, k) and i in",
"self.onz = self.__classify_onz() self.gba_class = self.__classify_by_gba() def reorder_to_match_other_tetrad(self, order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D]):",
"self.tetrads: distance = numpy.linalg.norm(ion.coordinates() - tetrad.center()) if distance < min_distance: min_distance = distance",
"'+' return '-' return None def __classify_by_loops(self) -> Optional[LoopClassification]: if len(self.loops) != 3",
"def is_next_by_stacking(nt1: Residue3D, nt2: Residue3D) -> bool: return nt2 in self.stacking_graph.get(nt1, []) def",
"def __classify_onz(self) -> ONZ: # transform into (0, 1, 2, 3) ni, nj,",
"logging.warning(f'Failed to classify the loop between {nt_first} and {nt_last}') return None if tetrad_with_first",
"def __post_init__(self): self.quadruplexes = self.__find_quadruplexes() def __find_quadruplexes(self): if len(self.tetrad_pairs) == 0: return [Quadruplex(self.tetrads,",
"[] order += 1 opening = '([{<' + string.ascii_uppercase closing = ')]}>' +",
"pair in queue}) queue, removed = removed, [] order += 1 opening =",
"direction, support = counter.most_common()[0] if support != len(self.tetrad_pairs): direction = 'h' counter =",
"helix_tetrad_pairs, self.structure3d)) helix_tetrads = [ti, tj] helix_tetrad_pairs = [tp] if helix_tetrads: helices.append(Helix(helix_tetrads, helix_tetrad_pairs,",
"self.pair_41, self.pair_12 elif nmin == nk: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt3, self.nt4,",
"last: Residue3D, tetrad: Tetrad) -> Optional[str]: for pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]:",
"sorted(filter(lambda nt: nt.is_nucleotide, self.structure3d.residues), key=lambda nt: nt.index): if chain and chain != nt.chain:",
"''.join([loop.loop_type.value[0] for loop in self.loops]) if fingerprint not in loop_classes: logging.error(f'Unknown loop classification:",
"= set(self.tetrads) - {ti} while candidates: tj = max([tj for tj in candidates],",
"len(self.tetrads) > 1: builder += f'n4-helix with {len(self.tetrads)} tetrads\\n' for quadruplex in self.quadruplexes:",
"itertools import logging import math import os import string import subprocess import tempfile",
"if chain and chain != nt.chain: sequence += '-' structure += '-' shift_value",
"= field(init=False) twist: float = field(init=False) def __post_init__(self): self.tetrad2_nts_best_order = ( self.stacked[self.tetrad1.nt1], self.stacked[self.tetrad1.nt2],",
"elif order == (self.nt3, self.nt4, self.nt1, self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34,",
"syn/anti: {[nt.chi_class for nt in self.nucleotides]}') return None return gba_classes[fingerprint] def __calculate_planarity_deviation(self) ->",
"Direction: indices1 = list(map(lambda nt: nt.index, self.tetrad1.nucleotides)) indices2 = list(map(lambda nt: nt.index, self.tetrad2_nts_best_order))",
"combination of syn/anti: {[nt.chi_class for nt in self.nucleotides]}') return None return gba_classes[fingerprint] def",
"__detect_loop_type(self, nt_first: Residue3D, nt_last: Residue3D) -> Optional[LoopType]: tetrad_with_first = self.__find_tetrad_with_nt(nt_first) tetrad_with_last = self.__find_tetrad_with_nt(nt_last)",
"tetrad in self.tetrads: distance = numpy.linalg.norm(ion.coordinates() - tetrad.center()) if distance < min_distance: min_distance",
"self.nt2, self.nt3, self.nt4 = self.nt3, self.nt4, self.nt1, self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41 =",
"bool, no_reorder: bool, stacking_mismatch: int) -> Analysis: return Analysis(structure2d, structure3d, strict, no_reorder, stacking_mismatch)",
"sequence += nt.one_letter_name structure += dotbracket.get(nt, '.') shifts[nt] = shift_value chain = nt.chain",
"builder += f'{self.sequence}\\n{self.line1}\\n{self.line2}' return builder def __chain_order(self) -> List[str]: only_nucleic_acids = filter(lambda nt:",
"1, 2): return ONZ.Z_MINUS raise RuntimeError(f'Impossible combination: {ni} {nj} {nk} {nl}') def __classify_by_gba(self)",
"field(init=False) tetrads: List[Tetrad] = field(init=False) tetrad_scores: Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]] = field(init=False)",
"else: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) helix_tetrads = [ti, tj] helix_tetrad_pairs = [tp] if helix_tetrads:",
"{ 'aass': GbaTetradClassification.Ia, 'ssaa': GbaTetradClassification.Ib, 'asas': GbaTetradClassification.IIa, 'sasa': GbaTetradClassification.IIb, 'asaa': GbaTetradClassification.IIIa, 'sass': GbaTetradClassification.IIIb,",
"self.pair_41, self.pair_12, self.pair_23, self.pair_34 # flip order if necessary if self.pair_12.score() > self.pair_41.reverse().score():",
"chains, (1e10, 1e10) if len(chains) > 1: for permutation in itertools.permutations(chains): self.__reorder_chains(permutation) classifications",
"- tetrad.center()) if distance < min_distance: min_distance = distance min_tetrad = tetrad #",
"field(init=False) rise: float = field(init=False) twist: float = field(init=False) def __post_init__(self): self.tetrad2_nts_best_order =",
"'3', 'lpp': '4', 'pdp': '5', 'lll': '6', 'llp': '7', 'lpl': '8', 'pll': '9',",
"< pair.reverse().score(): return '+' return '-' return None def __classify_by_loops(self) -> Optional[LoopClassification]: if",
"for tetrad in self.tetrads: if nt in tetrad.nucleotides: return tetrad return None def",
"self.__classify_onzm() self.gba_classes = self.__classify_by_gba() self.tracts = self.__find_tracts() self.loops = self.__find_loops() self.loop_class = self.__classify_by_loops()",
"first: if pair.score() < pair.reverse().score(): return '+' return '-' return None def __classify_by_loops(self)",
"-> bool: lw1 = pair_dictionary[(nt1, nt2)].lw lw2 = pair_dictionary[(nt2, nt3)].lw lw3 = pair_dictionary[(nt3,",
"self.pair_12 elif nmin == nk: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt3, self.nt4, self.nt1,",
"removed, [] order += 1 opening = '([{<' + string.ascii_uppercase closing = ')]}>'",
"RuntimeError(f'Impossible combination: {ni} {nj} {nk} {nl}') def __classify_by_gba(self) -> Optional[GbaTetradClassification]: \"\"\" See: <NAME>.",
"nt in sorted(filter(lambda nt: nt.is_nucleotide, self.structure3d.residues), key=lambda nt: nt.index): if chain and chain",
"if canonical: for pair in canonical: x, y = pair.nt1, pair.nt2 x, y",
"'10', 'ldl': '11', 'dpd': '12', 'ldp': '13' } fingerprint = ''.join([loop.loop_type.value[0] for loop",
"eltetrado.model import Atom3D, Structure3D, Structure2D, BasePair3D, Residue3D, GlycosidicBond, ONZ, \\ GbaTetradClassification, Ion, Direction,",
"self.nt4, self.nt3, self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() else:",
"(n4, n3, n2, n1), (n3, n2, n1, n4), (n2, n1, n4, n3)] for",
"[ti, tj] helix_tetrad_pairs = [tp] if helix_tetrads: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) for tetrad in",
"\\ -> Tuple[Dict[Tetrad, List[Atom3D]], Dict[Tuple[Tetrad, Residue3D], List[Atom3D]]]: if len(self.tetrads) == 0: return {},",
"a 4-letter string made of 's' for syn or 'a' for anti fingerprint",
"order += 1 opening = '([{<' + string.ascii_uppercase closing = ')]}>' + string.ascii_lowercase",
"counter.most_common()[0] if count == 4: # all in the same direction return Direction.parallel",
"self.stacked[self.tetrad1.nt3], self.stacked[self.tetrad1.nt4] ) self.direction = self.__determine_direction() self.rise = self.__calculate_rise() self.twist = self.__calculate_twist() def",
"6, 'VII': 7, 'VIII': 8} gbas = sorted(gbas, key=lambda gba: roman_numerals.get(gba, 100)) return",
"and check_tetrad(tp.tetrad2) return list(filter(check_pair, self.tetrad_pairs)) def __str__(self): builder = '' if len(self.tetrads) >",
"self.__reorder_chains(permutation) classifications = [t.onz for h in self.helices for t in h.tetrads] logging.debug(",
"{\" \".join(self.__chain_order())}\\n' for helix in self.helices: builder += str(helix) builder += f'{self.sequence}\\n{self.line1}\\n{self.line2}' return",
"list() tetrads = list() for tetrad in [self.tetrad_pairs[0].tetrad1] + [tetrad_pair.tetrad2 for tetrad_pair in",
"self.tetrad1.nucleotides)) indices2 = list(map(lambda nt: nt.index, self.tetrad2_nts_best_order)) # count directions 5' -> 3'",
"== 4: # all in the same direction return Direction.parallel elif count ==",
"len(graph[candidates[0]]) > 0: tetrads.remove(candidates[0]) else: break return sorted(tetrads, key=lambda t: min(map(lambda nt: nt.index,",
"== best_score: # in case of a tie, pick permutation earlier in lexicographical",
"for base_pair in self.base_pairs if base_pair.is_canonical()] @dataclass class Visualizer: analysis: Analysis tetrads: List[Tetrad]",
"def __reorder_chains(self, chain_order: Iterable[str]): i = 1 for chain in chain_order: for nt",
"suffix: str): fasta = tempfile.NamedTemporaryFile('w+', suffix='.fasta') fasta.write(f'>{prefix}-{suffix}\\n') fasta.write(self.analysis.sequence) fasta.flush() layer1, layer2 = [],",
"tetrad.pair_41]} def visualize(self, prefix: str, suffix: str): fasta = tempfile.NamedTemporaryFile('w+', suffix='.fasta') fasta.write(f'>{prefix}-{suffix}\\n') fasta.write(self.analysis.sequence)",
"https://doi.org/10.1002/chem.200701255 :return: Classification according to Webba da Silva or n/a \"\"\" # without",
"self.line1, self.line2, self.shifts = self.__generate_twoline_dotbracket() self.ions = self.__find_ions() self.__assign_ions_to_tetrads() def __find_tetrads(self, no_reorder=False) ->",
"quadruplexes def __filter_tetrad_pairs(self, tetrads: List[Tetrad]) -> List[TetradPair]: chains = set() for tetrad in",
"Tuple[Dict[Tetrad, List[Atom3D]], Dict[Tuple[Tetrad, Residue3D], List[Atom3D]]]: if len(self.tetrads) == 0: return {}, {} ions_channel",
"nt_first: Residue3D, nt_last: Residue3D) -> Optional[LoopType]: tetrad_with_first = self.__find_tetrad_with_nt(nt_first) tetrad_with_last = self.__find_tetrad_with_nt(nt_last) if",
"= v1 / numpy.linalg.norm(v1) v2 = nt2_1.find_atom(\"C1'\").coordinates() - nt2_2.find_atom(\"C1'\").coordinates() v2 = v2 /",
"will create a 4-letter string made of 's' for syn or 'a' for",
"'11', 'dpd': '12', 'ldp': '13' } fingerprint = ''.join([loop.loop_type.value[0] for loop in self.loops])",
"'([{<' + string.ascii_uppercase closing = ')]}>' + string.ascii_lowercase dotbracket = dict() for pair,",
"self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() # ONZ and da",
"2, 3) ni, nj, nk, nl = map(lambda nt: nt.index, self.nucleotides) indices =",
"nt.index, self.tetrad2_nts_best_order)) # count directions 5' -> 3' as +1 or -1 counter",
"key=lambda t: (len(graph[t]), t.planarity_deviation), reverse=True) if len(graph[candidates[0]]) > 0: tetrads.remove(candidates[0]) else: break return",
"return builder @dataclass class Helix: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D quadruplexes: List[Quadruplex]",
"\"INFO\")) @dataclass(order=True) class Tetrad: @staticmethod def is_valid(nt1: Residue3D, nt2: Residue3D, nt3: Residue3D, nt4:",
">= (4 - self.stacking_mismatch): helix_tetrads.append(tj) helix_tetrad_pairs.append(tp) else: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) helix_tetrads = [ti,",
"self.analysis.structure3d.residues shifts = self.analysis.shifts helix = tempfile.NamedTemporaryFile('w+', suffix='.helix') helix.write(f'#{len(self.analysis.sequence) + 1}\\n') helix.write('i\\tj\\tlength\\tvalue\\n') for",
"return f' {self.loop_type.value if self.loop_type else \"n/a\"} ' \\ f'{\", \".join(map(lambda nt: nt.full_name,",
"= self.base_pair_dict[(l, i)] tetrads.append(Tetrad(i, j, k, l, pair_12, pair_23, pair_34, pair_41)) # build",
"mapped to fingerprints gba_classes = { 'aass': GbaTetradClassification.Ia, 'ssaa': GbaTetradClassification.Ib, 'asas': GbaTetradClassification.IIa, 'sasa':",
"helix_tetrads = [] helix_tetrad_pairs = [] for tp in self.tetrad_pairs: ti, tj =",
"self.tetrad_pairs)) def __str__(self): builder = '' if len(self.tetrads) > 1: builder += f'n4-helix",
"BasePair3D pair_41: BasePair3D onz: ONZ = field(init=False) gba_class: Optional[GbaTetradClassification] = field(init=False) planarity_deviation: float",
"for tp in self.tetrad_pairs]) direction, support = counter.most_common()[0] if support != len(self.tetrad_pairs): direction",
"the loop between {nt_first} and {nt_last}') return None def __find_tetrad_with_nt(self, nt: Residue3D) ->",
"(stacked[ti.nt1], stacked[ti.nt2], stacked[ti.nt3], stacked[ti.nt4]) tj.reorder_to_match_other_tetrad(order) return tetrad_pairs def __find_helices(self): helices = [] helix_tetrads",
"(chain_order.index(c1) - chain_order.index(c2)) ** 2 return sum_sq def __find_ions(self) -> List[Atom3D]: metal_atom_names =",
"\\ f'{self.__ions_outside_str()}\\n' def chains(self) -> Set[str]: return set([nt.chain for nt in self.nucleotides]) def",
"self.__find_helices() if not self.no_reorder: self.__find_best_chain_order() self.sequence, self.line1, self.line2, self.shifts = self.__generate_twoline_dotbracket() self.ions =",
"= field(init=False) rise: float = field(init=False) twist: float = field(init=False) def __post_init__(self): self.tetrad2_nts_best_order",
"self.__find_tetrad_with_nt(nt_last) if tetrad_with_first is None or tetrad_with_last is None: logging.warning(f'Failed to classify the",
"List[TetradPair]: tetrads = list(self.tetrads) best_score = 0 best_order = tetrads for ti in",
"1 + shifts[x], nucleotides.index(y) + 1 + shifts[y] helix.write(f'{x}\\t{y}\\t1\\t8\\n') helix.flush() return helix class",
"last nt of a loop is in the same tetrad sign = self.__detect_loop_sign(nt_first,",
"nt: nt.index, self.nucleotides) indices = sorted((ni, nj, nk, nl)) ni, nj, nk, nl",
"@dataclass class Tract: nucleotides: List[Residue3D] def __str__(self): return f' {\", \".join(map(lambda nt: nt.full_name,",
"!= len(self.tetrad_pairs): direction = 'h' counter = Counter([t.onz.value[1] for t in self.tetrads]) plus_minus,",
"Structure2D, structure3d: Structure3D): self.pairs: List[BasePair3D] = structure3d.base_pairs(structure2d) self.graph: Dict[Residue3D, List[Residue3D]] = structure3d.base_pair_graph(structure2d) self.pair_dict:",
"in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) sequence, line1, shifts = self.__elimination_conflicts(layer1) _, line2,",
"return Analysis(structure2d, structure3d, strict, no_reorder, stacking_mismatch) def has_tetrad(structure2d: Structure2D, structure3d: Structure3D) -> bool:",
"ion in Ion]) ions = [] used = set() for residue in self.structure3d.residues:",
"residue: residue.outermost_atom, self.nucleotides)) + \\ list(map(lambda residue: residue.innermost_atom, self.nucleotides)) def __ions_channel_str(self) -> str:",
"self.__detect_loop_sign(nt_first, nt, tetrad_with_first) if sign is not None: return LoopType.from_value(f'propeller{sign}') logging.warning(f'Failed to classify",
"math import os import string import subprocess import tempfile from collections import defaultdict,",
"atom.coordinates()) if distance < min_distance: min_distance = distance min_tetrad = tetrad min_nt =",
"# all in the same direction return Direction.parallel elif count == 2: #",
"self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif order ==",
"ions_outside.items(): tetrad, residue = pair tetrad.ions_outside[residue] = ions def __generate_twoline_dotbracket(self) -> Tuple[str, str,",
"ONZ.O_MINUS: 2, ONZ.N_PLUS: 3, ONZ.N_MINUS: 4, ONZ.Z_PLUS: 5, ONZ.Z_MINUS: 6} nucleotides = self.analysis.structure3d.residues",
"l in filter(lambda x: x not in (i, j, k) and x in",
"chain = None for nt in sorted(filter(lambda nt: nt.is_nucleotide, self.structure3d.residues), key=lambda nt: nt.index):",
"earlier in lexicographical sense if permutation < best_permutation: best_permutation = permutation final_order.extend(best_permutation) if",
"tetrad.ions_channel = ions for pair, ions in ions_outside.items(): tetrad, residue = pair tetrad.ions_outside[residue]",
"'ppp': '1', 'ppl': '2', 'plp': '3', 'lpp': '4', 'pdp': '5', 'lll': '6', 'llp':",
"(ti, tj) in itertools.combinations(tetrads, 2): if not ti.is_disjoint(tj): graph[ti].append(tj) graph[tj].append(ti) # remove tetrad",
"nt2.chain and abs(nt1.index - nt2.index) == 1 tetrad_scores = defaultdict(dict) for ti, tj",
"+ string.ascii_uppercase closing = ')]}>' + string.ascii_lowercase dotbracket = dict() for pair, order",
"is not None: gbas.add(gba.value[:-1]) # discard 'a' or 'b' subvariant roman_numerals = {'I':",
"= field(init=False) shifts: Dict[Residue3D, int] = field(init=False) def __post_init__(self): self.base_pairs = self.structure3d.base_pairs(self.structure2d) self.base_pair_graph",
"t: (len(graph[t]), t.planarity_deviation), reverse=True) if len(graph[candidates[0]]) > 0: tetrads.remove(candidates[0]) else: break return sorted(tetrads,",
"def __detect_loop_type(self, nt_first: Residue3D, nt_last: Residue3D) -> Optional[LoopType]: tetrad_with_first = self.__find_tetrad_with_nt(nt_first) tetrad_with_last =",
"qi.update(qj) del candidates[j] changed = True break candidates = sorted(candidates, key=lambda x: len(x),",
"nk, nl) if order == (1, 2, 3): return ONZ.O_PLUS elif order ==",
"__str__(self): return f' direction={self.direction.value} rise={round(self.rise, 2)} twist={round(self.twist, 2)}\\n' @dataclass class Tract: nucleotides: List[Residue3D]",
"None: logging.warning(f'Failed to classify the loop between {nt_first} and {nt_last}') return None if",
"nt3: Residue3D nt4: Residue3D pair_12: BasePair3D pair_23: BasePair3D pair_34: BasePair3D pair_41: BasePair3D onz:",
"self.quadruplexes: builder += str(quadruplex) elif len(self.tetrads) == 1: builder += 'single tetrad without",
"continue min_distance = math.inf min_tetrad = self.tetrads[0] min_nt = min_tetrad.nt1 for tetrad in",
"-> tempfile.NamedTemporaryFile(): onz_value = {ONZ.O_PLUS: 1, ONZ.O_MINUS: 2, ONZ.N_PLUS: 3, ONZ.N_MINUS: 4, ONZ.Z_PLUS:",
"return list(map(lambda x: GbaQuadruplexClassification[x], gbas)) def __find_tracts(self) -> List[Tract]: tracts = [[self.tetrads[0].nt1], [self.tetrads[0].nt2],",
"= nucleotides.index(x) + 1 + shifts[x], nucleotides.index(y) + 1 + shifts[y] helix.write(f'{x}\\t{y}\\t1\\t8\\n') helix.flush()",
"self.pair_12.reverse(), self.pair_41.reverse() elif order == (self.nt3, self.nt2, self.nt1, self.nt4): self.pair_12, self.pair_23, self.pair_34, self.pair_41",
"(i, j, k) and x in self.graph[i], self.graph[k]): if Tetrad.is_valid(i, j, k, l,",
"if pair.score() < pair.reverse().score(): return '+' return '-' return None def __classify_by_loops(self) ->",
"# build graph of tetrads while tetrads: graph = defaultdict(list) for (ti, tj)",
"Dict[Residue3D, List[Residue3D]] = field(init=False) tetrads: List[Tetrad] = field(init=False) tetrad_scores: Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple,",
"Dict[Residue3D, int]]: orders = dict() order = 0 queue = list(pairs) removed =",
"self.ions: min_distance = math.inf min_tetrad = self.tetrads[0] for tetrad in self.tetrads: distance =",
"\"\"\" # without all nucleotides having a valid syn/anti, this classification is impossible",
"{\" \".join(permutation)} {\" \".join(map(lambda c: c.value, classifications))}') onz_score = sum(c.score() for c in",
"+ \\ list(map(lambda residue: residue.innermost_atom, self.nucleotides)) def __ions_channel_str(self) -> str: if self.ions_channel: return",
"for coord in coords) zs = (coord[2] for coord in coords) return numpy.array((sum(xs)",
"nt.one_letter_name structure += dotbracket.get(nt, '.') shifts[nt] = shift_value chain = nt.chain return sequence,",
"bool, stacking_mismatch: int) -> Analysis: return Analysis(structure2d, structure3d, strict, no_reorder, stacking_mismatch) def has_tetrad(structure2d:",
"AnalysisSimple: def __init__(self, structure2d: Structure2D, structure3d: Structure3D): self.pairs: List[BasePair3D] = structure3d.base_pairs(structure2d) self.graph: Dict[Residue3D,",
"field(init=False) tracts: List[Tract] = field(init=False) loops: List[Loop] = field(init=False) loop_class: Optional[LoopClassification] = field(init=False)",
"for t in h.tetrads] logging.debug(f'Selected chain order: {\" \".join(final_order)} ' f'{\" \".join(map(lambda onz:",
"__chain_order_score(self, chain_order: Tuple[str, ...]) -> int: chain_pairs = [] for h in self.helices:",
"( self.stacked[self.tetrad1.nt1], self.stacked[self.tetrad1.nt2], self.stacked[self.tetrad1.nt3], self.stacked[self.tetrad1.nt4] ) self.direction = self.__determine_direction() self.rise = self.__calculate_rise() self.twist",
"onz = self.onz_dict[pair] helix.write(f'{x}\\t{y}\\t1\\t{onz_value.get(onz, 7)}\\n') if canonical: for pair in canonical: x, y",
"tetrads: chains.update(tetrad.chains()) def check_tetrad(t: Tetrad) -> bool: return not t.chains().isdisjoint(chains) def check_pair(tp: TetradPair)",
"[ti] candidates = set(self.tetrads) - {ti} while candidates: tj = max([tj for tj",
"loop_type)) return loops def __detect_loop_type(self, nt_first: Residue3D, nt_last: Residue3D) -> Optional[LoopType]: tetrad_with_first =",
"= sorted((ni, nj, nk, nl)) ni, nj, nk, nl = (indices.index(x) for x",
"== (self.nt2, self.nt3, self.nt4, self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41,",
"order.append(tj) candidates.remove(tj) ti = tj if score > best_score: best_score = score best_order",
"t.nt2.chain, t.nt3.chain, t.nt4.chain])) candidates = [set(c) for c in candidates] changed = True",
"Dict[Residue3D, List[Atom3D]] = field(default_factory=dict) def __post_init__(self): self.reorder_to_match_5p_3p() self.planarity_deviation = self.__calculate_planarity_deviation() def reorder_to_match_5p_3p(self): #",
"-> List[List[str]]: candidates = set() for h in self.helices: for t in h.tetrads:",
"- nt2.index) == 1 tetrad_scores = defaultdict(dict) for ti, tj in itertools.combinations(self.tetrads, 2):",
"else -1 for i, j in zip(indices1, indices2)) direction, count = counter.most_common()[0] if",
"(indices.index(x) for x in (ni, nj, nk, nl)) while ni != 0: ni,",
"\\ f'{self.onz.value} {self.gba_class.value} ' \\ f'planarity={round(self.planarity_deviation, 2)} ' \\ f'{self.__ions_channel_str()} ' \\ f'{self.__ions_outside_str()}\\n'",
"remove one which has the worst planarity deviation candidates = sorted(tetrads, key=lambda t:",
"for ion in Ion]) ions = [] used = set() for residue in",
"len(coords))) def eltetrado(structure2d: Structure2D, structure3d: Structure3D, strict: bool, no_reorder: bool, stacking_mismatch: int) ->",
"self.tracts: if nprev in tract.nucleotides and ncur in tract.nucleotides: break else: nts =",
"tract.nucleotides: break else: nts = list(filter(lambda nt: nprev.index < nt.index < ncur.index, self.structure3d.residues))",
"pair_12, pair_23, pair_34, pair_41)) # build graph of tetrads while tetrads: graph =",
"lw_j.name[2]: return False return True nt1: Residue3D nt2: Residue3D nt3: Residue3D nt4: Residue3D",
"= Counter([tp.direction.value[0] for tp in self.tetrad_pairs]) direction, support = counter.most_common()[0] if support !=",
"i in range(4)} stacked.update({v: k for k, v in stacked.items()}) tetrad_pairs.append(TetradPair(ti, tj, stacked))",
"score >= (4 - self.stacking_mismatch): helix_tetrads.append(tj) helix_tetrad_pairs.append(tp) else: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) helix_tetrads =",
"structure3d, strict, no_reorder, stacking_mismatch) def has_tetrad(structure2d: Structure2D, structure3d: Structure3D) -> bool: structure =",
"def is_valid(nt1: Residue3D, nt2: Residue3D, nt3: Residue3D, nt4: Residue3D, pair_dictionary: Dict[Tuple[Residue3D, Residue3D], BasePair3D])",
"tetrad_with_first is None or tetrad_with_last is None: logging.warning(f'Failed to classify the loop between",
"score_sequential, score_stacking best_order = nts2 if best_score == 4: break tetrad_scores[ti][tj] = (best_score,",
"self.tetrad2.outer_and_inner_atoms() return numpy.linalg.norm(center_of_mass(t1) - center_of_mass(t2)) def __calculate_twist(self) -> float: nt1_1, nt1_2, _, _",
"itertools.combinations(tetrads, 2): if not ti.is_disjoint(tj): graph[ti].append(tj) graph[tj].append(ti) # remove tetrad which conflicts the",
"coords) ys = (coord[1] for coord in coords) zs = (coord[2] for coord",
"in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]} def visualize(self, prefix: str, suffix: str): fasta =",
"reorder: {\" \".join(permutation)} {\" \".join(map(lambda c: c.value, classifications))}') onz_score = sum(c.score() for c",
"x: (len(x[1]), x[0].nt1)) removed.append(pair) queue.remove(pair) else: orders.update({pair: order for pair in queue}) queue,",
"sequence: str = field(init=False) line1: str = field(init=False) line2: str = field(init=False) shifts:",
"GbaTetradClassification.IIIb, 'aaas': GbaTetradClassification.IVa, 'sssa': GbaTetradClassification.IVb, 'aasa': GbaTetradClassification.Va, 'ssas': GbaTetradClassification.Vb, 'assa': GbaTetradClassification.VIa, 'saas': GbaTetradClassification.VIb,",
"tempfile.NamedTemporaryFile(): onz_value = {ONZ.O_PLUS: 1, ONZ.O_MINUS: 2, ONZ.N_PLUS: 3, ONZ.N_MINUS: 4, ONZ.Z_PLUS: 5,",
"def reorder_to_match_5p_3p(self): # transform into (0, 1, 2, 3) ni, nj, nk, nl",
"== tetrad_with_last: # diagonal or laterals happen when first and last nt of",
"!= 0: ni, nj, nk, nl = nl, ni, nj, nk order =",
"is required to recalculate ONZ tp.tetrad2.reorder_to_match_other_tetrad(order) def __chain_order_score(self, chain_order: Tuple[str, ...]) -> int:",
"n4 = tj.nucleotides viable_permutations = [(n1, n2, n3, n4), (n2, n3, n4, n1),",
"lw3)): if lw_i.name[1] == lw_j.name[2]: return False return True nt1: Residue3D nt2: Residue3D",
"(nt.index for nt in self.nucleotides) indices = sorted((ni, nj, nk, nl)) ni, nj,",
"-> bool: return nt2 in self.stacking_graph.get(nt1, []) def is_next_sequentially(nt1: Residue3D, nt2: Residue3D) ->",
"else 0 for i in range(4)] score_sequential = [1 if is_next_sequentially(nts1[i], nts2[i]) else",
"List[BasePair3D] = field(init=False) base_pair_graph: Dict[Residue3D, List[Residue3D]] = field(init=False) base_pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] =",
"candidates.remove(tj) ti = tj if score > best_score: best_score = score best_order =",
"def visualize(self, prefix: str, suffix: str): fasta = tempfile.NamedTemporaryFile('w+', suffix='.fasta') fasta.write(f'>{prefix}-{suffix}\\n') fasta.write(self.analysis.sequence) fasta.flush()",
"def is_disjoint(self, other) -> bool: return frozenset(self.nucleotides).isdisjoint(frozenset(other.nucleotides)) def center(self) -> numpy.ndarray: return center_of_mass(self.outer_and_inner_atoms())",
"dataclasses import dataclass, field from typing import Dict, Iterable, List, Tuple, Optional, Set",
"self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23 elif order == (self.nt4, self.nt1, self.nt2,",
"self.tetrad_scores[ti][tk][0]) score += self.tetrad_scores[ti][tj][0] order.append(tj) candidates.remove(tj) ti = tj if score > best_score:",
"y = nucleotides.index(x) + 1 + shifts[x], nucleotides.index(y) + 1 + shifts[y] helix.write(f'{x}\\t{y}\\t1\\t8\\n')",
"tetrad_pair.tetrad2_nts_best_order[2], tetrad_pair.tetrad1.nt4: tetrad_pair.tetrad2_nts_best_order[3], } for i in range(4): tracts[i].append(nt_dict[tracts[i][-1]]) return [Tract(nts) for nts",
"{self.loop_class.value} {self.loop_class.loop_progression()}' else: builder += f' n/a' builder += f' quadruplex with {len(self.tetrads)}",
"-> Optional[ONZM]: if len(self.tetrads) == 1: return None if any([t.onz is None for",
"= structure3d.base_pair_graph(structure2d) self.pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = structure3d.base_pair_dict(structure2d) def has_tetrads(self): tetrads = set()",
"= field(init=False) base_pair_graph: Dict[Residue3D, List[Residue3D]] = field(init=False) base_pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = field(init=False)",
"and pair.nt2 == first: if pair.score() < pair.reverse().score(): return '+' return '-' return",
"if tract_with_last is not None: # search along the tract to check what",
"self.nt3, self.nt4 = self.nt4, self.nt1, self.nt2, self.nt3 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41,",
"List[Residue3D] def __str__(self): return f' {\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass class Loop:",
"counter = Counter(1 if j - i > 0 else -1 for i,",
"itertools.combinations(queue, 2): if pi.conflicts_with(pj): conflicts[pi].append(pj) conflicts[pj].append(pi) if conflicts: pair, _ = max(conflicts.items(), key=lambda",
"pair, ions in ions_outside.items(): tetrad, residue = pair tetrad.ions_outside[residue] = ions def __generate_twoline_dotbracket(self)",
"x not in (i, j), self.graph[j]): for l in filter(lambda x: x not",
"ions in ions_outside.items(): tetrad, residue = pair tetrad.ions_outside[residue] = ions def __generate_twoline_dotbracket(self) ->",
"dotbracket = dict() for pair, order in orders.items(): nt1, nt2 = sorted([pair.nt1, pair.nt2])",
"self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23 elif order ==",
"tj if score > best_score: best_score = score best_order = order if best_score",
"import os import string import subprocess import tempfile from collections import defaultdict, Counter",
"elif count == 2: # two in +, one in - direction return",
"self.onzm is not None else \"R\"}' builder += f' {\",\".join(map(lambda gba: gba.value, self.gba_classes))}'",
"if not all([nt.chi_class in (GlycosidicBond.syn, GlycosidicBond.anti) for nt in self.nucleotides]): return None #",
"1: return None if any([t.onz is None for t in self.tetrads]): return None",
"def center(self) -> numpy.ndarray: return center_of_mass(self.outer_and_inner_atoms()) def outer_and_inner_atoms(self) -> List[Atom3D]: return list(map(lambda residue:",
"= {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5, 'VI': 6,",
"'pdl': '10', 'ldl': '11', 'dpd': '12', 'ldp': '13' } fingerprint = ''.join([loop.loop_type.value[0] for",
"Counter from dataclasses import dataclass, field from typing import Dict, Iterable, List, Tuple,",
"{nj} {nk} {nl}') def __classify_by_gba(self) -> Optional[GbaTetradClassification]: \"\"\" See: <NAME>. (2007). Geometric Formalism",
"n3, n2, n1), (n3, n2, n1, n4), (n2, n1, n4, n3)] for nts2",
"self.tetrads[0] for tetrad in self.tetrads: distance = numpy.linalg.norm(ion.coordinates() - tetrad.center()) if distance <",
"_ = max(conflicts.items(), key=lambda x: (len(x[1]), x[0].nt1)) removed.append(pair) queue.remove(pair) else: orders.update({pair: order for",
"for k, v in stacked.items()}) tetrad_pairs.append(TetradPair(ti, tj, stacked)) order = (stacked[ti.nt1], stacked[ti.nt2], stacked[ti.nt3],",
"nt: Residue3D) -> Optional[Tetrad]: for tetrad in self.tetrads: if nt in tetrad.nucleotides: return",
"Optional[LoopClassification]: if len(self.loops) != 3 or any([loop.loop_type is None for loop in self.loops]):",
"lw1), (lw3, lw2), (lw4, lw3)): if lw_i.name[1] == lw_j.name[2]: return False return True",
"= self.structure3d.base_pair_graph(self.structure2d, self.strict) self.base_pair_dict = self.structure3d.base_pair_dict(self.structure2d, self.strict) self.stacking_graph = self.structure3d.stacking_graph(self.structure2d) self.tetrads = self.__find_tetrads(self.no_reorder)",
"0 queue = list(pairs) removed = [] while queue: conflicts = defaultdict(list) for",
"dataclass, field from typing import Dict, Iterable, List, Tuple, Optional, Set import numpy",
"List[TetradPair] structure3d: Structure3D quadruplexes: List[Quadruplex] = field(init=False) def __post_init__(self): self.quadruplexes = self.__find_quadruplexes() def",
"None if tetrad_with_first == tetrad_with_last: # diagonal or laterals happen when first and",
"viable_permutations = [(n1, n2, n3, n4), (n2, n3, n4, n1), (n3, n4, n1,",
"= sum(score_sequential) score_stacking = sum(score_stacking) if (score, score_sequential, score_stacking) > (best_score, best_score_sequential, best_score_stacking):",
"f'{self.__ions_outside_str()}\\n' def chains(self) -> Set[str]: return set([nt.chain for nt in self.nucleotides]) def is_disjoint(self,",
"for i in self.graph: for j in filter(lambda x: x != i, self.graph[i]):",
"i in self.base_pair_graph[x], self.base_pair_graph[k]): if Tetrad.is_valid(i, j, k, l, self.base_pair_dict): pair_12 = self.base_pair_dict[(i,",
"Structure2D, BasePair3D, Residue3D, GlycosidicBond, ONZ, \\ GbaTetradClassification, Ion, Direction, LoopType, ONZM, GbaQuadruplexClassification, LoopClassification",
"nt: nt.full_name, self.nucleotides))}' @dataclass class Loop: nucleotides: List[Residue3D] loop_type: Optional[LoopType] def __str__(self): return",
"- center_of_mass(inner)) @property def nucleotides(self) -> Tuple[Residue3D, Residue3D, Residue3D, Residue3D]: return self.nt1, self.nt2,",
"in lexicographical sense if permutation < best_permutation: best_permutation = permutation final_order.extend(best_permutation) if len(final_order)",
"for ti in tetrads: score = 0 order = [ti] candidates = set(self.tetrads)",
"nt3)].lw lw3 = pair_dictionary[(nt3, nt4)].lw lw4 = pair_dictionary[(nt4, nt1)].lw for lw_i, lw_j in",
"def __find_loops(self) -> List[Loop]: if len(self.tetrads) == 1: return [] loops = []",
"logging.error(f'Failed to prepare visualization, reason:\\n {run.stderr.decode()}') def __to_helix(self, layer: List[BasePair3D], canonical: Optional[List[BasePair3D]] =",
"support != len(self.tetrads): plus_minus = '*' return ONZM.from_value(f'{onz}{direction}{plus_minus}') def __classify_by_gba(self) -> List[GbaQuadruplexClassification]: gbas",
"tetrad: Tetrad) -> Optional[str]: for pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]: # main",
"__post_init__(self): self.onzm = self.__classify_onzm() self.gba_classes = self.__classify_by_gba() self.tracts = self.__find_tracts() self.loops = self.__find_loops()",
"for t in self.tetrads]): return None counter = Counter([t.onz.value[0] for t in self.tetrads])",
"score = self.tetrad_scores[helix_tetrads[-1]][tj][0] if score >= (4 - self.stacking_mismatch): helix_tetrads.append(tj) helix_tetrad_pairs.append(tp) else: helices.append(Helix(helix_tetrads,",
"in classifications) chain_order_score = self.__chain_order_score(permutation) score = (onz_score, chain_order_score) if score < best_score:",
"= (indices.index(x) for x in (ni, nj, nk, nl)) nmin = min(ni, nj,",
"in groups], key=lambda x: x[0]) def __reorder_chains(self, chain_order: Iterable[str]): i = 1 for",
"self.analysis.canonical() if self.complete2d else []) helix2 = self.__to_helix(layer2) currdir = os.path.dirname(os.path.realpath(__file__)) output_pdf =",
"tj in itertools.combinations(self.tetrads, 2): nts1 = ti.nucleotides best_score = 0 best_score_sequential = 0",
"tetrads = list(self.tetrads) best_score = 0 best_order = tetrads for ti in tetrads:",
"return True nt1: Residue3D nt2: Residue3D nt3: Residue3D nt4: Residue3D pair_12: BasePair3D pair_23:",
"= [[self.tetrads[0].nt1], [self.tetrads[0].nt2], [self.tetrads[0].nt3], [self.tetrads[0].nt4]] if len(self.tetrad_pairs) > 0: for tetrad_pair in self.tetrad_pairs:",
"key=lambda x: x[0]) def __reorder_chains(self, chain_order: Iterable[str]): i = 1 for chain in",
"self.pair_41 = self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse() elif order == (self.nt2, self.nt1, self.nt4, self.nt3):",
"class TetradPair: tetrad1: Tetrad tetrad2: Tetrad stacked: Dict[Residue3D, Residue3D] tetrad2_nts_best_order: Tuple[Residue3D, Residue3D, Residue3D,",
"ions in ions_channel.items(): tetrad.ions_channel = ions for pair, ions in ions_outside.items(): tetrad, residue",
"n1, n2), (n4, n1, n2, n3), (n1, n4, n3, n2), (n4, n3, n2,",
"stacking_mismatch): nts1, nts2 = self.tetrad_scores[ti][tj][1:] stacked = {nts1[i]: nts2[i] for i in range(4)}",
"tetrads.append(Tetrad(i, j, k, l, pair_12, pair_23, pair_34, pair_41)) # build graph of tetrads",
"= self.pair_34, self.pair_41, self.pair_12, self.pair_23 elif order == (self.nt4, self.nt1, self.nt2, self.nt3): self.pair_12,",
"self.tetrads: gba = t.gba_class if gba is not None: gbas.add(gba.value[:-1]) # discard 'a'",
"(len(graph[t]), t.planarity_deviation), reverse=True) if len(graph[candidates[0]]) > 0: tetrads.remove(candidates[0]) else: break return sorted(tetrads, key=lambda",
"subprocess.run([os.path.join(currdir, 'quadraw.R'), fasta.name, helix1.name, helix2.name, output_pdf], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if run.returncode == 0: print('\\nPlot:',",
"-> List[BasePair3D]: return [base_pair for base_pair in self.base_pairs if base_pair.is_canonical()] @dataclass class Visualizer:",
"class Tetrad: @staticmethod def is_valid(nt1: Residue3D, nt2: Residue3D, nt3: Residue3D, nt4: Residue3D, pair_dictionary:",
"'VI': 6, 'VII': 7, 'VIII': 8} gbas = sorted(gbas, key=lambda gba: roman_numerals.get(gba, 100))",
"def __init__(self, structure2d: Structure2D, structure3d: Structure3D): self.pairs: List[BasePair3D] = structure3d.base_pairs(structure2d) self.graph: Dict[Residue3D, List[Residue3D]]",
"__post_init__(self): self.tetrad2_nts_best_order = ( self.stacked[self.tetrad1.nt1], self.stacked[self.tetrad1.nt2], self.stacked[self.tetrad1.nt3], self.stacked[self.tetrad1.nt4] ) self.direction = self.__determine_direction() self.rise",
"and {nt_last}') return None def __find_tetrad_with_nt(self, nt: Residue3D) -> Optional[Tetrad]: for tetrad in",
"tetrad_scores def __find_tetrad_pairs(self, stacking_mismatch: int) -> List[TetradPair]: tetrads = list(self.tetrads) best_score = 0",
"= self.analysis.shifts helix = tempfile.NamedTemporaryFile('w+', suffix='.helix') helix.write(f'#{len(self.analysis.sequence) + 1}\\n') helix.write('i\\tj\\tlength\\tvalue\\n') for pair in",
"chain_order: chain_pairs.append([c1, c2]) sum_sq = 0 for c1, c2 in chain_pairs: sum_sq +=",
"helices: List[Helix] = field(init=False) ions: List[Atom3D] = field(init=False) sequence: str = field(init=False) line1:",
"range(4)]) score_sequential = sum(score_sequential) score_stacking = sum(score_stacking) if (score, score_sequential, score_stacking) > (best_score,",
"{self.loop_class.loop_progression()}' else: builder += f' n/a' builder += f' quadruplex with {len(self.tetrads)} tetrads\\n'",
"min_distance = math.inf min_tetrad = self.tetrads[0] for tetrad in self.tetrads: distance = numpy.linalg.norm(ion.coordinates()",
"__chain_order(self) -> List[str]: only_nucleic_acids = filter(lambda nt: nt.is_nucleotide, self.structure3d.residues) return list({nt.chain: 0 for",
"for tetrad in [self.tetrad_pairs[0].tetrad1] + [tetrad_pair.tetrad2 for tetrad_pair in self.tetrad_pairs]: if tetrads: if",
"return None def __find_tetrad_with_nt(self, nt: Residue3D) -> Optional[Tetrad]: for tetrad in self.tetrads: if",
"list(map(lambda x: GbaQuadruplexClassification[x], gbas)) def __find_tracts(self) -> List[Tract]: tracts = [[self.tetrads[0].nt1], [self.tetrads[0].nt2], [self.tetrads[0].nt3],",
"= 1 for chain in chain_order: for nt in self.structure3d.residues: if nt.chain ==",
"{self.pair_41.lw.value} ' \\ f'{self.onz.value} {self.gba_class.value} ' \\ f'planarity={round(self.planarity_deviation, 2)} ' \\ f'{self.__ions_channel_str()} '",
"Optional[GbaTetradClassification] = field(init=False) planarity_deviation: float = field(init=False) ions_channel: List[Atom3D] = field(default_factory=list) ions_outside: Dict[Residue3D,",
"elif order == (2, 3, 1): return ONZ.N_MINUS elif order == (2, 1,",
"','.join([atom.atomName for atom in self.ions_channel]) return '' def __ions_outside_str(self) -> str: if self.ions_outside:",
"structure2d: Structure2D structure3d: Structure3D strict: bool no_reorder: bool stacking_mismatch: int base_pairs: List[BasePair3D] =",
"__hash__(self): return hash(frozenset([self.nt1, self.nt2, self.nt3, self.nt4])) def __str__(self): return f' ' \\ f'{self.nt1.full_name}",
"self.base_pair_graph = self.structure3d.base_pair_graph(self.structure2d, self.strict) self.base_pair_dict = self.structure3d.base_pair_dict(self.structure2d, self.strict) self.stacking_graph = self.structure3d.stacking_graph(self.structure2d) self.tetrads =",
"j -> k -> l # ^--------------^ tetrads = [] for i in",
"tetrad.center()) if distance < min_distance: min_distance = distance min_tetrad = tetrad # TODO:",
"first: Residue3D, last: Residue3D, tetrad: Tetrad) -> Optional[str]: for pair in [tetrad.pair_12, tetrad.pair_23,",
"ions.append(atom) used.add(coordinates) return ions def __assign_ions_to_tetrads(self) \\ -> Tuple[Dict[Tetrad, List[Atom3D]], Dict[Tuple[Tetrad, Residue3D], List[Atom3D]]]:",
"p.nt1.chain c2 = p.nt2.chain if c1 != c2 and c1 in chain_order and",
"from eltetrado.model import Atom3D, Structure3D, Structure2D, BasePair3D, Residue3D, GlycosidicBond, ONZ, \\ GbaTetradClassification, Ion,",
"lexicographical sense if permutation < best_permutation: best_permutation = permutation final_order.extend(best_permutation) if len(final_order) >",
"nucleotides.index(y) + 1 + shifts[y] onz = self.onz_dict[pair] helix.write(f'{x}\\t{y}\\t1\\t{onz_value.get(onz, 7)}\\n') if canonical: for",
"changed = False for i, j in itertools.combinations(range(len(candidates)), 2): qi, qj = candidates[i],",
"{[nt.chi_class for nt in self.nucleotides]}') return None return gba_classes[fingerprint] def __calculate_planarity_deviation(self) -> float:",
"not in (i, j, k) and i in self.base_pair_graph[x], self.base_pair_graph[k]): if Tetrad.is_valid(i, j,",
"self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif order == (self.nt3, self.nt4,",
"List[Atom3D] = field(init=False) sequence: str = field(init=False) line1: str = field(init=False) line2: str",
"nl) if order == (1, 2, 3): return ONZ.O_PLUS elif order == (3,",
"in gba_classes: logging.error(f'Impossible combination of syn/anti: {[nt.chi_class for nt in self.nucleotides]}') return None",
"sum(zs) / len(coords))) def eltetrado(structure2d: Structure2D, structure3d: Structure3D, strict: bool, no_reorder: bool, stacking_mismatch:",
"DNA Quadruplex Folding. Chemistry - A European Journal, 13(35), 9738–9745. https://doi.org/10.1002/chem.200701255 :return: Classification",
"self.__detect_loop_type(nprev, ncur) loops.append(Loop(nts, loop_type)) return loops def __detect_loop_type(self, nt_first: Residue3D, nt_last: Residue3D) ->",
"self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34 elif order == (self.nt4, self.nt3, self.nt2,",
"pair.reverse().score(): return '-' return '+' # reverse check if pair.nt1 == last and",
"= score best_permutation = permutation elif score == best_score: # in case of",
"pair, _ = max(conflicts.items(), key=lambda x: (len(x[1]), x[0].nt1)) removed.append(pair) queue.remove(pair) else: orders.update({pair: order",
"bool: return not t.chains().isdisjoint(chains) def check_pair(tp: TetradPair) -> bool: return check_tetrad(tp.tetrad1) and check_tetrad(tp.tetrad2)",
"key=lambda nt: nt.index)}.keys()) def canonical(self) -> List[BasePair3D]: return [base_pair for base_pair in self.base_pairs",
"logging.warning(f'Failed to classify the loop between {nt_first} and {nt_last}') return None def __find_tetrad_with_nt(self,",
"output_pdf = f'{prefix}-{suffix}.pdf' run = subprocess.run([os.path.join(currdir, 'quadraw.R'), fasta.name, helix1.name, helix2.name, output_pdf], stdout=subprocess.PIPE, stderr=subprocess.PIPE)",
"def __find_tetrad_with_nt(self, nt: Residue3D) -> Optional[Tetrad]: for tetrad in self.tetrads: if nt in",
"self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23 else: self.nt1, self.nt2, self.nt3, self.nt4 =",
"for tetrad in self.tetrads for nt in tetrad.nucleotides], key=lambda nt: nt.index) for i",
"if support != len(self.tetrad_pairs): direction = 'h' counter = Counter([t.onz.value[1] for t in",
"def __ions_channel_str(self) -> str: if self.ions_channel: return 'ions_channel=' + ','.join([atom.atomName for atom in",
"break tetrad_scores[ti][tj] = (best_score, nts1, best_order) tetrad_scores[tj][ti] = (best_score, best_order, nts1) return tetrad_scores",
"= tetrad min_nt = nt # TODO: verify threshold of 3A between an",
"search along the tract to check what pairs with nt_first for nt in",
"min_tetrad = self.tetrads[0] min_nt = min_tetrad.nt1 for tetrad in self.tetrads: for nt in",
"class Visualizer: analysis: Analysis tetrads: List[Tetrad] complete2d: bool onz_dict: Dict[BasePair3D, ONZ] = field(init=False)",
"self.nt4 = self.nt1, self.nt4, self.nt3, self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(),",
"None: gbas.add(gba.value[:-1]) # discard 'a' or 'b' subvariant roman_numerals = {'I': 1, 'II':",
"queue: conflicts = defaultdict(list) for pi, pj in itertools.combinations(queue, 2): if pi.conflicts_with(pj): conflicts[pi].append(pj)",
"tetrad_pair in self.tetrad_pairs: builder += str(tetrad_pair) builder += str(tetrad_pair.tetrad2) if self.tracts: builder +=",
"n4, n3)] for nts2 in viable_permutations: score_stacking = [1 if is_next_by_stacking(nts1[i], nts2[i]) else",
"[atom.coordinates() for atom in atoms] xs = (coord[0] for coord in coords) ys",
"def __str__(self): builder = '' if len(self.tetrads) == 1: builder += ' single",
"helix_tetrad_pairs.append(tp) else: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) helix_tetrads = [ti, tj] helix_tetrad_pairs = [tp] if",
"= None) -> tempfile.NamedTemporaryFile(): onz_value = {ONZ.O_PLUS: 1, ONZ.O_MINUS: 2, ONZ.N_PLUS: 3, ONZ.N_MINUS:",
"c in classifications) chain_order_score = self.__chain_order_score(permutation) score = (onz_score, chain_order_score) if score <",
"tract_with_last is not None: # search along the tract to check what pairs",
"elif nmin == nj: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt2, self.nt3, self.nt4, self.nt1",
"return f' direction={self.direction.value} rise={round(self.rise, 2)} twist={round(self.twist, 2)}\\n' @dataclass class Tract: nucleotides: List[Residue3D] def",
"if self.tracts: builder += '\\n Tracts:\\n' for tract in self.tracts: builder += f'{tract}\\n'",
"self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse() elif order == (self.nt1,",
"defaultdict(dict) for ti, tj in itertools.combinations(self.tetrads, 2): nts1 = ti.nucleotides best_score = 0",
"0: for tetrad_pair in self.tetrad_pairs: nt_dict = { tetrad_pair.tetrad1.nt1: tetrad_pair.tetrad2_nts_best_order[0], tetrad_pair.tetrad1.nt2: tetrad_pair.tetrad2_nts_best_order[1], tetrad_pair.tetrad1.nt3:",
"self.tetrads for pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]} def visualize(self, prefix: str, suffix:",
"chains.update(tetrad.chains()) def check_tetrad(t: Tetrad) -> bool: return not t.chains().isdisjoint(chains) def check_pair(tp: TetradPair) ->",
"self.pair_34, self.pair_41 = self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse() elif order == (self.nt3, self.nt2, self.nt1,",
"tetrad_nucleotides[i - 1] ncur = tetrad_nucleotides[i] if ncur.index - nprev.index > 1 and",
"'III': 3, 'IV': 4, 'V': 5, 'VI': 6, 'VII': 7, 'VIII': 8} gbas",
"= t.gba_class if gba is not None: gbas.add(gba.value[:-1]) # discard 'a' or 'b'",
"continue groups.append(candidate) return sorted([sorted(group) for group in groups], key=lambda x: x[0]) def __reorder_chains(self,",
"- 1], best_order[i] score = self.tetrad_scores[ti][tj][0] if score >= (4 - stacking_mismatch): nts1,",
"Tetrad tetrad2: Tetrad stacked: Dict[Residue3D, Residue3D] tetrad2_nts_best_order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D] = field(init=False)",
"group in groups]): continue groups.append(candidate) return sorted([sorted(group) for group in groups], key=lambda x:",
"tk: self.tetrad_scores[ti][tk][0]) score += self.tetrad_scores[ti][tj][0] order.append(tj) candidates.remove(tj) ti = tj if score >",
"suffix='.fasta') fasta.write(f'>{prefix}-{suffix}\\n') fasta.write(self.analysis.sequence) fasta.flush() layer1, layer2 = [], [] for tetrad in self.tetrads:",
"3A between an ion and an atom if min_distance < 3.0: ions_outside[(min_tetrad, min_nt)].append(ion)",
"for lw_i, lw_j in ((lw1, lw4), (lw2, lw1), (lw3, lw2), (lw4, lw3)): if",
"-> bool: return check_tetrad(tp.tetrad1) and check_tetrad(tp.tetrad2) return list(filter(check_pair, self.tetrad_pairs)) def __str__(self): builder =",
"for residue, ions in self.ions_outside.items(): result.append(f'{residue.full_name}: [{\",\".join([ion.atomName for ion in ions])}]') return 'ions_outside='",
"def __classify_by_gba(self) -> List[GbaQuadruplexClassification]: gbas = set() for t in self.tetrads: gba =",
"if best_score == 4: break tetrad_scores[ti][tj] = (best_score, nts1, best_order) tetrad_scores[tj][ti] = (best_score,",
"builder += '\\n' return builder @dataclass class Helix: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d:",
"k, l, self.base_pair_dict): pair_12 = self.base_pair_dict[(i, j)] pair_23 = self.base_pair_dict[(j, k)] pair_34 =",
"center_of_mass(self.outer_and_inner_atoms()) def outer_and_inner_atoms(self) -> List[Atom3D]: return list(map(lambda residue: residue.outermost_atom, self.nucleotides)) + \\ list(map(lambda",
"return not t.chains().isdisjoint(chains) def check_pair(tp: TetradPair) -> bool: return check_tetrad(tp.tetrad1) and check_tetrad(tp.tetrad2) return",
"check_tetrad(t: Tetrad) -> bool: return not t.chains().isdisjoint(chains) def check_pair(tp: TetradPair) -> bool: return",
"'ssss': GbaTetradClassification.VIIIb } if fingerprint not in gba_classes: logging.error(f'Impossible combination of syn/anti: {[nt.chi_class",
"distance < min_distance: min_distance = distance min_tetrad = tetrad # TODO: verify threshold",
"for group in groups]): continue groups.append(candidate) return sorted([sorted(group) for group in groups], key=lambda",
"if len(self.loops) != 3 or any([loop.loop_type is None for loop in self.loops]): return",
"sign = self.__detect_loop_sign(nt_first, nt, tetrad_with_first) if sign is not None: return LoopType.from_value(f'propeller{sign}') logging.warning(f'Failed",
"sense if permutation < best_permutation: best_permutation = permutation final_order.extend(best_permutation) if len(final_order) > 1:",
"f' {\",\".join(map(lambda gba: gba.value, self.gba_classes))}' if self.loop_class: builder += f' {self.loop_class.value} {self.loop_class.loop_progression()}' else:",
"of syn/anti: {[nt.chi_class for nt in self.nucleotides]}') return None return gba_classes[fingerprint] def __calculate_planarity_deviation(self)",
"\\ -> Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]]: def is_next_by_stacking(nt1: Residue3D, nt2: Residue3D) ->",
"to classify the loop between {nt_first} and {nt_last}') return None def __find_tetrad_with_nt(self, nt:",
"permutation final_order.extend(best_permutation) if len(final_order) > 1: self.__reorder_chains(final_order) classifications = [t.onz for h in",
"to prepare visualization, reason:\\n {run.stderr.decode()}') def __to_helix(self, layer: List[BasePair3D], canonical: Optional[List[BasePair3D]] = None)",
"sorted(candidates, key=lambda x: len(x), reverse=True) groups = [] for candidate in candidates: if",
"'-' shift_value += 1 sequence += nt.one_letter_name structure += dotbracket.get(nt, '.') shifts[nt] =",
"n4, n3, n2), (n4, n3, n2, n1), (n3, n2, n1, n4), (n2, n1,",
"in chain_order: nt.index = i i += 1 if len(self.tetrad_pairs) > 0: self.tetrad_pairs[0].tetrad1.reorder_to_match_5p_3p()",
"loop in self.loops]) if fingerprint not in loop_classes: logging.error(f'Unknown loop classification: {fingerprint}') return",
"structure += '-' shift_value += 1 sequence += nt.one_letter_name structure += dotbracket.get(nt, '.')",
"order if best_score == (len(self.tetrads) - 1) * 4: break tetrad_pairs = []",
"self.nucleotides]) # this dict has all classes mapped to fingerprints gba_classes = {",
"self.pair_41.reverse(), self.pair_34.reverse() elif order == (self.nt2, self.nt1, self.nt4, self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41",
"in nt.atoms: distance = numpy.linalg.norm(ion.coordinates() - atom.coordinates()) if distance < min_distance: min_distance =",
"tetrad_pair.tetrad1.nt2: tetrad_pair.tetrad2_nts_best_order[1], tetrad_pair.tetrad1.nt3: tetrad_pair.tetrad2_nts_best_order[2], tetrad_pair.tetrad1.nt4: tetrad_pair.tetrad2_nts_best_order[3], } for i in range(4): tracts[i].append(nt_dict[tracts[i][-1]]) return",
"self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse() elif order ==",
"LoopClassification.from_value(f'{loop_classes[fingerprint]}{subtype}') def __str__(self): builder = '' if len(self.tetrads) == 1: builder += '",
"in helices]): helices.append(Helix([tetrad], [], self.structure3d)) return helices def __find_best_chain_order(self): chain_groups = self.__group_related_chains() final_order",
"Optional[GbaTetradClassification]: \"\"\" See: <NAME>. (2007). Geometric Formalism for DNA Quadruplex Folding. Chemistry -",
"str: if self.ions_channel: return 'ions_channel=' + ','.join([atom.atomName for atom in self.ions_channel]) return ''",
"chain order: {\" \".join(final_order)} ' f'{\" \".join(map(lambda onz: onz.value, classifications))}') self.tetrads = self.__find_tetrads(True)",
"self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23 else: self.nt1, self.nt2, self.nt3,",
"i += 1 for nt in self.structure3d.residues: if nt.chain not in chain_order: nt.index",
"nucleotides.index(x) + 1 + shifts[x], nucleotides.index(y) + 1 + shifts[y] onz = self.onz_dict[pair]",
"in coords) zs = (coord[2] for coord in coords) return numpy.array((sum(xs) / len(coords),",
"= field(init=False) tetrad_scores: Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]] = field(init=False) tetrad_pairs: List[TetradPair] =",
"1: return [] loops = [] tetrad_nucleotides = sorted([nt for tetrad in self.tetrads",
"1e10) if len(chains) > 1: for permutation in itertools.permutations(chains): self.__reorder_chains(permutation) classifications = [t.onz",
"= (coord[0] for coord in coords) ys = (coord[1] for coord in coords)",
"= self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() # ONZ and da Silva's classification are valid",
"n/a \"\"\" # without all nucleotides having a valid syn/anti, this classification is",
"if is_next_by_stacking(nts1[i], nts2[i]) else 0 for i in range(4)] score_sequential = [1 if",
"nprev = tetrad_nucleotides[i - 1] ncur = tetrad_nucleotides[i] if ncur.index - nprev.index >",
"in filter(lambda x: x not in (i, j, k) and i in self.base_pair_graph[x],",
"for pair in queue}) queue, removed = removed, [] order += 1 opening",
"{len(self.tetrads)} tetrads\\n' builder += str(self.tetrad_pairs[0].tetrad1) for tetrad_pair in self.tetrad_pairs: builder += str(tetrad_pair) builder",
"ions def __assign_ions_to_tetrads(self) \\ -> Tuple[Dict[Tetrad, List[Atom3D]], Dict[Tuple[Tetrad, Residue3D], List[Atom3D]]]: if len(self.tetrads) ==",
"ncur.index, self.structure3d.residues)) loop_type = self.__detect_loop_type(nprev, ncur) loops.append(Loop(nts, loop_type)) return loops def __detect_loop_type(self, nt_first:",
"helix = tempfile.NamedTemporaryFile('w+', suffix='.helix') helix.write(f'#{len(self.analysis.sequence) + 1}\\n') helix.write('i\\tj\\tlength\\tvalue\\n') for pair in layer: x,",
"GbaTetradClassification.Ia, 'ssaa': GbaTetradClassification.Ib, 'asas': GbaTetradClassification.IIa, 'sasa': GbaTetradClassification.IIb, 'asaa': GbaTetradClassification.IIIa, 'sass': GbaTetradClassification.IIIb, 'aaas': GbaTetradClassification.IVa,",
"in +, one in - direction return Direction.antiparallel return Direction.hybrid def __calculate_rise(self) ->",
"best_permutation: best_permutation = permutation final_order.extend(best_permutation) if len(final_order) > 1: self.__reorder_chains(final_order) classifications = [t.onz",
"any tetrad (distance={min_distance})') for tetrad, ions in ions_channel.items(): tetrad.ions_channel = ions for pair,",
"metal_atom_names = set([ion.value.upper() for ion in Ion]) ions = [] used = set()",
"atom in residue.atoms: if atom.atomName.upper() in metal_atom_names: coordinates = tuple(atom.coordinates()) if coordinates not",
"onz_score = sum(c.score() for c in classifications) chain_order_score = self.__chain_order_score(permutation) score = (onz_score,",
"reorder_to_match_5p_3p(self): # transform into (0, 1, 2, 3) ni, nj, nk, nl =",
"= field(init=False) def __post_init__(self): self.tetrad2_nts_best_order = ( self.stacked[self.tetrad1.nt1], self.stacked[self.tetrad1.nt2], self.stacked[self.tetrad1.nt3], self.stacked[self.tetrad1.nt4] ) self.direction",
"classification are valid in 5'-3' order self.onz = self.__classify_onz() self.gba_class = self.__classify_by_gba() def",
"= f'{prefix}-{suffix}.pdf' run = subprocess.run([os.path.join(currdir, 'quadraw.R'), fasta.name, helix1.name, helix2.name, output_pdf], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if",
"self.tracts: if nt in tract.nucleotides: return tract return None def __detect_loop_sign(self, first: Residue3D,",
"in self.structure3d.residues: for atom in residue.atoms: if atom.atomName.upper() in metal_atom_names: coordinates = tuple(atom.coordinates())",
"for k in filter(lambda x: x not in (i, j), self.graph[j]): for l",
"if score > best_score: best_score = score best_order = order if best_score ==",
"c2 in chain_pairs: sum_sq += (chain_order.index(c1) - chain_order.index(c2)) ** 2 return sum_sq def",
"= '([{<' + string.ascii_uppercase closing = ')]}>' + string.ascii_lowercase dotbracket = dict() for",
"len(self.tetrad_pairs): direction = 'h' counter = Counter([t.onz.value[1] for t in self.tetrads]) plus_minus, support",
"if fingerprint != 'dpd' else 1].loop_type.value[-1] == '-' else 'b' return LoopClassification.from_value(f'{loop_classes[fingerprint]}{subtype}') def",
"= dict() order = 0 queue = list(pairs) removed = [] while queue:",
"self.tetrad_scores[ti][tj][0] order.append(tj) candidates.remove(tj) ti = tj if score > best_score: best_score = score",
"= list() for tetrad in [self.tetrad_pairs[0].tetrad1] + [tetrad_pair.tetrad2 for tetrad_pair in self.tetrad_pairs]: if",
"atoms] xs = (coord[0] for coord in coords) ys = (coord[1] for coord",
"return '+' # reverse check if pair.nt1 == last and pair.nt2 == first:",
"Residue3D nt3: Residue3D nt4: Residue3D pair_12: BasePair3D pair_23: BasePair3D pair_34: BasePair3D pair_41: BasePair3D",
"not None: gbas.add(gba.value[:-1]) # discard 'a' or 'b' subvariant roman_numerals = {'I': 1,",
"builder += f' n/a' builder += f' quadruplex with {len(self.tetrads)} tetrads\\n' builder +=",
"@dataclass(order=True) class Tetrad: @staticmethod def is_valid(nt1: Residue3D, nt2: Residue3D, nt3: Residue3D, nt4: Residue3D,",
"nj: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt2, self.nt3, self.nt4, self.nt1 self.pair_12, self.pair_23, self.pair_34,",
"string made of 's' for syn or 'a' for anti fingerprint = ''.join([nt.chi_class.value[0]",
"builder def __chain_order(self) -> List[str]: only_nucleic_acids = filter(lambda nt: nt.is_nucleotide, self.structure3d.residues) return list({nt.chain:",
"threshold of 6A between an ion and tetrad channel if min_distance < 6.0:",
"visualize(self, prefix: str, suffix: str): fasta = tempfile.NamedTemporaryFile('w+', suffix='.fasta') fasta.write(f'>{prefix}-{suffix}\\n') fasta.write(self.analysis.sequence) fasta.flush() layer1,",
"structure3d.base_pairs(structure2d) self.graph: Dict[Residue3D, List[Residue3D]] = structure3d.base_pair_graph(structure2d) self.pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = structure3d.base_pair_dict(structure2d) def",
"for nts in tracts] def __find_loops(self) -> List[Loop]: if len(self.tetrads) == 1: return",
"x: x not in (i, j), self.graph[j]): for l in filter(lambda x: x",
"'9', 'pdl': '10', 'ldl': '11', 'dpd': '12', 'ldp': '13' } fingerprint = ''.join([loop.loop_type.value[0]",
"zip(indices1, indices2)) direction, count = counter.most_common()[0] if count == 4: # all in",
"return False return True nt1: Residue3D nt2: Residue3D nt3: Residue3D nt4: Residue3D pair_12:",
"def __find_tract_with_nt(self, nt: Residue3D) -> Optional[Tract]: for tract in self.tracts: if nt in",
"# TODO: verify threshold of 3A between an ion and an atom if",
"y = pair.nt1, pair.nt2 x, y = nucleotides.index(x) + 1 + shifts[x], nucleotides.index(y)",
"2): if pi.conflicts_with(pj): conflicts[pi].append(pj) conflicts[pj].append(pi) if conflicts: pair, _ = max(conflicts.items(), key=lambda x:",
"for pi, pj in itertools.combinations(queue, 2): if pi.conflicts_with(pj): conflicts[pi].append(pj) conflicts[pj].append(pi) if conflicts: pair,",
"* 4: break tetrad_pairs = [] for i in range(1, len(best_order)): ti, tj",
"if not any([tetrad in helix.tetrads for helix in helices]): helices.append(Helix([tetrad], [], self.structure3d)) return",
"Optional[List[BasePair3D]] = None) -> tempfile.NamedTemporaryFile(): onz_value = {ONZ.O_PLUS: 1, ONZ.O_MINUS: 2, ONZ.N_PLUS: 3,",
"most with others # in case of a tie, remove one which has",
"ni, nj, nk, nl = nl, ni, nj, nk order = (nj, nk,",
"= self.__determine_direction() self.rise = self.__calculate_rise() self.twist = self.__calculate_twist() def __determine_direction(self) -> Direction: indices1",
"def __find_quadruplexes(self): if len(self.tetrad_pairs) == 0: return [Quadruplex(self.tetrads, [], self.structure3d)] quadruplexes = list()",
"Dict[Residue3D, int]]: layer1, layer2 = [], [] for tetrad in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34])",
"min(ni, nj, nk, nl) if nmin == ni: pass elif nmin == nj:",
"def __detect_loop_sign(self, first: Residue3D, last: Residue3D, tetrad: Tetrad) -> Optional[str]: for pair in",
"builder += str(self.tetrad_pairs[0].tetrad1) for tetrad_pair in self.tetrad_pairs: builder += str(tetrad_pair) builder += str(tetrad_pair.tetrad2)",
"[self.tetrads[0].nt3], [self.tetrads[0].nt4]] if len(self.tetrad_pairs) > 0: for tetrad_pair in self.tetrad_pairs: nt_dict = {",
"!= 3 or any([loop.loop_type is None for loop in self.loops]): return None loop_classes",
"for nt in self.nucleotides]}') return None return gba_classes[fingerprint] def __calculate_planarity_deviation(self) -> float: outer",
"+ shifts[x], nucleotides.index(y) + 1 + shifts[y] helix.write(f'{x}\\t{y}\\t1\\t8\\n') helix.flush() return helix class AnalysisSimple:",
"-> Optional[str]: for pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]: # main check if",
"bool: return check_tetrad(tp.tetrad1) and check_tetrad(tp.tetrad2) return list(filter(check_pair, self.tetrad_pairs)) def __str__(self): builder = ''",
"class Helix: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D quadruplexes: List[Quadruplex] = field(init=False) def",
"return True return False def center_of_mass(atoms): coords = [atom.coordinates() for atom in atoms]",
"Structure2D, structure3d: Structure3D, strict: bool, no_reorder: bool, stacking_mismatch: int) -> Analysis: return Analysis(structure2d,",
"-> float: outer = [nt.outermost_atom for nt in self.nucleotides] inner = [nt.innermost_atom for",
"pi, pj in itertools.combinations(queue, 2): if pi.conflicts_with(pj): conflicts[pi].append(pj) conflicts[pj].append(pi) if conflicts: pair, _",
"distance = numpy.linalg.norm(ion.coordinates() - tetrad.center()) if distance < min_distance: min_distance = distance min_tetrad",
"for chain in chain_order: for nt in self.structure3d.residues: if nt.chain == chain: nt.index",
"self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() else: raise RuntimeError(f'Cannot apply",
"self.tetrad2_nts_best_order)) # count directions 5' -> 3' as +1 or -1 counter =",
"tetrad_with_last is None: logging.warning(f'Failed to classify the loop between {nt_first} and {nt_last}') return",
"chain != nt.chain: sequence += '-' structure += '-' shift_value += 1 sequence",
"== (len(self.tetrads) - 1) * 4: break tetrad_pairs = [] for i in",
"in self.tetrads: distance = numpy.linalg.norm(ion.coordinates() - tetrad.center()) if distance < min_distance: min_distance =",
"Quadruplex: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D onzm: Optional[ONZM] = field(init=False) gba_classes: List[GbaQuadruplexClassification]",
"count == 4: # all in the same direction return Direction.parallel elif count",
"List[Tract]: tracts = [[self.tetrads[0].nt1], [self.tetrads[0].nt2], [self.tetrads[0].nt3], [self.tetrads[0].nt4]] if len(self.tetrad_pairs) > 0: for tetrad_pair",
"case of a tie, pick permutation earlier in lexicographical sense if permutation <",
"Tetrad.is_valid(i, j, k, l, self.base_pair_dict): pair_12 = self.base_pair_dict[(i, j)] pair_23 = self.base_pair_dict[(j, k)]",
"run = subprocess.run([os.path.join(currdir, 'quadraw.R'), fasta.name, helix1.name, helix2.name, output_pdf], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if run.returncode ==",
"support = counter.most_common()[0] if support != len(self.tetrad_pairs): direction = 'h' counter = Counter([t.onz.value[1]",
"for pair in canonical: x, y = pair.nt1, pair.nt2 x, y = nucleotides.index(x)",
"'.join(result) return '' @dataclass class TetradPair: tetrad1: Tetrad tetrad2: Tetrad stacked: Dict[Residue3D, Residue3D]",
"self.nt3, self.nt4 = self.nt1, self.nt4, self.nt3, self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(),",
"best_score_sequential = 0 best_score_stacking = 0 best_order = tj.nucleotides n1, n2, n3, n4",
"self.tetrad_scores[ti][tj][0] if score >= (4 - stacking_mismatch): nts1, nts2 = self.tetrad_scores[ti][tj][1:] stacked =",
"l])) if len(tetrads) > 1: return True return False def center_of_mass(atoms): coords =",
"Residue3D, nt3: Residue3D, nt4: Residue3D, pair_dictionary: Dict[Tuple[Residue3D, Residue3D], BasePair3D]) -> bool: lw1 =",
"helices = [] helix_tetrads = [] helix_tetrad_pairs = [] for tp in self.tetrad_pairs:",
"4: break tetrad_pairs = [] for i in range(1, len(best_order)): ti, tj =",
"ions for pair, ions in ions_outside.items(): tetrad, residue = pair tetrad.ions_outside[residue] = ions",
"stderr=subprocess.PIPE) if run.returncode == 0: print('\\nPlot:', output_pdf) else: logging.error(f'Failed to prepare visualization, reason:\\n",
"in layer: x, y = pair.nt1, pair.nt2 x, y = nucleotides.index(x) + 1",
"self.gba_class = self.__classify_by_gba() def reorder_to_match_other_tetrad(self, order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D]): if order ==",
"= set() for i in self.graph: for j in filter(lambda x: x !=",
"self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() def __group_related_chains(self) -> List[List[str]]: candidates = set() for h",
"tetrad.nucleotides: return tetrad return None def __find_tract_with_nt(self, nt: Residue3D) -> Optional[Tract]: for tract",
"= sum(score_stacking) if (score, score_sequential, score_stacking) > (best_score, best_score_sequential, best_score_stacking): best_score, best_score_sequential, best_score_stacking",
"self.pair_34, self.pair_41, self.pair_12 elif order == (self.nt3, self.nt4, self.nt1, self.nt2): self.pair_12, self.pair_23, self.pair_34,",
"return set([nt.chain for nt in self.nucleotides]) def is_disjoint(self, other) -> bool: return frozenset(self.nucleotides).isdisjoint(frozenset(other.nucleotides))",
"nt.index = i i += 1 for nt in self.structure3d.residues: if nt.chain not",
"[] used = set() for residue in self.structure3d.residues: for atom in residue.atoms: if",
"-> Tuple[Dict[Tetrad, List[Atom3D]], Dict[Tuple[Tetrad, Residue3D], List[Atom3D]]]: if len(self.tetrads) == 0: return {}, {}",
"Residue3D], BasePair3D] = field(init=False) stacking_graph: Dict[Residue3D, List[Residue3D]] = field(init=False) tetrads: List[Tetrad] = field(init=False)",
"combination: {ni} {nj} {nk} {nl}') def __classify_by_gba(self) -> Optional[GbaTetradClassification]: \"\"\" See: <NAME>. (2007).",
"stacking_mismatch: int) -> Analysis: return Analysis(structure2d, structure3d, strict, no_reorder, stacking_mismatch) def has_tetrad(structure2d: Structure2D,",
"tetrads: List[Tetrad] complete2d: bool onz_dict: Dict[BasePair3D, ONZ] = field(init=False) def __post_init__(self): self.onz_dict =",
"7)}\\n') if canonical: for pair in canonical: x, y = pair.nt1, pair.nt2 x,",
"def __elimination_conflicts(self, pairs: List[BasePair3D]) -> Tuple[str, str, Dict[Residue3D, int]]: orders = dict() order",
"(self.nt1, self.nt4, self.nt3, self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse()",
"= pair_dictionary[(nt1, nt2)].lw lw2 = pair_dictionary[(nt2, nt3)].lw lw3 = pair_dictionary[(nt3, nt4)].lw lw4 =",
"= self.__calculate_planarity_deviation() def reorder_to_match_5p_3p(self): # transform into (0, 1, 2, 3) ni, nj,",
"(GlycosidicBond.syn, GlycosidicBond.anti) for nt in self.nucleotides]): return None # this will create a",
"Dict[Residue3D, int] = field(init=False) def __post_init__(self): self.base_pairs = self.structure3d.base_pairs(self.structure2d) self.base_pair_graph = self.structure3d.base_pair_graph(self.structure2d, self.strict)",
"layer2.extend([tetrad.pair_23, tetrad.pair_41]) sequence, line1, shifts = self.__elimination_conflicts(layer1) _, line2, _ = self.__elimination_conflicts(layer2) return",
"nt in self.nucleotides] return numpy.linalg.norm(center_of_mass(outer) - center_of_mass(inner)) @property def nucleotides(self) -> Tuple[Residue3D, Residue3D,",
"tp.tetrad1, tp.tetrad2 if not helix_tetrads: helix_tetrads.append(ti) score = self.tetrad_scores[helix_tetrads[-1]][tj][0] if score >= (4",
"self.structure3d)) return quadruplexes def __filter_tetrad_pairs(self, tetrads: List[Tetrad]) -> List[TetradPair]: chains = set() for",
"one which has the worst planarity deviation candidates = sorted(tetrads, key=lambda t: (len(graph[t]),",
"_ = self.tetrad1.nucleotides nt2_1, nt2_2, _, _ = self.tetrad2_nts_best_order v1 = nt1_1.find_atom(\"C1'\").coordinates() -",
"l # ^--------------^ tetrads = [] for i in self.base_pair_graph: for j in",
"if len(self.tetrads) > 1: builder += f'n4-helix with {len(self.tetrads)} tetrads\\n' for quadruplex in",
"the most with others # in case of a tie, remove one which",
"helix.write(f'{x}\\t{y}\\t1\\t8\\n') helix.flush() return helix class AnalysisSimple: def __init__(self, structure2d: Structure2D, structure3d: Structure3D): self.pairs:",
"= self.__find_loops() self.loop_class = self.__classify_by_loops() def __classify_onzm(self) -> Optional[ONZM]: if len(self.tetrads) == 1:",
"= best_order[i - 1], best_order[i] score = self.tetrad_scores[ti][tj][0] if score >= (4 -",
"2 return sum_sq def __find_ions(self) -> List[Atom3D]: metal_atom_names = set([ion.value.upper() for ion in",
"List[Loop] = field(init=False) loop_class: Optional[LoopClassification] = field(init=False) def __post_init__(self): self.onzm = self.__classify_onzm() self.gba_classes",
"elif order == (2, 1, 3): return ONZ.Z_PLUS elif order == (3, 1,",
"pj in itertools.combinations(queue, 2): if pi.conflicts_with(pj): conflicts[pi].append(pj) conflicts[pj].append(pi) if conflicts: pair, _ =",
"len(tetrads) > 1: return True return False def center_of_mass(atoms): coords = [atom.coordinates() for",
"in the same tetrad sign = self.__detect_loop_sign(nt_first, nt_last, tetrad_with_first) if sign is not",
"= self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() def __group_related_chains(self) -> List[List[str]]: candidates = set() for",
"self.pair_41.reverse().score(): self.nt1, self.nt2, self.nt3, self.nt4 = self.nt1, self.nt4, self.nt3, self.nt2 self.pair_12, self.pair_23, self.pair_34,",
"j - i > 0 else -1 for i, j in zip(indices1, indices2))",
"gba_classes[fingerprint] def __calculate_planarity_deviation(self) -> float: outer = [nt.outermost_atom for nt in self.nucleotides] inner",
"if min_distance < 3.0: ions_outside[(min_tetrad, min_nt)].append(ion) continue logging.debug(f'Skipping an ion, because it is",
"nt2: Residue3D nt3: Residue3D nt4: Residue3D pair_12: BasePair3D pair_23: BasePair3D pair_34: BasePair3D pair_41:",
"return sorted(tetrads, key=lambda t: min(map(lambda nt: nt.index, t.nucleotides))) def __calculate_tetrad_scores(self) \\ -> Dict[Tetrad,",
"x[0].nt1)) removed.append(pair) queue.remove(pair) else: orders.update({pair: order for pair in queue}) queue, removed =",
"self.structure3d)) helix_tetrads = [ti, tj] helix_tetrad_pairs = [tp] if helix_tetrads: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d))",
"'*' return ONZM.from_value(f'{onz}{direction}{plus_minus}') def __classify_by_gba(self) -> List[GbaQuadruplexClassification]: gbas = set() for t in",
"nt_last, tetrad_with_first) if sign is not None: return LoopType.from_value(f'lateral{sign}') return LoopType.diagonal tract_with_last =",
"builder @dataclass class Analysis: structure2d: Structure2D structure3d: Structure3D strict: bool no_reorder: bool stacking_mismatch:",
"nt.chain return sequence, structure, shifts def __str__(self): builder = f'Chain order: {\" \".join(self.__chain_order())}\\n'",
"self.graph: Dict[Residue3D, List[Residue3D]] = structure3d.base_pair_graph(structure2d) self.pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = structure3d.base_pair_dict(structure2d) def has_tetrads(self):",
"= tetrad # TODO: verify threshold of 6A between an ion and tetrad",
"self.nt4 = self.nt2, self.nt3, self.nt4, self.nt1 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34,",
"self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() # ONZ and da Silva's classification are valid in 5'-3'",
"'asas': GbaTetradClassification.IIa, 'sasa': GbaTetradClassification.IIb, 'asaa': GbaTetradClassification.IIIa, 'sass': GbaTetradClassification.IIIb, 'aaas': GbaTetradClassification.IVa, 'sssa': GbaTetradClassification.IVb, 'aasa':",
"self.nucleotides))}' @dataclass class Quadruplex: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D onzm: Optional[ONZM] =",
"-> Analysis: return Analysis(structure2d, structure3d, strict, no_reorder, stacking_mismatch) def has_tetrad(structure2d: Structure2D, structure3d: Structure3D)",
"in self.tetrads]) onz, support = counter.most_common()[0] if support != len(self.tetrads): onz = 'M'",
"1] ncur = tetrad_nucleotides[i] if ncur.index - nprev.index > 1 and ncur.chain ==",
"+= ' single tetrad\\n' builder += str(self.tetrads[0]) else: builder += f' {self.onzm.value if",
"if sign is not None: return LoopType.from_value(f'lateral{sign}') return LoopType.diagonal tract_with_last = self.__find_tract_with_nt(nt_last) if",
"'lll': '6', 'llp': '7', 'lpl': '8', 'pll': '9', 'pdl': '10', 'ldl': '11', 'dpd':",
"= ions for pair, ions in ions_outside.items(): tetrad, residue = pair tetrad.ions_outside[residue] =",
"return ONZ.Z_PLUS elif order == (3, 1, 2): return ONZ.Z_MINUS raise RuntimeError(f'Impossible combination:",
"rise: float = field(init=False) twist: float = field(init=False) def __post_init__(self): self.tetrad2_nts_best_order = (",
"to fingerprints gba_classes = { 'aass': GbaTetradClassification.Ia, 'ssaa': GbaTetradClassification.Ib, 'asas': GbaTetradClassification.IIa, 'sasa': GbaTetradClassification.IIb,",
"list({nt.chain: 0 for nt in sorted(only_nucleic_acids, key=lambda nt: nt.index)}.keys()) def canonical(self) -> List[BasePair3D]:",
"self.nt2, self.nt3, self.nt4, self.nt1 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12",
"field(init=False) helices: List[Helix] = field(init=False) ions: List[Atom3D] = field(init=False) sequence: str = field(init=False)",
"'7', 'lpl': '8', 'pll': '9', 'pdl': '10', 'ldl': '11', 'dpd': '12', 'ldp': '13'",
"(self.nt4, self.nt3, self.nt2, self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse()",
"in self.tetrads for nt in tetrad.nucleotides], key=lambda nt: nt.index) for i in range(1,",
"return check_tetrad(tp.tetrad1) and check_tetrad(tp.tetrad2) return list(filter(check_pair, self.tetrad_pairs)) def __str__(self): builder = '' if",
"to classify the loop between {nt_first} and {nt_last}') return None if tetrad_with_first ==",
"return None loop_classes = { 'ppp': '1', 'ppl': '2', 'plp': '3', 'lpp': '4',",
"set() for h in self.helices: for t in h.tetrads: candidates.add(frozenset([t.nt1.chain, t.nt2.chain, t.nt3.chain, t.nt4.chain]))",
"self.sequence, self.line1, self.line2, self.shifts = self.__generate_twoline_dotbracket() self.ions = self.__find_ions() self.__assign_ions_to_tetrads() def __find_tetrads(self, no_reorder=False)",
"return numpy.linalg.norm(center_of_mass(outer) - center_of_mass(inner)) @property def nucleotides(self) -> Tuple[Residue3D, Residue3D, Residue3D, Residue3D]: return",
"classifications = [t.onz for h in self.helices for t in h.tetrads] logging.debug(f'Selected chain",
"= self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif nmin == nk: self.nt1, self.nt2, self.nt3, self.nt4",
"== (1, 3, 2): return ONZ.N_PLUS elif order == (2, 3, 1): return",
"\\ f'{self.pair_12.lw.value} {self.pair_23.lw.value} {self.pair_34.lw.value} {self.pair_41.lw.value} ' \\ f'{self.onz.value} {self.gba_class.value} ' \\ f'planarity={round(self.planarity_deviation, 2)}",
"ions_outside[(min_tetrad, min_nt)].append(ion) continue logging.debug(f'Skipping an ion, because it is too far from any",
"[]) def is_next_sequentially(nt1: Residue3D, nt2: Residue3D) -> bool: return nt1.chain == nt2.chain and",
"= chains, (1e10, 1e10) if len(chains) > 1: for permutation in itertools.permutations(chains): self.__reorder_chains(permutation)",
"self.tetrads[0] min_nt = min_tetrad.nt1 for tetrad in self.tetrads: for nt in tetrad.nucleotides: for",
"helix class AnalysisSimple: def __init__(self, structure2d: Structure2D, structure3d: Structure3D): self.pairs: List[BasePair3D] = structure3d.base_pairs(structure2d)",
"i in range(4)] score = sum([max(score_stacking[i], score_sequential[i]) for i in range(4)]) score_sequential =",
"<NAME>. (2007). Geometric Formalism for DNA Quadruplex Folding. Chemistry - A European Journal,",
"max(conflicts.items(), key=lambda x: (len(x[1]), x[0].nt1)) removed.append(pair) queue.remove(pair) else: orders.update({pair: order for pair in",
"None: return LoopType.from_value(f'lateral{sign}') return LoopType.diagonal tract_with_last = self.__find_tract_with_nt(nt_last) if tract_with_last is not None:",
"self.nt3 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34 # flip order",
"viable_permutations: score_stacking = [1 if is_next_by_stacking(nts1[i], nts2[i]) else 0 for i in range(4)]",
"ONZ = field(init=False) gba_class: Optional[GbaTetradClassification] = field(init=False) planarity_deviation: float = field(init=False) ions_channel: List[Atom3D]",
"of a tie, pick permutation earlier in lexicographical sense if permutation < best_permutation:",
"nk, nl = (indices.index(x) for x in (ni, nj, nk, nl)) nmin =",
"= tj.nucleotides n1, n2, n3, n4 = tj.nucleotides viable_permutations = [(n1, n2, n3,",
"k, l])) if len(tetrads) > 1: return True return False def center_of_mass(atoms): coords",
"or laterals happen when first and last nt of a loop is in",
"self.loops: builder += '\\n Loops:\\n' for loop in self.loops: builder += f'{loop}\\n' builder",
"-> List[TetradPair]: tetrads = list(self.tetrads) best_score = 0 best_order = tetrads for ti",
"GbaTetradClassification.IIa, 'sasa': GbaTetradClassification.IIb, 'asaa': GbaTetradClassification.IIIa, 'sass': GbaTetradClassification.IIIb, 'aaas': GbaTetradClassification.IVa, 'sssa': GbaTetradClassification.IVb, 'aasa': GbaTetradClassification.Va,",
"self.pair_dict): tetrads.add(frozenset([i, j, k, l])) if len(tetrads) > 1: return True return False",
"= distance min_tetrad = tetrad # TODO: verify threshold of 6A between an",
"== 1: builder += ' single tetrad\\n' builder += str(self.tetrads[0]) else: builder +=",
"happen when first and last nt of a loop is in the same",
"builder += str(tetrad_pair) builder += str(tetrad_pair.tetrad2) if self.tracts: builder += '\\n Tracts:\\n' for",
"counter = Counter([tp.direction.value[0] for tp in self.tetrad_pairs]) direction, support = counter.most_common()[0] if support",
"or tetrad_with_last is None: logging.warning(f'Failed to classify the loop between {nt_first} and {nt_last}')",
"if lw_i.name[1] == lw_j.name[2]: return False return True nt1: Residue3D nt2: Residue3D nt3:",
"nucleotides.index(x) + 1 + shifts[x], nucleotides.index(y) + 1 + shifts[y] helix.write(f'{x}\\t{y}\\t1\\t8\\n') helix.flush() return",
"for (ti, tj) in itertools.combinations(tetrads, 2): if not ti.is_disjoint(tj): graph[ti].append(tj) graph[tj].append(ti) # remove",
"__post_init__(self): self.base_pairs = self.structure3d.base_pairs(self.structure2d) self.base_pair_graph = self.structure3d.base_pair_graph(self.structure2d, self.strict) self.base_pair_dict = self.structure3d.base_pair_dict(self.structure2d, self.strict) self.stacking_graph",
"helix.flush() return helix class AnalysisSimple: def __init__(self, structure2d: Structure2D, structure3d: Structure3D): self.pairs: List[BasePair3D]",
"= [1 if is_next_sequentially(nts1[i], nts2[i]) else 0 for i in range(4)] score =",
"Iterable, List, Tuple, Optional, Set import numpy from eltetrado.model import Atom3D, Structure3D, Structure2D,",
"(n3, n2, n1, n4), (n2, n1, n4, n3)] for nts2 in viable_permutations: score_stacking",
"tp.stacked[tp.tetrad1.nt2], tp.stacked[tp.tetrad1.nt3], tp.stacked[tp.tetrad1.nt4]) tp.tetrad2.reorder_to_match_5p_3p() # this is required to recalculate ONZ tp.tetrad2.reorder_to_match_other_tetrad(order) def",
"in self.stacking_graph.get(nt1, []) def is_next_sequentially(nt1: Residue3D, nt2: Residue3D) -> bool: return nt1.chain ==",
"string.ascii_uppercase closing = ')]}>' + string.ascii_lowercase dotbracket = dict() for pair, order in",
"return ions def __assign_ions_to_tetrads(self) \\ -> Tuple[Dict[Tetrad, List[Atom3D]], Dict[Tuple[Tetrad, Residue3D], List[Atom3D]]]: if len(self.tetrads)",
"atom if min_distance < 3.0: ions_outside[(min_tetrad, min_nt)].append(ion) continue logging.debug(f'Skipping an ion, because it",
"= self.tetrad2.outer_and_inner_atoms() return numpy.linalg.norm(center_of_mass(t1) - center_of_mass(t2)) def __calculate_twist(self) -> float: nt1_1, nt1_2, _,",
"else: builder += f' {self.onzm.value if self.onzm is not None else \"R\"}' builder",
"if c1 != c2 and c1 in chain_order and c2 in chain_order: chain_pairs.append([c1,",
"nk, nl)) while ni != 0: ni, nj, nk, nl = nl, ni,",
"in h.tetrads] logging.debug( f'Checking reorder: {\" \".join(permutation)} {\" \".join(map(lambda c: c.value, classifications))}') onz_score",
"sequence += '-' structure += '-' shift_value += 1 sequence += nt.one_letter_name structure",
"return 'ions_channel=' + ','.join([atom.atomName for atom in self.ions_channel]) return '' def __ions_outside_str(self) ->",
"atom in self.ions_channel]) return '' def __ions_outside_str(self) -> str: if self.ions_outside: result =",
"lw4 = pair_dictionary[(nt4, nt1)].lw for lw_i, lw_j in ((lw1, lw4), (lw2, lw1), (lw3,",
"self.pair_23, self.pair_34, self.pair_41 = self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse() elif order == (self.nt2, self.nt1,",
"Silva's classification are valid in 5'-3' order self.onz = self.__classify_onz() self.gba_class = self.__classify_by_gba()",
"i in self.graph: for j in filter(lambda x: x != i, self.graph[i]): for",
"self.structure3d.residues: for atom in residue.atoms: if atom.atomName.upper() in metal_atom_names: coordinates = tuple(atom.coordinates()) if",
"None for nt in sorted(filter(lambda nt: nt.is_nucleotide, self.structure3d.residues), key=lambda nt: nt.index): if chain",
"0 best_order = tj.nucleotides n1, n2, n3, n4 = tj.nucleotides viable_permutations = [(n1,",
"List[GbaQuadruplexClassification]: gbas = set() for t in self.tetrads: gba = t.gba_class if gba",
"range(4)] score = sum([max(score_stacking[i], score_sequential[i]) for i in range(4)]) score_sequential = sum(score_sequential) score_stacking",
"if nprev in tract.nucleotides and ncur in tract.nucleotides: break else: nts = list(filter(lambda",
"Optional[ONZM]: if len(self.tetrads) == 1: return None if any([t.onz is None for t",
"dotbracket.get(nt, '.') shifts[nt] = shift_value chain = nt.chain return sequence, structure, shifts def",
"quadruplexes: List[Quadruplex] = field(init=False) def __post_init__(self): self.quadruplexes = self.__find_quadruplexes() def __find_quadruplexes(self): if len(self.tetrad_pairs)",
"x: x != i, self.base_pair_graph[i]): for k in filter(lambda x: x not in",
"field(default_factory=list) ions_outside: Dict[Residue3D, List[Atom3D]] = field(default_factory=dict) def __post_init__(self): self.reorder_to_match_5p_3p() self.planarity_deviation = self.__calculate_planarity_deviation() def",
"= self.__classify_onz() self.gba_class = self.__classify_by_gba() def reorder_to_match_other_tetrad(self, order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D]): if",
"a tie, pick permutation earlier in lexicographical sense if permutation < best_permutation: best_permutation",
"List[List[str]]: candidates = set() for h in self.helices: for t in h.tetrads: candidates.add(frozenset([t.nt1.chain,",
"in self.helices: builder += str(helix) builder += f'{self.sequence}\\n{self.line1}\\n{self.line2}' return builder def __chain_order(self) ->",
"- center_of_mass(t2)) def __calculate_twist(self) -> float: nt1_1, nt1_2, _, _ = self.tetrad1.nucleotides nt2_1,",
"= self.__find_ions() self.__assign_ions_to_tetrads() def __find_tetrads(self, no_reorder=False) -> List[Tetrad]: # search for a tetrad:",
"= distance min_tetrad = tetrad min_nt = nt # TODO: verify threshold of",
"for nt in self.nucleotides]) def is_disjoint(self, other) -> bool: return frozenset(self.nucleotides).isdisjoint(frozenset(other.nucleotides)) def center(self)",
"else \"n/a\"} ' \\ f'{\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass class Quadruplex: tetrads:",
"' single tetrad\\n' builder += str(self.tetrads[0]) else: builder += f' {self.onzm.value if self.onzm",
"nt.is_nucleotide, self.structure3d.residues) return list({nt.chain: 0 for nt in sorted(only_nucleic_acids, key=lambda nt: nt.index)}.keys()) def",
"self.pair_41, self.pair_12, self.pair_23 else: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt4, self.nt1, self.nt2, self.nt3",
"nt in self.nucleotides) indices = sorted((ni, nj, nk, nl)) ni, nj, nk, nl",
"distance = numpy.linalg.norm(ion.coordinates() - atom.coordinates()) if distance < min_distance: min_distance = distance min_tetrad",
"x != i, self.graph[i]): for k in filter(lambda x: x not in (i,",
"stdout=subprocess.PIPE, stderr=subprocess.PIPE) if run.returncode == 0: print('\\nPlot:', output_pdf) else: logging.error(f'Failed to prepare visualization,",
"self.tetrad2_nts_best_order = ( self.stacked[self.tetrad1.nt1], self.stacked[self.tetrad1.nt2], self.stacked[self.tetrad1.nt3], self.stacked[self.tetrad1.nt4] ) self.direction = self.__determine_direction() self.rise =",
"= self.pair_41, self.pair_12, self.pair_23, self.pair_34 elif order == (self.nt4, self.nt3, self.nt2, self.nt1): self.pair_12,",
"in ((lw1, lw4), (lw2, lw1), (lw3, lw2), (lw4, lw3)): if lw_i.name[1] == lw_j.name[2]:",
"else: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt4, self.nt1, self.nt2, self.nt3 self.pair_12, self.pair_23, self.pair_34,",
"self.pair_41 = self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse() elif order == (self.nt3, self.nt2, self.nt1, self.nt4):",
"pair_34 = self.base_pair_dict[(k, l)] pair_41 = self.base_pair_dict[(l, i)] tetrads.append(Tetrad(i, j, k, l, pair_12,",
"List[GbaQuadruplexClassification] = field(init=False) tracts: List[Tract] = field(init=False) loops: List[Loop] = field(init=False) loop_class: Optional[LoopClassification]",
"xs = (coord[0] for coord in coords) ys = (coord[1] for coord in",
"in self.nucleotides) indices = sorted((ni, nj, nk, nl)) ni, nj, nk, nl =",
"in self.tetrads]): return None counter = Counter([t.onz.value[0] for t in self.tetrads]) onz, support",
"> 1 and ncur.chain == nprev.chain: for tract in self.tracts: if nprev in",
"k -> l # ^--------------^ tetrads = [] for i in self.base_pair_graph: for",
"an atom if min_distance < 3.0: ions_outside[(min_tetrad, min_nt)].append(ion) continue logging.debug(f'Skipping an ion, because",
"Residue3D) -> Optional[Tetrad]: for tetrad in self.tetrads: if nt in tetrad.nucleotides: return tetrad",
"closing[order] sequence = '' structure = '' shifts = dict() shift_value = 0",
"2, 'III': 3, 'IV': 4, 'V': 5, 'VI': 6, 'VII': 7, 'VIII': 8}",
"+= f'n4-helix with {len(self.tetrads)} tetrads\\n' for quadruplex in self.quadruplexes: builder += str(quadruplex) elif",
"= nl, ni, nj, nk order = (nj, nk, nl) if order ==",
"self.tetrad_pairs]: if tetrads: if tetrad.chains().isdisjoint(tetrads[-1].chains()): quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) tetrads = list() tetrads.append(tetrad) quadruplexes.append(Quadruplex(tetrads,",
"if nt in tract.nucleotides: return tract return None def __detect_loop_sign(self, first: Residue3D, last:",
"[] for chains in chain_groups: best_permutation, best_score = chains, (1e10, 1e10) if len(chains)",
"distance min_tetrad = tetrad min_nt = nt # TODO: verify threshold of 3A",
"Counter(1 if j - i > 0 else -1 for i, j in",
"f' direction={self.direction.value} rise={round(self.rise, 2)} twist={round(self.twist, 2)}\\n' @dataclass class Tract: nucleotides: List[Residue3D] def __str__(self):",
"check_tetrad(tp.tetrad1) and check_tetrad(tp.tetrad2) return list(filter(check_pair, self.tetrad_pairs)) def __str__(self): builder = '' if len(self.tetrads)",
"if self.loop_type else \"n/a\"} ' \\ f'{\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass class",
"residue = pair tetrad.ions_outside[residue] = ions def __generate_twoline_dotbracket(self) -> Tuple[str, str, str, Dict[Residue3D,",
"= [] helix_tetrad_pairs = [] for tp in self.tetrad_pairs: ti, tj = tp.tetrad1,",
"self.pair_41, self.pair_12, self.pair_23 elif order == (self.nt4, self.nt1, self.nt2, self.nt3): self.pair_12, self.pair_23, self.pair_34,",
"is impossible if not all([nt.chi_class in (GlycosidicBond.syn, GlycosidicBond.anti) for nt in self.nucleotides]): return",
"self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse() elif order == (self.nt3,",
"chain_order_score = self.__chain_order_score(permutation) score = (onz_score, chain_order_score) if score < best_score: best_score =",
"onz_value = {ONZ.O_PLUS: 1, ONZ.O_MINUS: 2, ONZ.N_PLUS: 3, ONZ.N_MINUS: 4, ONZ.Z_PLUS: 5, ONZ.Z_MINUS:",
"for nt in tract_with_last.nucleotides: if nt in tetrad_with_first.nucleotides: sign = self.__detect_loop_sign(nt_first, nt, tetrad_with_first)",
"while ni != 0: ni, nj, nk, nl = nl, ni, nj, nk",
"__str__(self): builder = '' if len(self.tetrads) > 1: builder += f'n4-helix with {len(self.tetrads)}",
"GbaTetradClassification.VIIa, 'saaa': GbaTetradClassification.VIIb, 'aaaa': GbaTetradClassification.VIIIa, 'ssss': GbaTetradClassification.VIIIb } if fingerprint not in gba_classes:",
"[t.onz for h in self.helices for t in h.tetrads] logging.debug(f'Selected chain order: {\"",
"import Dict, Iterable, List, Tuple, Optional, Set import numpy from eltetrado.model import Atom3D,",
"i in range(1, len(tetrad_nucleotides)): nprev = tetrad_nucleotides[i - 1] ncur = tetrad_nucleotides[i] if",
"__find_best_chain_order(self): chain_groups = self.__group_related_chains() final_order = [] for chains in chain_groups: best_permutation, best_score",
"(2007). Geometric Formalism for DNA Quadruplex Folding. Chemistry - A European Journal, 13(35),",
"float = field(init=False) twist: float = field(init=False) def __post_init__(self): self.tetrad2_nts_best_order = ( self.stacked[self.tetrad1.nt1],",
"stacking_graph: Dict[Residue3D, List[Residue3D]] = field(init=False) tetrads: List[Tetrad] = field(init=False) tetrad_scores: Dict[Tetrad, Dict[Tetrad, Tuple[int,",
"order == (2, 3, 1): return ONZ.N_MINUS elif order == (2, 1, 3):",
"+= '\\n Tracts:\\n' for tract in self.tracts: builder += f'{tract}\\n' if self.loops: builder",
"== last and pair.nt2 == first: if pair.score() < pair.reverse().score(): return '+' return",
"for helix in self.helices: builder += str(helix) builder += f'{self.sequence}\\n{self.line1}\\n{self.line2}' return builder def",
"> 1: return True return False def center_of_mass(atoms): coords = [atom.coordinates() for atom",
"for ion in ions])}]') return 'ions_outside=' + ' '.join(result) return '' @dataclass class",
"\"n/a\"} ' \\ f'{\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass class Quadruplex: tetrads: List[Tetrad]",
"# transform into (0, 1, 2, 3) ni, nj, nk, nl = (nt.index",
"gbas = sorted(gbas, key=lambda gba: roman_numerals.get(gba, 100)) return list(map(lambda x: GbaQuadruplexClassification[x], gbas)) def",
"def __find_helices(self): helices = [] helix_tetrads = [] helix_tetrad_pairs = [] for tp",
"Analysis tetrads: List[Tetrad] complete2d: bool onz_dict: Dict[BasePair3D, ONZ] = field(init=False) def __post_init__(self): self.onz_dict",
"in tetrad.nucleotides], key=lambda nt: nt.index) for i in range(1, len(tetrad_nucleotides)): nprev = tetrad_nucleotides[i",
"2, ONZ.N_PLUS: 3, ONZ.N_MINUS: 4, ONZ.Z_PLUS: 5, ONZ.Z_MINUS: 6} nucleotides = self.analysis.structure3d.residues shifts",
"direction={self.direction.value} rise={round(self.rise, 2)} twist={round(self.twist, 2)}\\n' @dataclass class Tract: nucleotides: List[Residue3D] def __str__(self): return",
"True break candidates = sorted(candidates, key=lambda x: len(x), reverse=True) groups = [] for",
"c1 != c2 and c1 in chain_order and c2 in chain_order: chain_pairs.append([c1, c2])",
"-> Set[str]: return set([nt.chain for nt in self.nucleotides]) def is_disjoint(self, other) -> bool:",
"in Ion]) ions = [] used = set() for residue in self.structure3d.residues: for",
"return None subtype = 'a' if self.loops[0 if fingerprint != 'dpd' else 1].loop_type.value[-1]",
"ni, nj, nk, nl = map(lambda nt: nt.index, self.nucleotides) indices = sorted((ni, nj,",
"chain_order: for nt in self.structure3d.residues: if nt.chain == chain: nt.index = i i",
"stacked.items()}) tetrad_pairs.append(TetradPair(ti, tj, stacked)) order = (stacked[ti.nt1], stacked[ti.nt2], stacked[ti.nt3], stacked[ti.nt4]) tj.reorder_to_match_other_tetrad(order) return tetrad_pairs",
"order == (3, 2, 1): return ONZ.O_MINUS elif order == (1, 3, 2):",
"i += 1 if len(self.tetrad_pairs) > 0: self.tetrad_pairs[0].tetrad1.reorder_to_match_5p_3p() for tp in self.tetrad_pairs: order",
"= sum([max(score_stacking[i], score_sequential[i]) for i in range(4)]) score_sequential = sum(score_sequential) score_stacking = sum(score_stacking)",
"self.nt3, self.nt4 def __hash__(self): return hash(frozenset([self.nt1, self.nt2, self.nt3, self.nt4])) def __str__(self): return f'",
"nucleotides = self.analysis.structure3d.residues shifts = self.analysis.shifts helix = tempfile.NamedTemporaryFile('w+', suffix='.helix') helix.write(f'#{len(self.analysis.sequence) + 1}\\n')",
"sorted([sorted(group) for group in groups], key=lambda x: x[0]) def __reorder_chains(self, chain_order: Iterable[str]): i",
"= field(default_factory=dict) def __post_init__(self): self.reorder_to_match_5p_3p() self.planarity_deviation = self.__calculate_planarity_deviation() def reorder_to_match_5p_3p(self): # transform into",
"Structure3D, strict: bool, no_reorder: bool, stacking_mismatch: int) -> Analysis: return Analysis(structure2d, structure3d, strict,",
"= self.__chain_order_score(permutation) score = (onz_score, chain_order_score) if score < best_score: best_score = score",
"= defaultdict(list) ions_outside = defaultdict(list) for ion in self.ions: min_distance = math.inf min_tetrad",
"def __str__(self): builder = '' if len(self.tetrads) > 1: builder += f'n4-helix with",
"base_pair_graph: Dict[Residue3D, List[Residue3D]] = field(init=False) base_pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = field(init=False) stacking_graph: Dict[Residue3D,",
"counter.most_common()[0] if support != len(self.tetrads): plus_minus = '*' return ONZM.from_value(f'{onz}{direction}{plus_minus}') def __classify_by_gba(self) ->",
"nt in tetrad_with_first.nucleotides: sign = self.__detect_loop_sign(nt_first, nt, tetrad_with_first) if sign is not None:",
"self.pair_12.reverse() # ONZ and da Silva's classification are valid in 5'-3' order self.onz",
"nt.index)}.keys()) def canonical(self) -> List[BasePair3D]: return [base_pair for base_pair in self.base_pairs if base_pair.is_canonical()]",
"pairs with nt_first for nt in tract_with_last.nucleotides: if nt in tetrad_with_first.nucleotides: sign =",
"ni, nj, nk, nl = (indices.index(x) for x in (ni, nj, nk, nl))",
"string.ascii_lowercase dotbracket = dict() for pair, order in orders.items(): nt1, nt2 = sorted([pair.nt1,",
"'ssaa': GbaTetradClassification.Ib, 'asas': GbaTetradClassification.IIa, 'sasa': GbaTetradClassification.IIb, 'asaa': GbaTetradClassification.IIIa, 'sass': GbaTetradClassification.IIIb, 'aaas': GbaTetradClassification.IVa, 'sssa':",
"self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23 else: self.nt1, self.nt2,",
"nt1_1, nt1_2, _, _ = self.tetrad1.nucleotides nt2_1, nt2_2, _, _ = self.tetrad2_nts_best_order v1",
"def chains(self) -> Set[str]: return set([nt.chain for nt in self.nucleotides]) def is_disjoint(self, other)",
"float: nt1_1, nt1_2, _, _ = self.tetrad1.nucleotides nt2_1, nt2_2, _, _ = self.tetrad2_nts_best_order",
"Atom3D, Structure3D, Structure2D, BasePair3D, Residue3D, GlycosidicBond, ONZ, \\ GbaTetradClassification, Ion, Direction, LoopType, ONZM,",
"builder += '\\n Loops:\\n' for loop in self.loops: builder += f'{loop}\\n' builder +=",
"map(lambda nt: nt.index, self.nucleotides) indices = sorted((ni, nj, nk, nl)) ni, nj, nk,",
"order == (3, 1, 2): return ONZ.Z_MINUS raise RuntimeError(f'Impossible combination: {ni} {nj} {nk}",
"tract in self.tracts: if nprev in tract.nucleotides and ncur in tract.nucleotides: break else:",
"i, j in zip(indices1, indices2)) direction, count = counter.most_common()[0] if count == 4:",
"in groups]): continue groups.append(candidate) return sorted([sorted(group) for group in groups], key=lambda x: x[0])",
"for x in (ni, nj, nk, nl)) nmin = min(ni, nj, nk, nl)",
"= defaultdict(list) for pi, pj in itertools.combinations(queue, 2): if pi.conflicts_with(pj): conflicts[pi].append(pj) conflicts[pj].append(pi) if",
"return '' def __ions_outside_str(self) -> str: if self.ions_outside: result = [] for residue,",
"not None: return LoopType.from_value(f'lateral{sign}') return LoopType.diagonal tract_with_last = self.__find_tract_with_nt(nt_last) if tract_with_last is not",
"f'{self.__ions_channel_str()} ' \\ f'{self.__ions_outside_str()}\\n' def chains(self) -> Set[str]: return set([nt.chain for nt in",
"= field(init=False) def __post_init__(self): self.onz_dict = {pair: tetrad.onz for tetrad in self.tetrads for",
"'ions_channel=' + ','.join([atom.atomName for atom in self.ions_channel]) return '' def __ions_outside_str(self) -> str:",
"Residue3D]): if order == (self.nt1, self.nt2, self.nt3, self.nt4): pass elif order == (self.nt2,",
"= sorted(candidates, key=lambda x: len(x), reverse=True) groups = [] for candidate in candidates:",
"for k in filter(lambda x: x not in (i, j), self.base_pair_graph[j]): for l",
"t in h.tetrads] logging.debug( f'Checking reorder: {\" \".join(permutation)} {\" \".join(map(lambda c: c.value, classifications))}')",
"not any([tetrad in helix.tetrads for helix in helices]): helices.append(Helix([tetrad], [], self.structure3d)) return helices",
"= 0 best_order = tetrads for ti in tetrads: score = 0 order",
"class Tract: nucleotides: List[Residue3D] def __str__(self): return f' {\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}'",
"elif order == (3, 2, 1): return ONZ.O_MINUS elif order == (1, 3,",
"= ( self.stacked[self.tetrad1.nt1], self.stacked[self.tetrad1.nt2], self.stacked[self.tetrad1.nt3], self.stacked[self.tetrad1.nt4] ) self.direction = self.__determine_direction() self.rise = self.__calculate_rise()",
"for pair, ions in ions_outside.items(): tetrad, residue = pair tetrad.ions_outside[residue] = ions def",
"'IV': 4, 'V': 5, 'VI': 6, 'VII': 7, 'VIII': 8} gbas = sorted(gbas,",
"line2, _ = self.__elimination_conflicts(layer2) return sequence, line1, line2, shifts def __elimination_conflicts(self, pairs: List[BasePair3D])",
"candidates[i], candidates[j] if not qi.isdisjoint(qj): qi.update(qj) del candidates[j] changed = True break candidates",
"= set() for h in self.helices: for t in h.tetrads: candidates.add(frozenset([t.nt1.chain, t.nt2.chain, t.nt3.chain,",
"= { 'aass': GbaTetradClassification.Ia, 'ssaa': GbaTetradClassification.Ib, 'asas': GbaTetradClassification.IIa, 'sasa': GbaTetradClassification.IIb, 'asaa': GbaTetradClassification.IIIa, 'sass':",
"None: # search along the tract to check what pairs with nt_first for",
"self.helices for t in h.tetrads] logging.debug( f'Checking reorder: {\" \".join(permutation)} {\" \".join(map(lambda c:",
"nts1) return tetrad_scores def __find_tetrad_pairs(self, stacking_mismatch: int) -> List[TetradPair]: tetrads = list(self.tetrads) best_score",
"self.nt3, self.nt4, self.nt1 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif",
"if Tetrad.is_valid(i, j, k, l, self.base_pair_dict): pair_12 = self.base_pair_dict[(i, j)] pair_23 = self.base_pair_dict[(j,",
"= '' if len(self.tetrads) > 1: builder += f'n4-helix with {len(self.tetrads)} tetrads\\n' for",
"> (best_score, best_score_sequential, best_score_stacking): best_score, best_score_sequential, best_score_stacking = score, score_sequential, score_stacking best_order =",
"tetrad_with_first) if sign is not None: return LoopType.from_value(f'propeller{sign}') logging.warning(f'Failed to classify the loop",
"center(self) -> numpy.ndarray: return center_of_mass(self.outer_and_inner_atoms()) def outer_and_inner_atoms(self) -> List[Atom3D]: return list(map(lambda residue: residue.outermost_atom,",
"'+' # reverse check if pair.nt1 == last and pair.nt2 == first: if",
"score == best_score: # in case of a tie, pick permutation earlier in",
"self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34 # flip order if",
"in tract.nucleotides: break else: nts = list(filter(lambda nt: nprev.index < nt.index < ncur.index,",
"# this dict has all classes mapped to fingerprints gba_classes = { 'aass':",
"v2), -1.0, 1.0))) def __str__(self): return f' direction={self.direction.value} rise={round(self.rise, 2)} twist={round(self.twist, 2)}\\n' @dataclass",
"< best_permutation: best_permutation = permutation final_order.extend(best_permutation) if len(final_order) > 1: self.__reorder_chains(final_order) classifications =",
"= sorted([nt for tetrad in self.tetrads for nt in tetrad.nucleotides], key=lambda nt: nt.index)",
"-> int: chain_pairs = [] for h in self.helices: for t in h.tetrads:",
"field(init=False) line1: str = field(init=False) line2: str = field(init=False) shifts: Dict[Residue3D, int] =",
"def has_tetrad(structure2d: Structure2D, structure3d: Structure3D) -> bool: structure = AnalysisSimple(structure2d, structure3d) return structure.has_tetrads()",
"return ONZ.Z_MINUS raise RuntimeError(f'Impossible combination: {ni} {nj} {nk} {nl}') def __classify_by_gba(self) -> Optional[GbaTetradClassification]:",
"def __find_tetrad_pairs(self, stacking_mismatch: int) -> List[TetradPair]: tetrads = list(self.tetrads) best_score = 0 best_order",
"and tetrad channel if min_distance < 6.0: ions_channel[min_tetrad].append(ion) continue min_distance = math.inf min_tetrad",
"with {len(self.tetrads)} tetrads\\n' builder += str(self.tetrad_pairs[0].tetrad1) for tetrad_pair in self.tetrad_pairs: builder += str(tetrad_pair)",
"= defaultdict(list) for ion in self.ions: min_distance = math.inf min_tetrad = self.tetrads[0] for",
"list(filter(check_pair, self.tetrad_pairs)) def __str__(self): builder = '' if len(self.tetrads) > 1: builder +=",
"self.tetrad_pairs: builder += str(tetrad_pair) builder += str(tetrad_pair.tetrad2) if self.tracts: builder += '\\n Tracts:\\n'",
"self.structure3d)] quadruplexes = list() tetrads = list() for tetrad in [self.tetrad_pairs[0].tetrad1] + [tetrad_pair.tetrad2",
"candidate in candidates: if any([group.issuperset(candidate) for group in groups]): continue groups.append(candidate) return sorted([sorted(group)",
"{nt_last}') return None if tetrad_with_first == tetrad_with_last: # diagonal or laterals happen when",
"direction, count = counter.most_common()[0] if count == 4: # all in the same",
"/ len(coords), sum(zs) / len(coords))) def eltetrado(structure2d: Structure2D, structure3d: Structure3D, strict: bool, no_reorder:",
"self.helices = self.__find_helices() if not self.no_reorder: self.__find_best_chain_order() self.sequence, self.line1, self.line2, self.shifts = self.__generate_twoline_dotbracket()",
"(best_score, best_score_sequential, best_score_stacking): best_score, best_score_sequential, best_score_stacking = score, score_sequential, score_stacking best_order = nts2",
"while queue: conflicts = defaultdict(list) for pi, pj in itertools.combinations(queue, 2): if pi.conflicts_with(pj):",
"pair.score() < pair.reverse().score(): return '+' return '-' return None def __classify_by_loops(self) -> Optional[LoopClassification]:",
"for t in h.tetrads: candidates.add(frozenset([t.nt1.chain, t.nt2.chain, t.nt3.chain, t.nt4.chain])) candidates = [set(c) for c",
"if run.returncode == 0: print('\\nPlot:', output_pdf) else: logging.error(f'Failed to prepare visualization, reason:\\n {run.stderr.decode()}')",
"return 'ions_outside=' + ' '.join(result) return '' @dataclass class TetradPair: tetrad1: Tetrad tetrad2:",
"atom in nt.atoms: distance = numpy.linalg.norm(ion.coordinates() - atom.coordinates()) if distance < min_distance: min_distance",
"logging.debug(f'Selected chain order: {\" \".join(final_order)} ' f'{\" \".join(map(lambda onz: onz.value, classifications))}') self.tetrads =",
"List[Loop]: if len(self.tetrads) == 1: return [] loops = [] tetrad_nucleotides = sorted([nt",
"+= (chain_order.index(c1) - chain_order.index(c2)) ** 2 return sum_sq def __find_ions(self) -> List[Atom3D]: metal_atom_names",
"in candidates: if any([group.issuperset(candidate) for group in groups]): continue groups.append(candidate) return sorted([sorted(group) for",
"return ONZ.O_PLUS elif order == (3, 2, 1): return ONZ.O_MINUS elif order ==",
"structure3d: Structure3D quadruplexes: List[Quadruplex] = field(init=False) def __post_init__(self): self.quadruplexes = self.__find_quadruplexes() def __find_quadruplexes(self):",
"in self.tetrads: for nt in tetrad.nucleotides: for atom in nt.atoms: distance = numpy.linalg.norm(ion.coordinates()",
"self.nucleotides))}' @dataclass class Loop: nucleotides: List[Residue3D] loop_type: Optional[LoopType] def __str__(self): return f' {self.loop_type.value",
"list(map(lambda nt: nt.index, self.tetrad2_nts_best_order)) # count directions 5' -> 3' as +1 or",
"self.no_reorder: self.__find_best_chain_order() self.sequence, self.line1, self.line2, self.shifts = self.__generate_twoline_dotbracket() self.ions = self.__find_ions() self.__assign_ions_to_tetrads() def",
"filter(lambda x: x != i, self.base_pair_graph[i]): for k in filter(lambda x: x not",
"self.tetrad_pairs: ti, tj = tp.tetrad1, tp.tetrad2 if not helix_tetrads: helix_tetrads.append(ti) score = self.tetrad_scores[helix_tetrads[-1]][tj][0]",
"score_sequential = sum(score_sequential) score_stacking = sum(score_stacking) if (score, score_sequential, score_stacking) > (best_score, best_score_sequential,",
"pass elif order == (self.nt2, self.nt3, self.nt4, self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41 =",
"TODO: verify threshold of 6A between an ion and tetrad channel if min_distance",
"range(1, len(tetrad_nucleotides)): nprev = tetrad_nucleotides[i - 1] ncur = tetrad_nucleotides[i] if ncur.index -",
"distance min_tetrad = tetrad # TODO: verify threshold of 6A between an ion",
"self.structure3d.residues), key=lambda nt: nt.index): if chain and chain != nt.chain: sequence += '-'",
"elif order == (self.nt2, self.nt1, self.nt4, self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_12.reverse(),",
"nt1, nt2 = sorted([pair.nt1, pair.nt2]) dotbracket[nt1] = opening[order] dotbracket[nt2] = closing[order] sequence =",
"l)] pair_41 = self.base_pair_dict[(l, i)] tetrads.append(Tetrad(i, j, k, l, pair_12, pair_23, pair_34, pair_41))",
"return list(filter(check_pair, self.tetrad_pairs)) def __str__(self): builder = '' if len(self.tetrads) > 1: builder",
"= self.pair_34, self.pair_41, self.pair_12, self.pair_23 else: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt4, self.nt1,",
"this dict has all classes mapped to fingerprints gba_classes = { 'aass': GbaTetradClassification.Ia,",
"nt.index) for i in range(1, len(tetrad_nucleotides)): nprev = tetrad_nucleotides[i - 1] ncur =",
"== nprev.chain: for tract in self.tracts: if nprev in tract.nucleotides and ncur in",
"in self.tracts: if nprev in tract.nucleotides and ncur in tract.nucleotides: break else: nts",
"def __classify_by_gba(self) -> Optional[GbaTetradClassification]: \"\"\" See: <NAME>. (2007). Geometric Formalism for DNA Quadruplex",
"= set() for t in self.tetrads: gba = t.gba_class if gba is not",
"graph[ti].append(tj) graph[tj].append(ti) # remove tetrad which conflicts the most with others # in",
"{self.nt3.full_name} {self.nt4.full_name} ' \\ f'{self.pair_12.lw.value} {self.pair_23.lw.value} {self.pair_34.lw.value} {self.pair_41.lw.value} ' \\ f'{self.onz.value} {self.gba_class.value} '",
"reverse=True) if len(graph[candidates[0]]) > 0: tetrads.remove(candidates[0]) else: break return sorted(tetrads, key=lambda t: min(map(lambda",
"self.stacked[self.tetrad1.nt4] ) self.direction = self.__determine_direction() self.rise = self.__calculate_rise() self.twist = self.__calculate_twist() def __determine_direction(self)",
"set() for t in self.tetrads: gba = t.gba_class if gba is not None:",
"is None for t in self.tetrads]): return None counter = Counter([t.onz.value[0] for t",
"= False for i, j in itertools.combinations(range(len(candidates)), 2): qi, qj = candidates[i], candidates[j]",
"1: return True return False def center_of_mass(atoms): coords = [atom.coordinates() for atom in",
"= Counter([t.onz.value[1] for t in self.tetrads]) plus_minus, support = counter.most_common()[0] if support !=",
"= counter.most_common()[0] if support != len(self.tetrads): onz = 'M' counter = Counter([tp.direction.value[0] for",
"= 0 best_order = tj.nucleotides n1, n2, n3, n4 = tj.nucleotides viable_permutations =",
"if tetrads: if tetrad.chains().isdisjoint(tetrads[-1].chains()): quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) tetrads = list() tetrads.append(tetrad) quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads),",
"ion in ions])}]') return 'ions_outside=' + ' '.join(result) return '' @dataclass class TetradPair:",
"- direction return Direction.antiparallel return Direction.hybrid def __calculate_rise(self) -> float: t1 = self.tetrad1.outer_and_inner_atoms()",
"<gh_stars>0 import itertools import logging import math import os import string import subprocess",
"score_sequential = [1 if is_next_sequentially(nts1[i], nts2[i]) else 0 for i in range(4)] score",
"nt.chain: sequence += '-' structure += '-' shift_value += 1 sequence += nt.one_letter_name",
"conflicts = defaultdict(list) for pi, pj in itertools.combinations(queue, 2): if pi.conflicts_with(pj): conflicts[pi].append(pj) conflicts[pj].append(pi)",
"residue.atoms: if atom.atomName.upper() in metal_atom_names: coordinates = tuple(atom.coordinates()) if coordinates not in used:",
"tetrad in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) sequence, line1, shifts = self.__elimination_conflicts(layer1) _,",
"= self.__detect_loop_type(nprev, ncur) loops.append(Loop(nts, loop_type)) return loops def __detect_loop_type(self, nt_first: Residue3D, nt_last: Residue3D)",
"[[self.tetrads[0].nt1], [self.tetrads[0].nt2], [self.tetrads[0].nt3], [self.tetrads[0].nt4]] if len(self.tetrad_pairs) > 0: for tetrad_pair in self.tetrad_pairs: nt_dict",
"structure3d: Structure3D, strict: bool, no_reorder: bool, stacking_mismatch: int) -> Analysis: return Analysis(structure2d, structure3d,",
"self.__calculate_twist() def __determine_direction(self) -> Direction: indices1 = list(map(lambda nt: nt.index, self.tetrad1.nucleotides)) indices2 =",
"gba_classes = { 'aass': GbaTetradClassification.Ia, 'ssaa': GbaTetradClassification.Ib, 'asas': GbaTetradClassification.IIa, 'sasa': GbaTetradClassification.IIb, 'asaa': GbaTetradClassification.IIIa,",
"if j - i > 0 else -1 for i, j in zip(indices1,",
"= field(init=False) gba_classes: List[GbaQuadruplexClassification] = field(init=False) tracts: List[Tract] = field(init=False) loops: List[Loop] =",
"List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D quadruplexes: List[Quadruplex] = field(init=False) def __post_init__(self): self.quadruplexes =",
"field(init=False) stacking_graph: Dict[Residue3D, List[Residue3D]] = field(init=False) tetrads: List[Tetrad] = field(init=False) tetrad_scores: Dict[Tetrad, Dict[Tetrad,",
"List[BasePair3D]: return [base_pair for base_pair in self.base_pairs if base_pair.is_canonical()] @dataclass class Visualizer: analysis:",
"c in candidates] changed = True while changed: changed = False for i,",
"= [tp] if helix_tetrads: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) for tetrad in self.tetrads: if not",
"for nt in self.nucleotides] return numpy.linalg.norm(center_of_mass(outer) - center_of_mass(inner)) @property def nucleotides(self) -> Tuple[Residue3D,",
"h in self.helices: for t in h.tetrads: candidates.add(frozenset([t.nt1.chain, t.nt2.chain, t.nt3.chain, t.nt4.chain])) candidates =",
"int) -> List[TetradPair]: tetrads = list(self.tetrads) best_score = 0 best_order = tetrads for",
"= [] while queue: conflicts = defaultdict(list) for pi, pj in itertools.combinations(queue, 2):",
"ncur in tract.nucleotides: break else: nts = list(filter(lambda nt: nprev.index < nt.index <",
"Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]] = field(init=False) tetrad_pairs: List[TetradPair] = field(init=False) helices: List[Helix]",
"order = (stacked[ti.nt1], stacked[ti.nt2], stacked[ti.nt3], stacked[ti.nt4]) tj.reorder_to_match_other_tetrad(order) return tetrad_pairs def __find_helices(self): helices =",
"\".join(final_order)} ' f'{\" \".join(map(lambda onz: onz.value, classifications))}') self.tetrads = self.__find_tetrads(True) self.tetrad_scores = self.__calculate_tetrad_scores()",
"the loop between {nt_first} and {nt_last}') return None if tetrad_with_first == tetrad_with_last: #",
"tetrad_scores = defaultdict(dict) for ti, tj in itertools.combinations(self.tetrads, 2): nts1 = ti.nucleotides best_score",
"tetrad return None def __find_tract_with_nt(self, nt: Residue3D) -> Optional[Tract]: for tract in self.tracts:",
"self.base_pair_dict): pair_12 = self.base_pair_dict[(i, j)] pair_23 = self.base_pair_dict[(j, k)] pair_34 = self.base_pair_dict[(k, l)]",
"best_score: best_score = score best_order = order if best_score == (len(self.tetrads) - 1)",
"3' as +1 or -1 counter = Counter(1 if j - i >",
"= i i += 1 if len(self.tetrad_pairs) > 0: self.tetrad_pairs[0].tetrad1.reorder_to_match_5p_3p() for tp in",
"min_nt = min_tetrad.nt1 for tetrad in self.tetrads: for nt in tetrad.nucleotides: for atom",
"c2 in chain_order: chain_pairs.append([c1, c2]) sum_sq = 0 for c1, c2 in chain_pairs:",
"tetrad in self.tetrads: if nt in tetrad.nucleotides: return tetrad return None def __find_tract_with_nt(self,",
"for tetrad_pair in self.tetrad_pairs: nt_dict = { tetrad_pair.tetrad1.nt1: tetrad_pair.tetrad2_nts_best_order[0], tetrad_pair.tetrad1.nt2: tetrad_pair.tetrad2_nts_best_order[1], tetrad_pair.tetrad1.nt3: tetrad_pair.tetrad2_nts_best_order[2],",
"min_tetrad = tetrad # TODO: verify threshold of 6A between an ion and",
"= '' shifts = dict() shift_value = 0 chain = None for nt",
"2): return ONZ.N_PLUS elif order == (2, 3, 1): return ONZ.N_MINUS elif order",
"return list(map(lambda residue: residue.outermost_atom, self.nucleotides)) + \\ list(map(lambda residue: residue.innermost_atom, self.nucleotides)) def __ions_channel_str(self)",
"tetrad_pair in self.tetrad_pairs]: if tetrads: if tetrad.chains().isdisjoint(tetrads[-1].chains()): quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) tetrads = list()",
"order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D]): if order == (self.nt1, self.nt2, self.nt3, self.nt4): pass",
"for i in range(1, len(best_order)): ti, tj = best_order[i - 1], best_order[i] score",
"nt: nt.index, t.nucleotides))) def __calculate_tetrad_scores(self) \\ -> Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]]: def",
"self.nt4, self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse() elif order",
"self.base_pair_dict[(k, l)] pair_41 = self.base_pair_dict[(l, i)] tetrads.append(Tetrad(i, j, k, l, pair_12, pair_23, pair_34,",
"for t in self.tetrads: gba = t.gba_class if gba is not None: gbas.add(gba.value[:-1])",
"tetrad min_nt = nt # TODO: verify threshold of 3A between an ion",
"in ions_outside.items(): tetrad, residue = pair tetrad.ions_outside[residue] = ions def __generate_twoline_dotbracket(self) -> Tuple[str,",
"field(init=False) line2: str = field(init=False) shifts: Dict[Residue3D, int] = field(init=False) def __post_init__(self): self.base_pairs",
"x: GbaQuadruplexClassification[x], gbas)) def __find_tracts(self) -> List[Tract]: tracts = [[self.tetrads[0].nt1], [self.tetrads[0].nt2], [self.tetrads[0].nt3], [self.tetrads[0].nt4]]",
"removed = [] while queue: conflicts = defaultdict(list) for pi, pj in itertools.combinations(queue,",
"tie, remove one which has the worst planarity deviation candidates = sorted(tetrads, key=lambda",
"field(init=False) loop_class: Optional[LoopClassification] = field(init=False) def __post_init__(self): self.onzm = self.__classify_onzm() self.gba_classes = self.__classify_by_gba()",
"numpy.linalg.norm(ion.coordinates() - atom.coordinates()) if distance < min_distance: min_distance = distance min_tetrad = tetrad",
"removed = removed, [] order += 1 opening = '([{<' + string.ascii_uppercase closing",
"Helix: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D quadruplexes: List[Quadruplex] = field(init=False) def __post_init__(self):",
"in self.tetrad_pairs]: if tetrads: if tetrad.chains().isdisjoint(tetrads[-1].chains()): quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) tetrads = list() tetrads.append(tetrad)",
"groups]): continue groups.append(candidate) return sorted([sorted(group) for group in groups], key=lambda x: x[0]) def",
"ions_channel = defaultdict(list) ions_outside = defaultdict(list) for ion in self.ions: min_distance = math.inf",
"list(pairs) removed = [] while queue: conflicts = defaultdict(list) for pi, pj in",
"Loop: nucleotides: List[Residue3D] loop_type: Optional[LoopType] def __str__(self): return f' {self.loop_type.value if self.loop_type else",
"not None else \"R\"}' builder += f' {\",\".join(map(lambda gba: gba.value, self.gba_classes))}' if self.loop_class:",
"Formalism for DNA Quadruplex Folding. Chemistry - A European Journal, 13(35), 9738–9745. https://doi.org/10.1002/chem.200701255",
"self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse() elif order == (self.nt3, self.nt2, self.nt1, self.nt4): self.pair_12, self.pair_23, self.pair_34,",
"{\" \".join(map(lambda c: c.value, classifications))}') onz_score = sum(c.score() for c in classifications) chain_order_score",
"order def __classify_onz(self) -> ONZ: # transform into (0, 1, 2, 3) ni,",
"chain_order and c2 in chain_order: chain_pairs.append([c1, c2]) sum_sq = 0 for c1, c2",
"1: builder += ' single tetrad\\n' builder += str(self.tetrads[0]) else: builder += f'",
"= [ti] candidates = set(self.tetrads) - {ti} while candidates: tj = max([tj for",
"pair_41 = self.base_pair_dict[(l, i)] tetrads.append(Tetrad(i, j, k, l, pair_12, pair_23, pair_34, pair_41)) #",
"filter(lambda x: x not in (i, j), self.graph[j]): for l in filter(lambda x:",
"nprev.chain: for tract in self.tracts: if nprev in tract.nucleotides and ncur in tract.nucleotides:",
"import string import subprocess import tempfile from collections import defaultdict, Counter from dataclasses",
"nl)) ni, nj, nk, nl = (indices.index(x) for x in (ni, nj, nk,",
"[(n1, n2, n3, n4), (n2, n3, n4, n1), (n3, n4, n1, n2), (n4,",
"and chain != nt.chain: sequence += '-' structure += '-' shift_value += 1",
"tract.nucleotides: return tract return None def __detect_loop_sign(self, first: Residue3D, last: Residue3D, tetrad: Tetrad)",
"'sssa': GbaTetradClassification.IVb, 'aasa': GbaTetradClassification.Va, 'ssas': GbaTetradClassification.Vb, 'assa': GbaTetradClassification.VIa, 'saas': GbaTetradClassification.VIb, 'asss': GbaTetradClassification.VIIa, 'saaa':",
"in loop_classes: logging.error(f'Unknown loop classification: {fingerprint}') return None subtype = 'a' if self.loops[0",
"nk, nl)) ni, nj, nk, nl = (indices.index(x) for x in (ni, nj,",
"@dataclass class TetradPair: tetrad1: Tetrad tetrad2: Tetrad stacked: Dict[Residue3D, Residue3D] tetrad2_nts_best_order: Tuple[Residue3D, Residue3D,",
"__determine_direction(self) -> Direction: indices1 = list(map(lambda nt: nt.index, self.tetrad1.nucleotides)) indices2 = list(map(lambda nt:",
"order == (1, 2, 3): return ONZ.O_PLUS elif order == (3, 2, 1):",
"return math.degrees(numpy.arccos(numpy.clip(numpy.dot(v1, v2), -1.0, 1.0))) def __str__(self): return f' direction={self.direction.value} rise={round(self.rise, 2)} twist={round(self.twist,",
"main check if pair.nt1 == first and pair.nt2 == last: if pair.score() <",
"quadruplex in self.quadruplexes: builder += str(quadruplex) elif len(self.tetrads) == 1: builder += 'single",
"0 best_score_stacking = 0 best_order = tj.nucleotides n1, n2, n3, n4 = tj.nucleotides",
"4-letter string made of 's' for syn or 'a' for anti fingerprint =",
"nt in self.structure3d.residues: if nt.chain == chain: nt.index = i i += 1",
"loop in self.loops]): return None loop_classes = { 'ppp': '1', 'ppl': '2', 'plp':",
"Residue3D, Residue3D] = field(init=False) direction: Direction = field(init=False) rise: float = field(init=False) twist:",
"= sorted(gbas, key=lambda gba: roman_numerals.get(gba, 100)) return list(map(lambda x: GbaQuadruplexClassification[x], gbas)) def __find_tracts(self)",
"return self.nt1, self.nt2, self.nt3, self.nt4 def __hash__(self): return hash(frozenset([self.nt1, self.nt2, self.nt3, self.nt4])) def",
"'13' } fingerprint = ''.join([loop.loop_type.value[0] for loop in self.loops]) if fingerprint not in",
"= self.analysis.structure3d.residues shifts = self.analysis.shifts helix = tempfile.NamedTemporaryFile('w+', suffix='.helix') helix.write(f'#{len(self.analysis.sequence) + 1}\\n') helix.write('i\\tj\\tlength\\tvalue\\n')",
"len(chains) > 1: for permutation in itertools.permutations(chains): self.__reorder_chains(permutation) classifications = [t.onz for h",
"indices1 = list(map(lambda nt: nt.index, self.tetrad1.nucleotides)) indices2 = list(map(lambda nt: nt.index, self.tetrad2_nts_best_order)) #",
"tetrad, residue = pair tetrad.ions_outside[residue] = ions def __generate_twoline_dotbracket(self) -> Tuple[str, str, str,",
"helix_tetrads: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) for tetrad in self.tetrads: if not any([tetrad in helix.tetrads",
"is_disjoint(self, other) -> bool: return frozenset(self.nucleotides).isdisjoint(frozenset(other.nucleotides)) def center(self) -> numpy.ndarray: return center_of_mass(self.outer_and_inner_atoms()) def",
"Analysis: structure2d: Structure2D structure3d: Structure3D strict: bool no_reorder: bool stacking_mismatch: int base_pairs: List[BasePair3D]",
"in (i, j, k) and x in self.graph[i], self.graph[k]): if Tetrad.is_valid(i, j, k,",
"typing import Dict, Iterable, List, Tuple, Optional, Set import numpy from eltetrado.model import",
"is_next_by_stacking(nt1: Residue3D, nt2: Residue3D) -> bool: return nt2 in self.stacking_graph.get(nt1, []) def is_next_sequentially(nt1:",
"bool: return nt1.chain == nt2.chain and abs(nt1.index - nt2.index) == 1 tetrad_scores =",
"self.nt3, self.nt4])) def __str__(self): return f' ' \\ f'{self.nt1.full_name} {self.nt2.full_name} {self.nt3.full_name} {self.nt4.full_name} '",
"0 order = [ti] candidates = set(self.tetrads) - {ti} while candidates: tj =",
"in chain_order and c2 in chain_order: chain_pairs.append([c1, c2]) sum_sq = 0 for c1,",
"shifts = dict() shift_value = 0 chain = None for nt in sorted(filter(lambda",
"[], [] for tetrad in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) helix1 = self.__to_helix(layer1,",
"1: builder += f'n4-helix with {len(self.tetrads)} tetrads\\n' for quadruplex in self.quadruplexes: builder +=",
"self.tetrads for nt in tetrad.nucleotides], key=lambda nt: nt.index) for i in range(1, len(tetrad_nucleotides)):",
"in coords) ys = (coord[1] for coord in coords) zs = (coord[2] for",
"defaultdict, Counter from dataclasses import dataclass, field from typing import Dict, Iterable, List,",
"for tp in self.tetrad_pairs: ti, tj = tp.tetrad1, tp.tetrad2 if not helix_tetrads: helix_tetrads.append(ti)",
"return None def __detect_loop_sign(self, first: Residue3D, last: Residue3D, tetrad: Tetrad) -> Optional[str]: for",
"None def __find_tetrad_with_nt(self, nt: Residue3D) -> Optional[Tetrad]: for tetrad in self.tetrads: if nt",
"__calculate_twist(self) -> float: nt1_1, nt1_2, _, _ = self.tetrad1.nucleotides nt2_1, nt2_2, _, _",
"fingerprint != 'dpd' else 1].loop_type.value[-1] == '-' else 'b' return LoopClassification.from_value(f'{loop_classes[fingerprint]}{subtype}') def __str__(self):",
"as +1 or -1 counter = Counter(1 if j - i > 0",
"with others # in case of a tie, remove one which has the",
"chain_order_score) if score < best_score: best_score = score best_permutation = permutation elif score",
"plus_minus = '*' return ONZM.from_value(f'{onz}{direction}{plus_minus}') def __classify_by_gba(self) -> List[GbaQuadruplexClassification]: gbas = set() for",
"List, Tuple, Optional, Set import numpy from eltetrado.model import Atom3D, Structure3D, Structure2D, BasePair3D,",
"list(map(lambda nt: nt.index, self.tetrad1.nucleotides)) indices2 = list(map(lambda nt: nt.index, self.tetrad2_nts_best_order)) # count directions",
"ion, because it is too far from any tetrad (distance={min_distance})') for tetrad, ions",
"da Silva's classification are valid in 5'-3' order self.onz = self.__classify_onz() self.gba_class =",
"3): return ONZ.Z_PLUS elif order == (3, 1, 2): return ONZ.Z_MINUS raise RuntimeError(f'Impossible",
"best_score = chains, (1e10, 1e10) if len(chains) > 1: for permutation in itertools.permutations(chains):",
"x[0]) def __reorder_chains(self, chain_order: Iterable[str]): i = 1 for chain in chain_order: for",
"for c1, c2 in chain_pairs: sum_sq += (chain_order.index(c1) - chain_order.index(c2)) ** 2 return",
"== (self.nt1, self.nt2, self.nt3, self.nt4): pass elif order == (self.nt2, self.nt3, self.nt4, self.nt1):",
"if pair.nt1 == last and pair.nt2 == first: if pair.score() < pair.reverse().score(): return",
"nk, nl) if nmin == ni: pass elif nmin == nj: self.nt1, self.nt2,",
"self.tetrad1.nucleotides nt2_1, nt2_2, _, _ = self.tetrad2_nts_best_order v1 = nt1_1.find_atom(\"C1'\").coordinates() - nt1_2.find_atom(\"C1'\").coordinates() v1",
"[nt.innermost_atom for nt in self.nucleotides] return numpy.linalg.norm(center_of_mass(outer) - center_of_mass(inner)) @property def nucleotides(self) ->",
"LoopType.from_value(f'lateral{sign}') return LoopType.diagonal tract_with_last = self.__find_tract_with_nt(nt_last) if tract_with_last is not None: # search",
"itertools.combinations(range(len(candidates)), 2): qi, qj = candidates[i], candidates[j] if not qi.isdisjoint(qj): qi.update(qj) del candidates[j]",
"__find_tract_with_nt(self, nt: Residue3D) -> Optional[Tract]: for tract in self.tracts: if nt in tract.nucleotides:",
"key=lambda tk: self.tetrad_scores[ti][tk][0]) score += self.tetrad_scores[ti][tj][0] order.append(tj) candidates.remove(tj) ti = tj if score",
"return list({nt.chain: 0 for nt in sorted(only_nucleic_acids, key=lambda nt: nt.index)}.keys()) def canonical(self) ->",
"(2, 1, 3): return ONZ.Z_PLUS elif order == (3, 1, 2): return ONZ.Z_MINUS",
"self.ions_channel]) return '' def __ions_outside_str(self) -> str: if self.ions_outside: result = [] for",
"f'{tract}\\n' if self.loops: builder += '\\n Loops:\\n' for loop in self.loops: builder +=",
"i = 1 for chain in chain_order: for nt in self.structure3d.residues: if nt.chain",
"self.pair_34, self.pair_41, self.pair_12, self.pair_23 else: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt4, self.nt1, self.nt2,",
"in (GlycosidicBond.syn, GlycosidicBond.anti) for nt in self.nucleotides]): return None # this will create",
"helix1 = self.__to_helix(layer1, self.analysis.canonical() if self.complete2d else []) helix2 = self.__to_helix(layer2) currdir =",
"tetrad_with_first = self.__find_tetrad_with_nt(nt_first) tetrad_with_last = self.__find_tetrad_with_nt(nt_last) if tetrad_with_first is None or tetrad_with_last is",
"tetrads.remove(candidates[0]) else: break return sorted(tetrads, key=lambda t: min(map(lambda nt: nt.index, t.nucleotides))) def __calculate_tetrad_scores(self)",
"self.graph: for j in filter(lambda x: x != i, self.graph[i]): for k in",
"-> Optional[Tract]: for tract in self.tracts: if nt in tract.nucleotides: return tract return",
"no_reorder, stacking_mismatch) def has_tetrad(structure2d: Structure2D, structure3d: Structure3D) -> bool: structure = AnalysisSimple(structure2d, structure3d)",
"self.stacked[self.tetrad1.nt1], self.stacked[self.tetrad1.nt2], self.stacked[self.tetrad1.nt3], self.stacked[self.tetrad1.nt4] ) self.direction = self.__determine_direction() self.rise = self.__calculate_rise() self.twist =",
"coord in coords) ys = (coord[1] for coord in coords) zs = (coord[2]",
"len(self.tetrad_pairs) == 0: return [Quadruplex(self.tetrads, [], self.structure3d)] quadruplexes = list() tetrads = list()",
"run.returncode == 0: print('\\nPlot:', output_pdf) else: logging.error(f'Failed to prepare visualization, reason:\\n {run.stderr.decode()}') def",
"BasePair3D] = structure3d.base_pair_dict(structure2d) def has_tetrads(self): tetrads = set() for i in self.graph: for",
"'-' else 'b' return LoopClassification.from_value(f'{loop_classes[fingerprint]}{subtype}') def __str__(self): builder = '' if len(self.tetrads) ==",
"self.base_pair_dict[(j, k)] pair_34 = self.base_pair_dict[(k, l)] pair_41 = self.base_pair_dict[(l, i)] tetrads.append(Tetrad(i, j, k,",
"helix_tetrad_pairs = [] for tp in self.tetrad_pairs: ti, tj = tp.tetrad1, tp.tetrad2 if",
"nt in tetrad.nucleotides: return tetrad return None def __find_tract_with_nt(self, nt: Residue3D) -> Optional[Tract]:",
"score_stacking = [1 if is_next_by_stacking(nts1[i], nts2[i]) else 0 for i in range(4)] score_sequential",
"loop_classes = { 'ppp': '1', 'ppl': '2', 'plp': '3', 'lpp': '4', 'pdp': '5',",
"** 2 return sum_sq def __find_ions(self) -> List[Atom3D]: metal_atom_names = set([ion.value.upper() for ion",
"nt.atoms: distance = numpy.linalg.norm(ion.coordinates() - atom.coordinates()) if distance < min_distance: min_distance = distance",
"= p.nt2.chain if c1 != c2 and c1 in chain_order and c2 in",
"'M' counter = Counter([tp.direction.value[0] for tp in self.tetrad_pairs]) direction, support = counter.most_common()[0] if",
"+= f' {self.onzm.value if self.onzm is not None else \"R\"}' builder += f'",
"builder = '' if len(self.tetrads) > 1: builder += f'n4-helix with {len(self.tetrads)} tetrads\\n'",
"if len(self.tetrad_pairs) == 0: return [Quadruplex(self.tetrads, [], self.structure3d)] quadruplexes = list() tetrads =",
"self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() def __group_related_chains(self) -> List[List[str]]: candidates = set()",
"' \\ f'{self.pair_12.lw.value} {self.pair_23.lw.value} {self.pair_34.lw.value} {self.pair_41.lw.value} ' \\ f'{self.onz.value} {self.gba_class.value} ' \\ f'planarity={round(self.planarity_deviation,",
"numpy.ndarray: return center_of_mass(self.outer_and_inner_atoms()) def outer_and_inner_atoms(self) -> List[Atom3D]: return list(map(lambda residue: residue.outermost_atom, self.nucleotides)) +",
"return [Quadruplex(self.tetrads, [], self.structure3d)] quadruplexes = list() tetrads = list() for tetrad in",
"= [t.onz for h in self.helices for t in h.tetrads] logging.debug( f'Checking reorder:",
"def nucleotides(self) -> Tuple[Residue3D, Residue3D, Residue3D, Residue3D]: return self.nt1, self.nt2, self.nt3, self.nt4 def",
"t.planarity_deviation), reverse=True) if len(graph[candidates[0]]) > 0: tetrads.remove(candidates[0]) else: break return sorted(tetrads, key=lambda t:",
"nt2: Residue3D) -> bool: return nt1.chain == nt2.chain and abs(nt1.index - nt2.index) ==",
"self.nt1 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif nmin ==",
"'ldl': '11', 'dpd': '12', 'ldp': '13' } fingerprint = ''.join([loop.loop_type.value[0] for loop in",
"result = [] for residue, ions in self.ions_outside.items(): result.append(f'{residue.full_name}: [{\",\".join([ion.atomName for ion in",
"def __calculate_twist(self) -> float: nt1_1, nt1_2, _, _ = self.tetrad1.nucleotides nt2_1, nt2_2, _,",
"elif order == (3, 1, 2): return ONZ.Z_MINUS raise RuntimeError(f'Impossible combination: {ni} {nj}",
"# diagonal or laterals happen when first and last nt of a loop",
"Dict[Tuple[Residue3D, Residue3D], BasePair3D] = field(init=False) stacking_graph: Dict[Residue3D, List[Residue3D]] = field(init=False) tetrads: List[Tetrad] =",
"[] for i in self.base_pair_graph: for j in filter(lambda x: x != i,",
"in range(4)} stacked.update({v: k for k, v in stacked.items()}) tetrad_pairs.append(TetradPair(ti, tj, stacked)) order",
"0 for nt in sorted(only_nucleic_acids, key=lambda nt: nt.index)}.keys()) def canonical(self) -> List[BasePair3D]: return",
"h.tetrads: for p in [t.pair_12, t.pair_23, t.pair_34, t.pair_41]: c1 = p.nt1.chain c2 =",
"{len(self.tetrads)} tetrads\\n' for quadruplex in self.quadruplexes: builder += str(quadruplex) elif len(self.tetrads) == 1:",
"last and pair.nt2 == first: if pair.score() < pair.reverse().score(): return '+' return '-'",
"onz, support = counter.most_common()[0] if support != len(self.tetrads): onz = 'M' counter =",
"'pdp': '5', 'lll': '6', 'llp': '7', 'lpl': '8', 'pll': '9', 'pdl': '10', 'ldl':",
"= [] used = set() for residue in self.structure3d.residues: for atom in residue.atoms:",
"# two in +, one in - direction return Direction.antiparallel return Direction.hybrid def",
"pair_41)) # build graph of tetrads while tetrads: graph = defaultdict(list) for (ti,",
"tetrads for ti in tetrads: score = 0 order = [ti] candidates =",
"counter = Counter([t.onz.value[1] for t in self.tetrads]) plus_minus, support = counter.most_common()[0] if support",
"twist: float = field(init=False) def __post_init__(self): self.tetrad2_nts_best_order = ( self.stacked[self.tetrad1.nt1], self.stacked[self.tetrad1.nt2], self.stacked[self.tetrad1.nt3], self.stacked[self.tetrad1.nt4]",
"tetrads = list() for tetrad in [self.tetrad_pairs[0].tetrad1] + [tetrad_pair.tetrad2 for tetrad_pair in self.tetrad_pairs]:",
"sum_sq += (chain_order.index(c1) - chain_order.index(c2)) ** 2 return sum_sq def __find_ions(self) -> List[Atom3D]:",
"coord in coords) return numpy.array((sum(xs) / len(coords), sum(ys) / len(coords), sum(zs) / len(coords)))",
"in self.tetrad_pairs]) direction, support = counter.most_common()[0] if support != len(self.tetrad_pairs): direction = 'h'",
"self.nt3, self.nt4, self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif",
"sum_sq def __find_ions(self) -> List[Atom3D]: metal_atom_names = set([ion.value.upper() for ion in Ion]) ions",
"@dataclass class Visualizer: analysis: Analysis tetrads: List[Tetrad] complete2d: bool onz_dict: Dict[BasePair3D, ONZ] =",
"LoopType.diagonal tract_with_last = self.__find_tract_with_nt(nt_last) if tract_with_last is not None: # search along the",
"if nt in tetrad.nucleotides: return tetrad return None def __find_tract_with_nt(self, nt: Residue3D) ->",
"structure2d: Structure2D, structure3d: Structure3D): self.pairs: List[BasePair3D] = structure3d.base_pairs(structure2d) self.graph: Dict[Residue3D, List[Residue3D]] = structure3d.base_pair_graph(structure2d)",
"__calculate_rise(self) -> float: t1 = self.tetrad1.outer_and_inner_atoms() t2 = self.tetrad2.outer_and_inner_atoms() return numpy.linalg.norm(center_of_mass(t1) - center_of_mass(t2))",
"2): qi, qj = candidates[i], candidates[j] if not qi.isdisjoint(qj): qi.update(qj) del candidates[j] changed",
"order self.onz = self.__classify_onz() self.gba_class = self.__classify_by_gba() def reorder_to_match_other_tetrad(self, order: Tuple[Residue3D, Residue3D, Residue3D,",
"nt in self.nucleotides]) # this dict has all classes mapped to fingerprints gba_classes",
"self.tracts = self.__find_tracts() self.loops = self.__find_loops() self.loop_class = self.__classify_by_loops() def __classify_onzm(self) -> Optional[ONZM]:",
"nts1, best_order) tetrad_scores[tj][ti] = (best_score, best_order, nts1) return tetrad_scores def __find_tetrad_pairs(self, stacking_mismatch: int)",
"{order}') self.nt1, self.nt2, self.nt3, self.nt4 = order def __classify_onz(self) -> ONZ: # transform",
"self.__find_tracts() self.loops = self.__find_loops() self.loop_class = self.__classify_by_loops() def __classify_onzm(self) -> Optional[ONZM]: if len(self.tetrads)",
"tetrad_with_last: # diagonal or laterals happen when first and last nt of a",
"Webba da Silva or n/a \"\"\" # without all nucleotides having a valid",
"print('\\nPlot:', output_pdf) else: logging.error(f'Failed to prepare visualization, reason:\\n {run.stderr.decode()}') def __to_helix(self, layer: List[BasePair3D],",
"Residue3D, nt2: Residue3D) -> bool: return nt2 in self.stacking_graph.get(nt1, []) def is_next_sequentially(nt1: Residue3D,",
"for loop in self.loops]): return None loop_classes = { 'ppp': '1', 'ppl': '2',",
"def __filter_tetrad_pairs(self, tetrads: List[Tetrad]) -> List[TetradPair]: chains = set() for tetrad in tetrads:",
"str(self.tetrads[0]) else: builder += f' {self.onzm.value if self.onzm is not None else \"R\"}'",
"self.pair_23 else: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt4, self.nt1, self.nt2, self.nt3 self.pair_12, self.pair_23,",
"(n2, n1, n4, n3)] for nts2 in viable_permutations: score_stacking = [1 if is_next_by_stacking(nts1[i],",
"3.0: ions_outside[(min_tetrad, min_nt)].append(ion) continue logging.debug(f'Skipping an ion, because it is too far from",
"[]) helix2 = self.__to_helix(layer2) currdir = os.path.dirname(os.path.realpath(__file__)) output_pdf = f'{prefix}-{suffix}.pdf' run = subprocess.run([os.path.join(currdir,",
"self.helices: for t in h.tetrads: candidates.add(frozenset([t.nt1.chain, t.nt2.chain, t.nt3.chain, t.nt4.chain])) candidates = [set(c) for",
"tetrads\\n' for quadruplex in self.quadruplexes: builder += str(quadruplex) elif len(self.tetrads) == 1: builder",
"tetrad without stacking\\n' builder += str(self.tetrads[0]) return builder @dataclass class Analysis: structure2d: Structure2D",
"= self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif order == (self.nt3, self.nt4, self.nt1, self.nt2): self.pair_12,",
"Dict[Tuple[Residue3D, Residue3D], BasePair3D] = structure3d.base_pair_dict(structure2d) def has_tetrads(self): tetrads = set() for i in",
"= field(init=False) sequence: str = field(init=False) line1: str = field(init=False) line2: str =",
"self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse() elif order == (self.nt1, self.nt4, self.nt3, self.nt2): self.pair_12, self.pair_23,",
"= subprocess.run([os.path.join(currdir, 'quadraw.R'), fasta.name, helix1.name, helix2.name, output_pdf], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if run.returncode == 0:",
"not in loop_classes: logging.error(f'Unknown loop classification: {fingerprint}') return None subtype = 'a' if",
"self.pair_12.reverse() else: raise RuntimeError(f'Cannot apply order: {order}') self.nt1, self.nt2, self.nt3, self.nt4 = order",
"self.__calculate_rise() self.twist = self.__calculate_twist() def __determine_direction(self) -> Direction: indices1 = list(map(lambda nt: nt.index,",
"self.structure3d.base_pair_dict(self.structure2d, self.strict) self.stacking_graph = self.structure3d.stacking_graph(self.structure2d) self.tetrads = self.__find_tetrads(self.no_reorder) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs =",
"= self.base_pair_dict[(j, k)] pair_34 = self.base_pair_dict[(k, l)] pair_41 = self.base_pair_dict[(l, i)] tetrads.append(Tetrad(i, j,",
"for permutation in itertools.permutations(chains): self.__reorder_chains(permutation) classifications = [t.onz for h in self.helices for",
"1 for chain in chain_order: for nt in self.structure3d.residues: if nt.chain == chain:",
"h in self.helices for t in h.tetrads] logging.debug( f'Checking reorder: {\" \".join(permutation)} {\"",
"self.complete2d else []) helix2 = self.__to_helix(layer2) currdir = os.path.dirname(os.path.realpath(__file__)) output_pdf = f'{prefix}-{suffix}.pdf' run",
"1, ONZ.O_MINUS: 2, ONZ.N_PLUS: 3, ONZ.N_MINUS: 4, ONZ.Z_PLUS: 5, ONZ.Z_MINUS: 6} nucleotides =",
"nj, nk, nl = (nt.index for nt in self.nucleotides) indices = sorted((ni, nj,",
"i i += 1 if len(self.tetrad_pairs) > 0: self.tetrad_pairs[0].tetrad1.reorder_to_match_5p_3p() for tp in self.tetrad_pairs:",
"-> Optional[LoopType]: tetrad_with_first = self.__find_tetrad_with_nt(nt_first) tetrad_with_last = self.__find_tetrad_with_nt(nt_last) if tetrad_with_first is None or",
"for i, j in itertools.combinations(range(len(candidates)), 2): qi, qj = candidates[i], candidates[j] if not",
"'-' return None def __classify_by_loops(self) -> Optional[LoopClassification]: if len(self.loops) != 3 or any([loop.loop_type",
"1 if len(self.tetrad_pairs) > 0: self.tetrad_pairs[0].tetrad1.reorder_to_match_5p_3p() for tp in self.tetrad_pairs: order = (tp.stacked[tp.tetrad1.nt1],",
"nt2)].lw lw2 = pair_dictionary[(nt2, nt3)].lw lw3 = pair_dictionary[(nt3, nt4)].lw lw4 = pair_dictionary[(nt4, nt1)].lw",
"in self.base_pair_graph: for j in filter(lambda x: x != i, self.base_pair_graph[i]): for k",
"ti.is_disjoint(tj): graph[ti].append(tj) graph[tj].append(ti) # remove tetrad which conflicts the most with others #",
"tj.nucleotides viable_permutations = [(n1, n2, n3, n4), (n2, n3, n4, n1), (n3, n4,",
"in self.nucleotides]) def is_disjoint(self, other) -> bool: return frozenset(self.nucleotides).isdisjoint(frozenset(other.nucleotides)) def center(self) -> numpy.ndarray:",
"= field(init=False) tracts: List[Tract] = field(init=False) loops: List[Loop] = field(init=False) loop_class: Optional[LoopClassification] =",
"or any([loop.loop_type is None for loop in self.loops]): return None loop_classes = {",
"tetrad_pair.tetrad1.nt4: tetrad_pair.tetrad2_nts_best_order[3], } for i in range(4): tracts[i].append(nt_dict[tracts[i][-1]]) return [Tract(nts) for nts in",
"None or tetrad_with_last is None: logging.warning(f'Failed to classify the loop between {nt_first} and",
"return None counter = Counter([t.onz.value[0] for t in self.tetrads]) onz, support = counter.most_common()[0]",
"return {}, {} ions_channel = defaultdict(list) ions_outside = defaultdict(list) for ion in self.ions:",
"(i, j, k) and i in self.base_pair_graph[x], self.base_pair_graph[k]): if Tetrad.is_valid(i, j, k, l,",
"shifts def __elimination_conflicts(self, pairs: List[BasePair3D]) -> Tuple[str, str, Dict[Residue3D, int]]: orders = dict()",
"in itertools.combinations(range(len(candidates)), 2): qi, qj = candidates[i], candidates[j] if not qi.isdisjoint(qj): qi.update(qj) del",
"self.__group_related_chains() final_order = [] for chains in chain_groups: best_permutation, best_score = chains, (1e10,",
"{self.pair_34.lw.value} {self.pair_41.lw.value} ' \\ f'{self.onz.value} {self.gba_class.value} ' \\ f'planarity={round(self.planarity_deviation, 2)} ' \\ f'{self.__ions_channel_str()}",
"nj, nk, nl = (indices.index(x) for x in (ni, nj, nk, nl)) while",
"min_distance = distance min_tetrad = tetrad # TODO: verify threshold of 6A between",
"'sass': GbaTetradClassification.IIIb, 'aaas': GbaTetradClassification.IVa, 'sssa': GbaTetradClassification.IVb, 'aasa': GbaTetradClassification.Va, 'ssas': GbaTetradClassification.Vb, 'assa': GbaTetradClassification.VIa, 'saas':",
"nj, nk order = (nj, nk, nl) if order == (1, 2, 3):",
"self.gba_classes = self.__classify_by_gba() self.tracts = self.__find_tracts() self.loops = self.__find_loops() self.loop_class = self.__classify_by_loops() def",
"'h' counter = Counter([t.onz.value[1] for t in self.tetrads]) plus_minus, support = counter.most_common()[0] if",
"- nprev.index > 1 and ncur.chain == nprev.chain: for tract in self.tracts: if",
"' f'{\" \".join(map(lambda onz: onz.value, classifications))}') self.tetrads = self.__find_tetrads(True) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs",
"loop_class: Optional[LoopClassification] = field(init=False) def __post_init__(self): self.onzm = self.__classify_onzm() self.gba_classes = self.__classify_by_gba() self.tracts",
"class AnalysisSimple: def __init__(self, structure2d: Structure2D, structure3d: Structure3D): self.pairs: List[BasePair3D] = structure3d.base_pairs(structure2d) self.graph:",
"not in chain_order: nt.index = i i += 1 if len(self.tetrad_pairs) > 0:",
"+= 1 for nt in self.structure3d.residues: if nt.chain not in chain_order: nt.index =",
"== (3, 2, 1): return ONZ.O_MINUS elif order == (1, 3, 2): return",
"in self.quadruplexes: builder += str(quadruplex) elif len(self.tetrads) == 1: builder += 'single tetrad",
"ti = tj if score > best_score: best_score = score best_order = order",
"in itertools.combinations(queue, 2): if pi.conflicts_with(pj): conflicts[pi].append(pj) conflicts[pj].append(pi) if conflicts: pair, _ = max(conflicts.items(),",
"tj = max([tj for tj in candidates], key=lambda tk: self.tetrad_scores[ti][tk][0]) score += self.tetrad_scores[ti][tj][0]",
"builder += f'{loop}\\n' builder += '\\n' return builder @dataclass class Helix: tetrads: List[Tetrad]",
"self.nucleotides]}') return None return gba_classes[fingerprint] def __calculate_planarity_deviation(self) -> float: outer = [nt.outermost_atom for",
"gba_classes: List[GbaQuadruplexClassification] = field(init=False) tracts: List[Tract] = field(init=False) loops: List[Loop] = field(init=False) loop_class:",
"4: break tetrad_scores[ti][tj] = (best_score, nts1, best_order) tetrad_scores[tj][ti] = (best_score, best_order, nts1) return",
"= permutation elif score == best_score: # in case of a tie, pick",
"= sum(c.score() for c in classifications) chain_order_score = self.__chain_order_score(permutation) score = (onz_score, chain_order_score)",
"min_distance < 6.0: ions_channel[min_tetrad].append(ion) continue min_distance = math.inf min_tetrad = self.tetrads[0] min_nt =",
"Dict[Tuple[Tetrad, Residue3D], List[Atom3D]]]: if len(self.tetrads) == 0: return {}, {} ions_channel = defaultdict(list)",
"chain_order: nt.index = i i += 1 if len(self.tetrad_pairs) > 0: self.tetrad_pairs[0].tetrad1.reorder_to_match_5p_3p() for",
"def has_tetrads(self): tetrads = set() for i in self.graph: for j in filter(lambda",
"__classify_onzm(self) -> Optional[ONZM]: if len(self.tetrads) == 1: return None if any([t.onz is None",
"l, self.pair_dict): tetrads.add(frozenset([i, j, k, l])) if len(tetrads) > 1: return True return",
"= [] tetrad_nucleotides = sorted([nt for tetrad in self.tetrads for nt in tetrad.nucleotides],",
"self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() def __group_related_chains(self) -> List[List[str]]: candidates =",
"[] for tetrad in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) sequence, line1, shifts =",
"f'n4-helix with {len(self.tetrads)} tetrads\\n' for quadruplex in self.quadruplexes: builder += str(quadruplex) elif len(self.tetrads)",
"for i, j in zip(indices1, indices2)) direction, count = counter.most_common()[0] if count ==",
"- 1) * 4: break tetrad_pairs = [] for i in range(1, len(best_order)):",
"= tempfile.NamedTemporaryFile('w+', suffix='.fasta') fasta.write(f'>{prefix}-{suffix}\\n') fasta.write(self.analysis.sequence) fasta.flush() layer1, layer2 = [], [] for tetrad",
"self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif order == (self.nt3, self.nt4, self.nt1, self.nt2): self.pair_12, self.pair_23,",
"pair_dictionary[(nt3, nt4)].lw lw4 = pair_dictionary[(nt4, nt1)].lw for lw_i, lw_j in ((lw1, lw4), (lw2,",
"nt.index, t.nucleotides))) def __calculate_tetrad_scores(self) \\ -> Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]]: def is_next_by_stacking(nt1:",
"str, Dict[Residue3D, int]]: layer1, layer2 = [], [] for tetrad in self.tetrads: layer1.extend([tetrad.pair_12,",
"else: nts = list(filter(lambda nt: nprev.index < nt.index < ncur.index, self.structure3d.residues)) loop_type =",
"residue: residue.innermost_atom, self.nucleotides)) def __ions_channel_str(self) -> str: if self.ions_channel: return 'ions_channel=' + ','.join([atom.atomName",
"field(init=False) loops: List[Loop] = field(init=False) loop_class: Optional[LoopClassification] = field(init=False) def __post_init__(self): self.onzm =",
"= self.nt2, self.nt3, self.nt4, self.nt1 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41,",
"__assign_ions_to_tetrads(self) \\ -> Tuple[Dict[Tetrad, List[Atom3D]], Dict[Tuple[Tetrad, Residue3D], List[Atom3D]]]: if len(self.tetrads) == 0: return",
"+= f' n/a' builder += f' quadruplex with {len(self.tetrads)} tetrads\\n' builder += str(self.tetrad_pairs[0].tetrad1)",
"and an atom if min_distance < 3.0: ions_outside[(min_tetrad, min_nt)].append(ion) continue logging.debug(f'Skipping an ion,",
"self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() else: raise RuntimeError(f'Cannot apply order: {order}') self.nt1, self.nt2, self.nt3,",
"elif order == (self.nt4, self.nt3, self.nt2, self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34.reverse(),",
"def is_next_sequentially(nt1: Residue3D, nt2: Residue3D) -> bool: return nt1.chain == nt2.chain and abs(nt1.index",
"loop between {nt_first} and {nt_last}') return None def __find_tetrad_with_nt(self, nt: Residue3D) -> Optional[Tetrad]:",
"GlycosidicBond, ONZ, \\ GbaTetradClassification, Ion, Direction, LoopType, ONZM, GbaQuadruplexClassification, LoopClassification logging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"INFO\")) @dataclass(order=True)",
"def __group_related_chains(self) -> List[List[str]]: candidates = set() for h in self.helices: for t",
"syn or 'a' for anti fingerprint = ''.join([nt.chi_class.value[0] for nt in self.nucleotides]) #",
"qi, qj = candidates[i], candidates[j] if not qi.isdisjoint(qj): qi.update(qj) del candidates[j] changed =",
"Residue3D, nt4: Residue3D, pair_dictionary: Dict[Tuple[Residue3D, Residue3D], BasePair3D]) -> bool: lw1 = pair_dictionary[(nt1, nt2)].lw",
"= [], [] for tetrad in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) sequence, line1,",
"Residue3D, GlycosidicBond, ONZ, \\ GbaTetradClassification, Ion, Direction, LoopType, ONZM, GbaQuadruplexClassification, LoopClassification logging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"INFO\"))",
"field(init=False) direction: Direction = field(init=False) rise: float = field(init=False) twist: float = field(init=False)",
"for j in filter(lambda x: x != i, self.base_pair_graph[i]): for k in filter(lambda",
"self.tetrads = self.__find_tetrads(True) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() def",
"(onz_score, chain_order_score) if score < best_score: best_score = score best_permutation = permutation elif",
"Direction, LoopType, ONZM, GbaQuadruplexClassification, LoopClassification logging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"INFO\")) @dataclass(order=True) class Tetrad: @staticmethod def is_valid(nt1:",
"1: builder += 'single tetrad without stacking\\n' builder += str(self.tetrads[0]) return builder @dataclass",
"f'Chain order: {\" \".join(self.__chain_order())}\\n' for helix in self.helices: builder += str(helix) builder +=",
"[] for tetrad in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) helix1 = self.__to_helix(layer1, self.analysis.canonical()",
"gba_class: Optional[GbaTetradClassification] = field(init=False) planarity_deviation: float = field(init=False) ions_channel: List[Atom3D] = field(default_factory=list) ions_outside:",
"best_score == 4: break tetrad_scores[ti][tj] = (best_score, nts1, best_order) tetrad_scores[tj][ti] = (best_score, best_order,",
"(coord[0] for coord in coords) ys = (coord[1] for coord in coords) zs",
"score = sum([max(score_stacking[i], score_sequential[i]) for i in range(4)]) score_sequential = sum(score_sequential) score_stacking =",
"for tetrad_pair in self.tetrad_pairs]: if tetrads: if tetrad.chains().isdisjoint(tetrads[-1].chains()): quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) tetrads =",
"import defaultdict, Counter from dataclasses import dataclass, field from typing import Dict, Iterable,",
"def __determine_direction(self) -> Direction: indices1 = list(map(lambda nt: nt.index, self.tetrad1.nucleotides)) indices2 = list(map(lambda",
"count = counter.most_common()[0] if count == 4: # all in the same direction",
"quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) tetrads = list() tetrads.append(tetrad) quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) return quadruplexes def",
"in - direction return Direction.antiparallel return Direction.hybrid def __calculate_rise(self) -> float: t1 =",
"build graph of tetrads while tetrads: graph = defaultdict(list) for (ti, tj) in",
"counter.most_common()[0] if support != len(self.tetrad_pairs): direction = 'h' counter = Counter([t.onz.value[1] for t",
"pair_23 = self.base_pair_dict[(j, k)] pair_34 = self.base_pair_dict[(k, l)] pair_41 = self.base_pair_dict[(l, i)] tetrads.append(Tetrad(i,",
"= self.nt1, self.nt4, self.nt3, self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(),",
"self.nucleotides) indices = sorted((ni, nj, nk, nl)) ni, nj, nk, nl = (indices.index(x)",
"nts2[i]) else 0 for i in range(4)] score_sequential = [1 if is_next_sequentially(nts1[i], nts2[i])",
"without all nucleotides having a valid syn/anti, this classification is impossible if not",
"2)} ' \\ f'{self.__ions_channel_str()} ' \\ f'{self.__ions_outside_str()}\\n' def chains(self) -> Set[str]: return set([nt.chain",
"in self.tetrad_pairs: nt_dict = { tetrad_pair.tetrad1.nt1: tetrad_pair.tetrad2_nts_best_order[0], tetrad_pair.tetrad1.nt2: tetrad_pair.tetrad2_nts_best_order[1], tetrad_pair.tetrad1.nt3: tetrad_pair.tetrad2_nts_best_order[2], tetrad_pair.tetrad1.nt4: tetrad_pair.tetrad2_nts_best_order[3],",
"tj) in itertools.combinations(tetrads, 2): if not ti.is_disjoint(tj): graph[ti].append(tj) graph[tj].append(ti) # remove tetrad which",
"tetrad.pair_34, tetrad.pair_41]} def visualize(self, prefix: str, suffix: str): fasta = tempfile.NamedTemporaryFile('w+', suffix='.fasta') fasta.write(f'>{prefix}-{suffix}\\n')",
"int] = field(init=False) def __post_init__(self): self.base_pairs = self.structure3d.base_pairs(self.structure2d) self.base_pair_graph = self.structure3d.base_pair_graph(self.structure2d, self.strict) self.base_pair_dict",
"range(1, len(best_order)): ti, tj = best_order[i - 1], best_order[i] score = self.tetrad_scores[ti][tj][0] if",
"(1, 3, 2): return ONZ.N_PLUS elif order == (2, 3, 1): return ONZ.N_MINUS",
"helices.append(Helix([tetrad], [], self.structure3d)) return helices def __find_best_chain_order(self): chain_groups = self.__group_related_chains() final_order = []",
"range(4)} stacked.update({v: k for k, v in stacked.items()}) tetrad_pairs.append(TetradPair(ti, tj, stacked)) order =",
"= max(conflicts.items(), key=lambda x: (len(x[1]), x[0].nt1)) removed.append(pair) queue.remove(pair) else: orders.update({pair: order for pair",
"< nt.index < ncur.index, self.structure3d.residues)) loop_type = self.__detect_loop_type(nprev, ncur) loops.append(Loop(nts, loop_type)) return loops",
"tetrad_scores: Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]] = field(init=False) tetrad_pairs: List[TetradPair] = field(init=False) helices:",
"quadruplexes = list() tetrads = list() for tetrad in [self.tetrad_pairs[0].tetrad1] + [tetrad_pair.tetrad2 for",
"and pair.nt2 == last: if pair.score() < pair.reverse().score(): return '-' return '+' #",
"self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23 elif order == (self.nt4,",
"in tracts] def __find_loops(self) -> List[Loop]: if len(self.tetrads) == 1: return [] loops",
"if best_score == (len(self.tetrads) - 1) * 4: break tetrad_pairs = [] for",
"closing = ')]}>' + string.ascii_lowercase dotbracket = dict() for pair, order in orders.items():",
"frozenset(self.nucleotides).isdisjoint(frozenset(other.nucleotides)) def center(self) -> numpy.ndarray: return center_of_mass(self.outer_and_inner_atoms()) def outer_and_inner_atoms(self) -> List[Atom3D]: return list(map(lambda",
"self.pair_23.reverse(), self.pair_12.reverse() else: raise RuntimeError(f'Cannot apply order: {order}') self.nt1, self.nt2, self.nt3, self.nt4 =",
"def __post_init__(self): self.tetrad2_nts_best_order = ( self.stacked[self.tetrad1.nt1], self.stacked[self.tetrad1.nt2], self.stacked[self.tetrad1.nt3], self.stacked[self.tetrad1.nt4] ) self.direction = self.__determine_direction()",
"f' {self.onzm.value if self.onzm is not None else \"R\"}' builder += f' {\",\".join(map(lambda",
"Structure3D onzm: Optional[ONZM] = field(init=False) gba_classes: List[GbaQuadruplexClassification] = field(init=False) tracts: List[Tract] = field(init=False)",
"groups.append(candidate) return sorted([sorted(group) for group in groups], key=lambda x: x[0]) def __reorder_chains(self, chain_order:",
"dict() order = 0 queue = list(pairs) removed = [] while queue: conflicts",
"tetrad_pairs: List[TetradPair] structure3d: Structure3D quadruplexes: List[Quadruplex] = field(init=False) def __post_init__(self): self.quadruplexes = self.__find_quadruplexes()",
"subtype = 'a' if self.loops[0 if fingerprint != 'dpd' else 1].loop_type.value[-1] == '-'",
"tetrad in self.tetrads: if not any([tetrad in helix.tetrads for helix in helices]): helices.append(Helix([tetrad],",
"chain: nt.index = i i += 1 for nt in self.structure3d.residues: if nt.chain",
"direction return Direction.parallel elif count == 2: # two in +, one in",
"planarity deviation candidates = sorted(tetrads, key=lambda t: (len(graph[t]), t.planarity_deviation), reverse=True) if len(graph[candidates[0]]) >",
"elif order == (self.nt4, self.nt1, self.nt2, self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41,",
"(0, 1, 2, 3) ni, nj, nk, nl = (nt.index for nt in",
"+= f'{self.sequence}\\n{self.line1}\\n{self.line2}' return builder def __chain_order(self) -> List[str]: only_nucleic_acids = filter(lambda nt: nt.is_nucleotide,",
"j, k) and i in self.base_pair_graph[x], self.base_pair_graph[k]): if Tetrad.is_valid(i, j, k, l, self.base_pair_dict):",
"{\",\".join(map(lambda gba: gba.value, self.gba_classes))}' if self.loop_class: builder += f' {self.loop_class.value} {self.loop_class.loop_progression()}' else: builder",
"transform into (0, 1, 2, 3) ni, nj, nk, nl = (nt.index for",
"Dict[Residue3D, List[Residue3D]] = structure3d.base_pair_graph(structure2d) self.pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = structure3d.base_pair_dict(structure2d) def has_tetrads(self): tetrads",
"# ^--------------^ tetrads = [] for i in self.base_pair_graph: for j in filter(lambda",
"is too far from any tetrad (distance={min_distance})') for tetrad, ions in ions_channel.items(): tetrad.ions_channel",
"self.nt3, self.nt4, self.nt1, self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23",
"'' shifts = dict() shift_value = 0 chain = None for nt in",
"def __classify_by_loops(self) -> Optional[LoopClassification]: if len(self.loops) != 3 or any([loop.loop_type is None for",
">= (4 - stacking_mismatch): nts1, nts2 = self.tetrad_scores[ti][tj][1:] stacked = {nts1[i]: nts2[i] for",
"Tuple[str, ...]) -> int: chain_pairs = [] for h in self.helices: for t",
"same direction return Direction.parallel elif count == 2: # two in +, one",
"self.__assign_ions_to_tetrads() def __find_tetrads(self, no_reorder=False) -> List[Tetrad]: # search for a tetrad: i ->",
"return tetrad_scores def __find_tetrad_pairs(self, stacking_mismatch: int) -> List[TetradPair]: tetrads = list(self.tetrads) best_score =",
"= tuple(atom.coordinates()) if coordinates not in used: ions.append(atom) used.add(coordinates) return ions def __assign_ions_to_tetrads(self)",
"List[Atom3D]], Dict[Tuple[Tetrad, Residue3D], List[Atom3D]]]: if len(self.tetrads) == 0: return {}, {} ions_channel =",
"self.__find_tetrads(self.no_reorder) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices() if not self.no_reorder:",
"for nt in self.nucleotides] inner = [nt.innermost_atom for nt in self.nucleotides] return numpy.linalg.norm(center_of_mass(outer)",
"'dpd': '12', 'ldp': '13' } fingerprint = ''.join([loop.loop_type.value[0] for loop in self.loops]) if",
"field(init=False) tetrad_pairs: List[TetradPair] = field(init=False) helices: List[Helix] = field(init=False) ions: List[Atom3D] = field(init=False)",
"{} ions_channel = defaultdict(list) ions_outside = defaultdict(list) for ion in self.ions: min_distance =",
"min_nt = nt # TODO: verify threshold of 3A between an ion and",
"= pair.nt1, pair.nt2 x, y = nucleotides.index(x) + 1 + shifts[x], nucleotides.index(y) +",
"= pair_dictionary[(nt3, nt4)].lw lw4 = pair_dictionary[(nt4, nt1)].lw for lw_i, lw_j in ((lw1, lw4),",
"in tract.nucleotides and ncur in tract.nucleotides: break else: nts = list(filter(lambda nt: nprev.index",
"(ni, nj, nk, nl)) nmin = min(ni, nj, nk, nl) if nmin ==",
"x not in (i, j), self.base_pair_graph[j]): for l in filter(lambda x: x not",
"field(init=False) base_pair_graph: Dict[Residue3D, List[Residue3D]] = field(init=False) base_pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = field(init=False) stacking_graph:",
"= field(init=False) loops: List[Loop] = field(init=False) loop_class: Optional[LoopClassification] = field(init=False) def __post_init__(self): self.onzm",
"n3, n2), (n4, n3, n2, n1), (n3, n2, n1, n4), (n2, n1, n4,",
"in self.ions_channel]) return '' def __ions_outside_str(self) -> str: if self.ions_outside: result = []",
"- self.stacking_mismatch): helix_tetrads.append(tj) helix_tetrad_pairs.append(tp) else: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) helix_tetrads = [ti, tj] helix_tetrad_pairs",
"in residue.atoms: if atom.atomName.upper() in metal_atom_names: coordinates = tuple(atom.coordinates()) if coordinates not in",
"helix_tetrads: helix_tetrads.append(ti) score = self.tetrad_scores[helix_tetrads[-1]][tj][0] if score >= (4 - self.stacking_mismatch): helix_tetrads.append(tj) helix_tetrad_pairs.append(tp)",
"math.inf min_tetrad = self.tetrads[0] min_nt = min_tetrad.nt1 for tetrad in self.tetrads: for nt",
"in (i, j, k) and i in self.base_pair_graph[x], self.base_pair_graph[k]): if Tetrad.is_valid(i, j, k,",
"100)) return list(map(lambda x: GbaQuadruplexClassification[x], gbas)) def __find_tracts(self) -> List[Tract]: tracts = [[self.tetrads[0].nt1],",
"order == (self.nt4, self.nt1, self.nt2, self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12,",
"permutation earlier in lexicographical sense if permutation < best_permutation: best_permutation = permutation final_order.extend(best_permutation)",
"Tuple, Optional, Set import numpy from eltetrado.model import Atom3D, Structure3D, Structure2D, BasePair3D, Residue3D,",
"self.pair_23.reverse(), self.pair_12.reverse() # ONZ and da Silva's classification are valid in 5'-3' order",
"builder @dataclass class Helix: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D quadruplexes: List[Quadruplex] =",
"if self.onzm is not None else \"R\"}' builder += f' {\",\".join(map(lambda gba: gba.value,",
"6.0: ions_channel[min_tetrad].append(ion) continue min_distance = math.inf min_tetrad = self.tetrads[0] min_nt = min_tetrad.nt1 for",
"for i in range(4)]) score_sequential = sum(score_sequential) score_stacking = sum(score_stacking) if (score, score_sequential,",
"TetradPair) -> bool: return check_tetrad(tp.tetrad1) and check_tetrad(tp.tetrad2) return list(filter(check_pair, self.tetrad_pairs)) def __str__(self): builder",
"if self.loops[0 if fingerprint != 'dpd' else 1].loop_type.value[-1] == '-' else 'b' return",
"import dataclass, field from typing import Dict, Iterable, List, Tuple, Optional, Set import",
"nt2_1, nt2_2, _, _ = self.tetrad2_nts_best_order v1 = nt1_1.find_atom(\"C1'\").coordinates() - nt1_2.find_atom(\"C1'\").coordinates() v1 =",
"def __str__(self): return f' {\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass class Loop: nucleotides:",
"conflicts[pj].append(pi) if conflicts: pair, _ = max(conflicts.items(), key=lambda x: (len(x[1]), x[0].nt1)) removed.append(pair) queue.remove(pair)",
"nts2[i]) else 0 for i in range(4)] score = sum([max(score_stacking[i], score_sequential[i]) for i",
"nucleotides: List[Residue3D] loop_type: Optional[LoopType] def __str__(self): return f' {self.loop_type.value if self.loop_type else \"n/a\"}",
"if tetrad_with_first == tetrad_with_last: # diagonal or laterals happen when first and last",
"same tetrad sign = self.__detect_loop_sign(nt_first, nt_last, tetrad_with_first) if sign is not None: return",
"Tuple[str, str, Dict[Residue3D, int]]: orders = dict() order = 0 queue = list(pairs)",
"in self.structure3d.residues: if nt.chain == chain: nt.index = i i += 1 for",
"else []) helix2 = self.__to_helix(layer2) currdir = os.path.dirname(os.path.realpath(__file__)) output_pdf = f'{prefix}-{suffix}.pdf' run =",
"builder += str(self.tetrads[0]) else: builder += f' {self.onzm.value if self.onzm is not None",
"any([t.onz is None for t in self.tetrads]): return None counter = Counter([t.onz.value[0] for",
"os import string import subprocess import tempfile from collections import defaultdict, Counter from",
"if len(self.tetrads) == 1: return None if any([t.onz is None for t in",
"tetrad_pairs: List[TetradPair] structure3d: Structure3D onzm: Optional[ONZM] = field(init=False) gba_classes: List[GbaQuadruplexClassification] = field(init=False) tracts:",
"self.base_pair_graph[j]): for l in filter(lambda x: x not in (i, j, k) and",
"of 's' for syn or 'a' for anti fingerprint = ''.join([nt.chi_class.value[0] for nt",
"n1), (n3, n4, n1, n2), (n4, n1, n2, n3), (n1, n4, n3, n2),",
"return ONZM.from_value(f'{onz}{direction}{plus_minus}') def __classify_by_gba(self) -> List[GbaQuadruplexClassification]: gbas = set() for t in self.tetrads:",
"+ [tetrad_pair.tetrad2 for tetrad_pair in self.tetrad_pairs]: if tetrads: if tetrad.chains().isdisjoint(tetrads[-1].chains()): quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d))",
"return None if tetrad_with_first == tetrad_with_last: # diagonal or laterals happen when first",
"= self.tetrad_scores[ti][tj][0] if score >= (4 - stacking_mismatch): nts1, nts2 = self.tetrad_scores[ti][tj][1:] stacked",
"self.quadruplexes = self.__find_quadruplexes() def __find_quadruplexes(self): if len(self.tetrad_pairs) == 0: return [Quadruplex(self.tetrads, [], self.structure3d)]",
"= 0 queue = list(pairs) removed = [] while queue: conflicts = defaultdict(list)",
"best_order = nts2 if best_score == 4: break tetrad_scores[ti][tj] = (best_score, nts1, best_order)",
"candidates: tj = max([tj for tj in candidates], key=lambda tk: self.tetrad_scores[ti][tk][0]) score +=",
"Geometric Formalism for DNA Quadruplex Folding. Chemistry - A European Journal, 13(35), 9738–9745.",
"= 'a' if self.loops[0 if fingerprint != 'dpd' else 1].loop_type.value[-1] == '-' else",
"self.structure3d.stacking_graph(self.structure2d) self.tetrads = self.__find_tetrads(self.no_reorder) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices = self.__find_helices()",
"is not None else \"R\"}' builder += f' {\",\".join(map(lambda gba: gba.value, self.gba_classes))}' if",
"coordinates = tuple(atom.coordinates()) if coordinates not in used: ions.append(atom) used.add(coordinates) return ions def",
"permutation in itertools.permutations(chains): self.__reorder_chains(permutation) classifications = [t.onz for h in self.helices for t",
"tetrad_scores[ti][tj] = (best_score, nts1, best_order) tetrad_scores[tj][ti] = (best_score, best_order, nts1) return tetrad_scores def",
"self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() # ONZ and da Silva's",
"for quadruplex in self.quadruplexes: builder += str(quadruplex) elif len(self.tetrads) == 1: builder +=",
"if self.pair_12.score() > self.pair_41.reverse().score(): self.nt1, self.nt2, self.nt3, self.nt4 = self.nt1, self.nt4, self.nt3, self.nt2",
"Residue3D] tetrad2_nts_best_order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D] = field(init=False) direction: Direction = field(init=False) rise:",
"onz: ONZ = field(init=False) gba_class: Optional[GbaTetradClassification] = field(init=False) planarity_deviation: float = field(init=False) ions_channel:",
"defaultdict(list) for ion in self.ions: min_distance = math.inf min_tetrad = self.tetrads[0] for tetrad",
"= tp.tetrad1, tp.tetrad2 if not helix_tetrads: helix_tetrads.append(ti) score = self.tetrad_scores[helix_tetrads[-1]][tj][0] if score >=",
"= self.__find_tract_with_nt(nt_last) if tract_with_last is not None: # search along the tract to",
"in self.helices: for t in h.tetrads: for p in [t.pair_12, t.pair_23, t.pair_34, t.pair_41]:",
"'-' return '+' # reverse check if pair.nt1 == last and pair.nt2 ==",
"n2, n3, n4), (n2, n3, n4, n1), (n3, n4, n1, n2), (n4, n1,",
"return helices def __find_best_chain_order(self): chain_groups = self.__group_related_chains() final_order = [] for chains in",
"list(filter(lambda nt: nprev.index < nt.index < ncur.index, self.structure3d.residues)) loop_type = self.__detect_loop_type(nprev, ncur) loops.append(Loop(nts,",
"j, k, l, self.pair_dict): tetrads.add(frozenset([i, j, k, l])) if len(tetrads) > 1: return",
"List[Tetrad]) -> List[TetradPair]: chains = set() for tetrad in tetrads: chains.update(tetrad.chains()) def check_tetrad(t:",
"-> List[Tetrad]: # search for a tetrad: i -> j -> k ->",
"Residue3D, tetrad: Tetrad) -> Optional[str]: for pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]: #",
"f' n/a' builder += f' quadruplex with {len(self.tetrads)} tetrads\\n' builder += str(self.tetrad_pairs[0].tetrad1) for",
"pair_dictionary[(nt2, nt3)].lw lw3 = pair_dictionary[(nt3, nt4)].lw lw4 = pair_dictionary[(nt4, nt1)].lw for lw_i, lw_j",
"final_order = [] for chains in chain_groups: best_permutation, best_score = chains, (1e10, 1e10)",
"currdir = os.path.dirname(os.path.realpath(__file__)) output_pdf = f'{prefix}-{suffix}.pdf' run = subprocess.run([os.path.join(currdir, 'quadraw.R'), fasta.name, helix1.name, helix2.name,",
"base_pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = field(init=False) stacking_graph: Dict[Residue3D, List[Residue3D]] = field(init=False) tetrads: List[Tetrad]",
"self.tetrad1.outer_and_inner_atoms() t2 = self.tetrad2.outer_and_inner_atoms() return numpy.linalg.norm(center_of_mass(t1) - center_of_mass(t2)) def __calculate_twist(self) -> float: nt1_1,",
"line1, shifts = self.__elimination_conflicts(layer1) _, line2, _ = self.__elimination_conflicts(layer2) return sequence, line1, line2,",
"'pll': '9', 'pdl': '10', 'ldl': '11', 'dpd': '12', 'ldp': '13' } fingerprint =",
"verify threshold of 6A between an ion and tetrad channel if min_distance <",
"= removed, [] order += 1 opening = '([{<' + string.ascii_uppercase closing =",
"valid syn/anti, this classification is impossible if not all([nt.chi_class in (GlycosidicBond.syn, GlycosidicBond.anti) for",
"BasePair3D onz: ONZ = field(init=False) gba_class: Optional[GbaTetradClassification] = field(init=False) planarity_deviation: float = field(init=False)",
"check if pair.nt1 == first and pair.nt2 == last: if pair.score() < pair.reverse().score():",
"v in stacked.items()}) tetrad_pairs.append(TetradPair(ti, tj, stacked)) order = (stacked[ti.nt1], stacked[ti.nt2], stacked[ti.nt3], stacked[ti.nt4]) tj.reorder_to_match_other_tetrad(order)",
"nt3: Residue3D, nt4: Residue3D, pair_dictionary: Dict[Tuple[Residue3D, Residue3D], BasePair3D]) -> bool: lw1 = pair_dictionary[(nt1,",
"+= dotbracket.get(nt, '.') shifts[nt] = shift_value chain = nt.chain return sequence, structure, shifts",
"> self.pair_41.reverse().score(): self.nt1, self.nt2, self.nt3, self.nt4 = self.nt1, self.nt4, self.nt3, self.nt2 self.pair_12, self.pair_23,",
"nt.index = i i += 1 if len(self.tetrad_pairs) > 0: self.tetrad_pairs[0].tetrad1.reorder_to_match_5p_3p() for tp",
"3, ONZ.N_MINUS: 4, ONZ.Z_PLUS: 5, ONZ.Z_MINUS: 6} nucleotides = self.analysis.structure3d.residues shifts = self.analysis.shifts",
"5, ONZ.Z_MINUS: 6} nucleotides = self.analysis.structure3d.residues shifts = self.analysis.shifts helix = tempfile.NamedTemporaryFile('w+', suffix='.helix')",
"def __to_helix(self, layer: List[BasePair3D], canonical: Optional[List[BasePair3D]] = None) -> tempfile.NamedTemporaryFile(): onz_value = {ONZ.O_PLUS:",
"tj = best_order[i - 1], best_order[i] score = self.tetrad_scores[ti][tj][0] if score >= (4",
"field(init=False) ions: List[Atom3D] = field(init=False) sequence: str = field(init=False) line1: str = field(init=False)",
"len(self.tetrads) == 1: builder += 'single tetrad without stacking\\n' builder += str(self.tetrads[0]) return",
"self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) sequence, line1, shifts = self.__elimination_conflicts(layer1) _, line2, _",
"{nl}') def __classify_by_gba(self) -> Optional[GbaTetradClassification]: \"\"\" See: <NAME>. (2007). Geometric Formalism for DNA",
"Tuple]]] = field(init=False) tetrad_pairs: List[TetradPair] = field(init=False) helices: List[Helix] = field(init=False) ions: List[Atom3D]",
"[] for residue, ions in self.ions_outside.items(): result.append(f'{residue.full_name}: [{\",\".join([ion.atomName for ion in ions])}]') return",
"ion and tetrad channel if min_distance < 6.0: ions_channel[min_tetrad].append(ion) continue min_distance = math.inf",
"in ions])}]') return 'ions_outside=' + ' '.join(result) return '' @dataclass class TetradPair: tetrad1:",
"else \"R\"}' builder += f' {\",\".join(map(lambda gba: gba.value, self.gba_classes))}' if self.loop_class: builder +=",
"for p in [t.pair_12, t.pair_23, t.pair_34, t.pair_41]: c1 = p.nt1.chain c2 = p.nt2.chain",
"in sorted(filter(lambda nt: nt.is_nucleotide, self.structure3d.residues), key=lambda nt: nt.index): if chain and chain !=",
"= self.__find_helices() def __group_related_chains(self) -> List[List[str]]: candidates = set() for h in self.helices:",
"self.stacking_graph.get(nt1, []) def is_next_sequentially(nt1: Residue3D, nt2: Residue3D) -> bool: return nt1.chain == nt2.chain",
"i in range(4): tracts[i].append(nt_dict[tracts[i][-1]]) return [Tract(nts) for nts in tracts] def __find_loops(self) ->",
"raise RuntimeError(f'Cannot apply order: {order}') self.nt1, self.nt2, self.nt3, self.nt4 = order def __classify_onz(self)",
"= self.__detect_loop_sign(nt_first, nt, tetrad_with_first) if sign is not None: return LoopType.from_value(f'propeller{sign}') logging.warning(f'Failed to",
"__ions_outside_str(self) -> str: if self.ions_outside: result = [] for residue, ions in self.ions_outside.items():",
"builder += str(tetrad_pair.tetrad2) if self.tracts: builder += '\\n Tracts:\\n' for tract in self.tracts:",
"in used: ions.append(atom) used.add(coordinates) return ions def __assign_ions_to_tetrads(self) \\ -> Tuple[Dict[Tetrad, List[Atom3D]], Dict[Tuple[Tetrad,",
"helix_tetrad_pairs = [tp] if helix_tetrads: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) for tetrad in self.tetrads: if",
"= self.__find_tetrad_with_nt(nt_last) if tetrad_with_first is None or tetrad_with_last is None: logging.warning(f'Failed to classify",
"tp in self.tetrad_pairs: order = (tp.stacked[tp.tetrad1.nt1], tp.stacked[tp.tetrad1.nt2], tp.stacked[tp.tetrad1.nt3], tp.stacked[tp.tetrad1.nt4]) tp.tetrad2.reorder_to_match_5p_3p() # this is",
"= (coord[1] for coord in coords) zs = (coord[2] for coord in coords)",
"= list(map(lambda nt: nt.index, self.tetrad1.nucleotides)) indices2 = list(map(lambda nt: nt.index, self.tetrad2_nts_best_order)) # count",
"self.pair_23.reverse() elif order == (self.nt1, self.nt4, self.nt3, self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41 =",
"for tetrad in self.tetrads for pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]} def visualize(self,",
"shift_value chain = nt.chain return sequence, structure, shifts def __str__(self): builder = f'Chain",
"qi.isdisjoint(qj): qi.update(qj) del candidates[j] changed = True break candidates = sorted(candidates, key=lambda x:",
"def __calculate_rise(self) -> float: t1 = self.tetrad1.outer_and_inner_atoms() t2 = self.tetrad2.outer_and_inner_atoms() return numpy.linalg.norm(center_of_mass(t1) -",
"nt1_1.find_atom(\"C1'\").coordinates() - nt1_2.find_atom(\"C1'\").coordinates() v1 = v1 / numpy.linalg.norm(v1) v2 = nt2_1.find_atom(\"C1'\").coordinates() - nt2_2.find_atom(\"C1'\").coordinates()",
"tetrads = list() tetrads.append(tetrad) quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) return quadruplexes def __filter_tetrad_pairs(self, tetrads: List[Tetrad])",
"(ni, nj, nk, nl)) while ni != 0: ni, nj, nk, nl =",
"set([ion.value.upper() for ion in Ion]) ions = [] used = set() for residue",
"nl = (indices.index(x) for x in (ni, nj, nk, nl)) while ni !=",
"order = (nj, nk, nl) if order == (1, 2, 3): return ONZ.O_PLUS",
"bool stacking_mismatch: int base_pairs: List[BasePair3D] = field(init=False) base_pair_graph: Dict[Residue3D, List[Residue3D]] = field(init=False) base_pair_dict:",
"== 1: return None if any([t.onz is None for t in self.tetrads]): return",
"for nt in self.nucleotides) indices = sorted((ni, nj, nk, nl)) ni, nj, nk,",
"nt2: Residue3D, nt3: Residue3D, nt4: Residue3D, pair_dictionary: Dict[Tuple[Residue3D, Residue3D], BasePair3D]) -> bool: lw1",
"is not None: return LoopType.from_value(f'propeller{sign}') logging.warning(f'Failed to classify the loop between {nt_first} and",
"str = field(init=False) shifts: Dict[Residue3D, int] = field(init=False) def __post_init__(self): self.base_pairs = self.structure3d.base_pairs(self.structure2d)",
"None for t in self.tetrads]): return None counter = Counter([t.onz.value[0] for t in",
"GbaTetradClassification.VIIIa, 'ssss': GbaTetradClassification.VIIIb } if fingerprint not in gba_classes: logging.error(f'Impossible combination of syn/anti:",
"candidates[j] if not qi.isdisjoint(qj): qi.update(qj) del candidates[j] changed = True break candidates =",
"nprev.index < nt.index < ncur.index, self.structure3d.residues)) loop_type = self.__detect_loop_type(nprev, ncur) loops.append(Loop(nts, loop_type)) return",
"-> List[Atom3D]: metal_atom_names = set([ion.value.upper() for ion in Ion]) ions = [] used",
"defaultdict(list) for pi, pj in itertools.combinations(queue, 2): if pi.conflicts_with(pj): conflicts[pi].append(pj) conflicts[pj].append(pi) if conflicts:",
"-> float: t1 = self.tetrad1.outer_and_inner_atoms() t2 = self.tetrad2.outer_and_inner_atoms() return numpy.linalg.norm(center_of_mass(t1) - center_of_mass(t2)) def",
"__find_loops(self) -> List[Loop]: if len(self.tetrads) == 1: return [] loops = [] tetrad_nucleotides",
"self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23 elif order == (self.nt4, self.nt1,",
"self.nt4, self.nt1 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif nmin",
"any([tetrad in helix.tetrads for helix in helices]): helices.append(Helix([tetrad], [], self.structure3d)) return helices def",
"subvariant roman_numerals = {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5,",
"self.nucleotides)) + \\ list(map(lambda residue: residue.innermost_atom, self.nucleotides)) def __ions_channel_str(self) -> str: if self.ions_channel:",
"key=lambda t: min(map(lambda nt: nt.index, t.nucleotides))) def __calculate_tetrad_scores(self) \\ -> Dict[Tetrad, Dict[Tetrad, Tuple[int,",
"if nt in tetrad_with_first.nucleotides: sign = self.__detect_loop_sign(nt_first, nt, tetrad_with_first) if sign is not",
"not in (i, j), self.base_pair_graph[j]): for l in filter(lambda x: x not in",
"best_score_stacking): best_score, best_score_sequential, best_score_stacking = score, score_sequential, score_stacking best_order = nts2 if best_score",
"onz: onz.value, classifications))}') self.tetrads = self.__find_tetrads(True) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch) self.helices",
"in h.tetrads: candidates.add(frozenset([t.nt1.chain, t.nt2.chain, t.nt3.chain, t.nt4.chain])) candidates = [set(c) for c in candidates]",
"''.join([nt.chi_class.value[0] for nt in self.nucleotides]) # this dict has all classes mapped to",
"-> List[GbaQuadruplexClassification]: gbas = set() for t in self.tetrads: gba = t.gba_class if",
"tp in self.tetrad_pairs: ti, tj = tp.tetrad1, tp.tetrad2 if not helix_tetrads: helix_tetrads.append(ti) score",
"field(init=False) planarity_deviation: float = field(init=False) ions_channel: List[Atom3D] = field(default_factory=list) ions_outside: Dict[Residue3D, List[Atom3D]] =",
"f'{\" \".join(map(lambda onz: onz.value, classifications))}') self.tetrads = self.__find_tetrads(True) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs =",
"builder = f'Chain order: {\" \".join(self.__chain_order())}\\n' for helix in self.helices: builder += str(helix)",
"'saaa': GbaTetradClassification.VIIb, 'aaaa': GbaTetradClassification.VIIIa, 'ssss': GbaTetradClassification.VIIIb } if fingerprint not in gba_classes: logging.error(f'Impossible",
"h.tetrads] logging.debug(f'Selected chain order: {\" \".join(final_order)} ' f'{\" \".join(map(lambda onz: onz.value, classifications))}') self.tetrads",
"1): return ONZ.O_MINUS elif order == (1, 3, 2): return ONZ.N_PLUS elif order",
"ion in self.ions: min_distance = math.inf min_tetrad = self.tetrads[0] for tetrad in self.tetrads:",
"for coord in coords) return numpy.array((sum(xs) / len(coords), sum(ys) / len(coords), sum(zs) /",
"chain = nt.chain return sequence, structure, shifts def __str__(self): builder = f'Chain order:",
"in self.tetrads: if nt in tetrad.nucleotides: return tetrad return None def __find_tract_with_nt(self, nt:",
"len(self.tetrads) == 0: return {}, {} ions_channel = defaultdict(list) ions_outside = defaultdict(list) for",
"t in self.tetrads]) plus_minus, support = counter.most_common()[0] if support != len(self.tetrads): plus_minus =",
"self.tetrad_pairs]) direction, support = counter.most_common()[0] if support != len(self.tetrad_pairs): direction = 'h' counter",
"into (0, 1, 2, 3) ni, nj, nk, nl = (nt.index for nt",
"1.0))) def __str__(self): return f' direction={self.direction.value} rise={round(self.rise, 2)} twist={round(self.twist, 2)}\\n' @dataclass class Tract:",
"(coord[1] for coord in coords) zs = (coord[2] for coord in coords) return",
"self.nt1, self.nt2, self.nt3, self.nt4 = self.nt1, self.nt4, self.nt3, self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41",
"self.twist = self.__calculate_twist() def __determine_direction(self) -> Direction: indices1 = list(map(lambda nt: nt.index, self.tetrad1.nucleotides))",
"-> Optional[GbaTetradClassification]: \"\"\" See: <NAME>. (2007). Geometric Formalism for DNA Quadruplex Folding. Chemistry",
"in self.nucleotides] inner = [nt.innermost_atom for nt in self.nucleotides] return numpy.linalg.norm(center_of_mass(outer) - center_of_mass(inner))",
"of tetrads while tetrads: graph = defaultdict(list) for (ti, tj) in itertools.combinations(tetrads, 2):",
"all in the same direction return Direction.parallel elif count == 2: # two",
"len(final_order) > 1: self.__reorder_chains(final_order) classifications = [t.onz for h in self.helices for t",
"for h in self.helices for t in h.tetrads] logging.debug(f'Selected chain order: {\" \".join(final_order)}",
"base_pair in self.base_pairs if base_pair.is_canonical()] @dataclass class Visualizer: analysis: Analysis tetrads: List[Tetrad] complete2d:",
"= 0 best_score_sequential = 0 best_score_stacking = 0 best_order = tj.nucleotides n1, n2,",
"builder += f'{tract}\\n' if self.loops: builder += '\\n Loops:\\n' for loop in self.loops:",
"direction return Direction.antiparallel return Direction.hybrid def __calculate_rise(self) -> float: t1 = self.tetrad1.outer_and_inner_atoms() t2",
"self.nt1, self.nt4, self.nt3, self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse()",
"nt: nt.is_nucleotide, self.structure3d.residues) return list({nt.chain: 0 for nt in sorted(only_nucleic_acids, key=lambda nt: nt.index)}.keys())",
"in sorted(only_nucleic_acids, key=lambda nt: nt.index)}.keys()) def canonical(self) -> List[BasePair3D]: return [base_pair for base_pair",
"pair.nt2 == first: if pair.score() < pair.reverse().score(): return '+' return '-' return None",
"self.nt1, self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23 else: self.nt1,",
"key=lambda nt: nt.index) for i in range(1, len(tetrad_nucleotides)): nprev = tetrad_nucleotides[i - 1]",
"best_score: # in case of a tie, pick permutation earlier in lexicographical sense",
"- chain_order.index(c2)) ** 2 return sum_sq def __find_ions(self) -> List[Atom3D]: metal_atom_names = set([ion.value.upper()",
"0 best_order = tetrads for ti in tetrads: score = 0 order =",
"collections import defaultdict, Counter from dataclasses import dataclass, field from typing import Dict,",
"+= f' {self.loop_class.value} {self.loop_class.loop_progression()}' else: builder += f' n/a' builder += f' quadruplex",
"if len(self.tetrads) == 1: return [] loops = [] tetrad_nucleotides = sorted([nt for",
"tetrad.nucleotides], key=lambda nt: nt.index) for i in range(1, len(tetrad_nucleotides)): nprev = tetrad_nucleotides[i -",
"nts1 = ti.nucleotides best_score = 0 best_score_sequential = 0 best_score_stacking = 0 best_order",
"tj, stacked)) order = (stacked[ti.nt1], stacked[ti.nt2], stacked[ti.nt3], stacked[ti.nt4]) tj.reorder_to_match_other_tetrad(order) return tetrad_pairs def __find_helices(self):",
"= [(n1, n2, n3, n4), (n2, n3, n4, n1), (n3, n4, n1, n2),",
"for ion in self.ions: min_distance = math.inf min_tetrad = self.tetrads[0] for tetrad in",
"reason:\\n {run.stderr.decode()}') def __to_helix(self, layer: List[BasePair3D], canonical: Optional[List[BasePair3D]] = None) -> tempfile.NamedTemporaryFile(): onz_value",
"[{\",\".join([ion.atomName for ion in ions])}]') return 'ions_outside=' + ' '.join(result) return '' @dataclass",
"(lw3, lw2), (lw4, lw3)): if lw_i.name[1] == lw_j.name[2]: return False return True nt1:",
"= self.__find_tracts() self.loops = self.__find_loops() self.loop_class = self.__classify_by_loops() def __classify_onzm(self) -> Optional[ONZM]: if",
"self.nt4 = self.nt4, self.nt1, self.nt2, self.nt3 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12,",
"self.structure3d.residues: if nt.chain == chain: nt.index = i i += 1 for nt",
"for t in self.tetrads]) onz, support = counter.most_common()[0] if support != len(self.tetrads): onz",
"tracts[i].append(nt_dict[tracts[i][-1]]) return [Tract(nts) for nts in tracts] def __find_loops(self) -> List[Loop]: if len(self.tetrads)",
"+= str(quadruplex) elif len(self.tetrads) == 1: builder += 'single tetrad without stacking\\n' builder",
"structure3d: Structure3D onzm: Optional[ONZM] = field(init=False) gba_classes: List[GbaQuadruplexClassification] = field(init=False) tracts: List[Tract] =",
"field(default_factory=dict) def __post_init__(self): self.reorder_to_match_5p_3p() self.planarity_deviation = self.__calculate_planarity_deviation() def reorder_to_match_5p_3p(self): # transform into (0,",
"or -1 counter = Counter(1 if j - i > 0 else -1",
"in orders.items(): nt1, nt2 = sorted([pair.nt1, pair.nt2]) dotbracket[nt1] = opening[order] dotbracket[nt2] = closing[order]",
"ions in self.ions_outside.items(): result.append(f'{residue.full_name}: [{\",\".join([ion.atomName for ion in ions])}]') return 'ions_outside=' + '",
"return nt2 in self.stacking_graph.get(nt1, []) def is_next_sequentially(nt1: Residue3D, nt2: Residue3D) -> bool: return",
"for c in classifications) chain_order_score = self.__chain_order_score(permutation) score = (onz_score, chain_order_score) if score",
"return Direction.antiparallel return Direction.hybrid def __calculate_rise(self) -> float: t1 = self.tetrad1.outer_and_inner_atoms() t2 =",
"builder += f' {self.loop_class.value} {self.loop_class.loop_progression()}' else: builder += f' n/a' builder += f'",
"= self.nt3, self.nt4, self.nt1, self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12,",
"self.base_pair_graph[k]): if Tetrad.is_valid(i, j, k, l, self.base_pair_dict): pair_12 = self.base_pair_dict[(i, j)] pair_23 =",
"in itertools.combinations(self.tetrads, 2): nts1 = ti.nucleotides best_score = 0 best_score_sequential = 0 best_score_stacking",
"and abs(nt1.index - nt2.index) == 1 tetrad_scores = defaultdict(dict) for ti, tj in",
"None def __detect_loop_sign(self, first: Residue3D, last: Residue3D, tetrad: Tetrad) -> Optional[str]: for pair",
"\\ GbaTetradClassification, Ion, Direction, LoopType, ONZM, GbaQuadruplexClassification, LoopClassification logging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"INFO\")) @dataclass(order=True) class Tetrad:",
"key=lambda gba: roman_numerals.get(gba, 100)) return list(map(lambda x: GbaQuadruplexClassification[x], gbas)) def __find_tracts(self) -> List[Tract]:",
"k)] pair_34 = self.base_pair_dict[(k, l)] pair_41 = self.base_pair_dict[(l, i)] tetrads.append(Tetrad(i, j, k, l,",
"BasePair3D, Residue3D, GlycosidicBond, ONZ, \\ GbaTetradClassification, Ion, Direction, LoopType, ONZM, GbaQuadruplexClassification, LoopClassification logging.basicConfig(level=os.environ.get(\"LOGLEVEL\",",
"for a tetrad: i -> j -> k -> l # ^--------------^ tetrads",
"ONZ and da Silva's classification are valid in 5'-3' order self.onz = self.__classify_onz()",
"nmin == ni: pass elif nmin == nj: self.nt1, self.nt2, self.nt3, self.nt4 =",
"= numpy.linalg.norm(ion.coordinates() - tetrad.center()) if distance < min_distance: min_distance = distance min_tetrad =",
"canonical: Optional[List[BasePair3D]] = None) -> tempfile.NamedTemporaryFile(): onz_value = {ONZ.O_PLUS: 1, ONZ.O_MINUS: 2, ONZ.N_PLUS:",
"= field(init=False) loop_class: Optional[LoopClassification] = field(init=False) def __post_init__(self): self.onzm = self.__classify_onzm() self.gba_classes =",
"= [] for candidate in candidates: if any([group.issuperset(candidate) for group in groups]): continue",
"1: for permutation in itertools.permutations(chains): self.__reorder_chains(permutation) classifications = [t.onz for h in self.helices",
"Dict[BasePair3D, ONZ] = field(init=False) def __post_init__(self): self.onz_dict = {pair: tetrad.onz for tetrad in",
"for i in self.base_pair_graph: for j in filter(lambda x: x != i, self.base_pair_graph[i]):",
"2, 3) ni, nj, nk, nl = (nt.index for nt in self.nucleotides) indices",
"(n4, n1, n2, n3), (n1, n4, n3, n2), (n4, n3, n2, n1), (n3,",
"nt: nt.index): if chain and chain != nt.chain: sequence += '-' structure +=",
"' \\ f'{self.onz.value} {self.gba_class.value} ' \\ f'planarity={round(self.planarity_deviation, 2)} ' \\ f'{self.__ions_channel_str()} ' \\",
"Tetrad: @staticmethod def is_valid(nt1: Residue3D, nt2: Residue3D, nt3: Residue3D, nt4: Residue3D, pair_dictionary: Dict[Tuple[Residue3D,",
"self.loops]) if fingerprint not in loop_classes: logging.error(f'Unknown loop classification: {fingerprint}') return None subtype",
"self.nt1, self.nt2, self.nt3, self.nt4 = self.nt3, self.nt4, self.nt1, self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41",
"nucleotides.index(y) + 1 + shifts[y] helix.write(f'{x}\\t{y}\\t1\\t8\\n') helix.flush() return helix class AnalysisSimple: def __init__(self,",
"tetrad_with_last = self.__find_tetrad_with_nt(nt_last) if tetrad_with_first is None or tetrad_with_last is None: logging.warning(f'Failed to",
"+= 1 sequence += nt.one_letter_name structure += dotbracket.get(nt, '.') shifts[nt] = shift_value chain",
"h.tetrads] logging.debug( f'Checking reorder: {\" \".join(permutation)} {\" \".join(map(lambda c: c.value, classifications))}') onz_score =",
"in candidates] changed = True while changed: changed = False for i, j",
"__find_ions(self) -> List[Atom3D]: metal_atom_names = set([ion.value.upper() for ion in Ion]) ions = []",
"dotbracket[nt2] = closing[order] sequence = '' structure = '' shifts = dict() shift_value",
"sorted(tetrads, key=lambda t: (len(graph[t]), t.planarity_deviation), reverse=True) if len(graph[candidates[0]]) > 0: tetrads.remove(candidates[0]) else: break",
"European Journal, 13(35), 9738–9745. https://doi.org/10.1002/chem.200701255 :return: Classification according to Webba da Silva or",
"loops.append(Loop(nts, loop_type)) return loops def __detect_loop_type(self, nt_first: Residue3D, nt_last: Residue3D) -> Optional[LoopType]: tetrad_with_first",
"self.__find_tract_with_nt(nt_last) if tract_with_last is not None: # search along the tract to check",
"== (2, 3, 1): return ONZ.N_MINUS elif order == (2, 1, 3): return",
"8} gbas = sorted(gbas, key=lambda gba: roman_numerals.get(gba, 100)) return list(map(lambda x: GbaQuadruplexClassification[x], gbas))",
"__init__(self, structure2d: Structure2D, structure3d: Structure3D): self.pairs: List[BasePair3D] = structure3d.base_pairs(structure2d) self.graph: Dict[Residue3D, List[Residue3D]] =",
"is in the same tetrad sign = self.__detect_loop_sign(nt_first, nt_last, tetrad_with_first) if sign is",
"self.pair_12, self.pair_23 else: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt4, self.nt1, self.nt2, self.nt3 self.pair_12,",
"-> 3' as +1 or -1 counter = Counter(1 if j - i",
"+, one in - direction return Direction.antiparallel return Direction.hybrid def __calculate_rise(self) -> float:",
"sequence, line1, line2, shifts def __elimination_conflicts(self, pairs: List[BasePair3D]) -> Tuple[str, str, Dict[Residue3D, int]]:",
"in range(1, len(best_order)): ti, tj = best_order[i - 1], best_order[i] score = self.tetrad_scores[ti][tj][0]",
"tract in self.tracts: builder += f'{tract}\\n' if self.loops: builder += '\\n Loops:\\n' for",
"best_score = score best_order = order if best_score == (len(self.tetrads) - 1) *",
"if nt.chain == chain: nt.index = i i += 1 for nt in",
"self.loops = self.__find_loops() self.loop_class = self.__classify_by_loops() def __classify_onzm(self) -> Optional[ONZM]: if len(self.tetrads) ==",
"if pi.conflicts_with(pj): conflicts[pi].append(pj) conflicts[pj].append(pi) if conflicts: pair, _ = max(conflicts.items(), key=lambda x: (len(x[1]),",
"score_sequential, score_stacking) > (best_score, best_score_sequential, best_score_stacking): best_score, best_score_sequential, best_score_stacking = score, score_sequential, score_stacking",
"self.pair_34, self.pair_41 = self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse() elif order == (self.nt1, self.nt4, self.nt3,",
"min_tetrad = tetrad min_nt = nt # TODO: verify threshold of 3A between",
"permutation elif score == best_score: # in case of a tie, pick permutation",
"List[Residue3D] loop_type: Optional[LoopType] def __str__(self): return f' {self.loop_type.value if self.loop_type else \"n/a\"} '",
"!= i, self.graph[i]): for k in filter(lambda x: x not in (i, j),",
"nk: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt3, self.nt4, self.nt1, self.nt2 self.pair_12, self.pair_23, self.pair_34,",
"ONZ.Z_MINUS raise RuntimeError(f'Impossible combination: {ni} {nj} {nk} {nl}') def __classify_by_gba(self) -> Optional[GbaTetradClassification]: \"\"\"",
"score > best_score: best_score = score best_order = order if best_score == (len(self.tetrads)",
"ONZ.Z_PLUS: 5, ONZ.Z_MINUS: 6} nucleotides = self.analysis.structure3d.residues shifts = self.analysis.shifts helix = tempfile.NamedTemporaryFile('w+',",
"builder = '' if len(self.tetrads) == 1: builder += ' single tetrad\\n' builder",
"j), self.graph[j]): for l in filter(lambda x: x not in (i, j, k)",
"'' @dataclass class TetradPair: tetrad1: Tetrad tetrad2: Tetrad stacked: Dict[Residue3D, Residue3D] tetrad2_nts_best_order: Tuple[Residue3D,",
"{nk} {nl}') def __classify_by_gba(self) -> Optional[GbaTetradClassification]: \"\"\" See: <NAME>. (2007). Geometric Formalism for",
"== nj: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt2, self.nt3, self.nt4, self.nt1 self.pair_12, self.pair_23,",
"'\\n Tracts:\\n' for tract in self.tracts: builder += f'{tract}\\n' if self.loops: builder +=",
"self.helices: builder += str(helix) builder += f'{self.sequence}\\n{self.line1}\\n{self.line2}' return builder def __chain_order(self) -> List[str]:",
"tetrad, ions in ions_channel.items(): tetrad.ions_channel = ions for pair, ions in ions_outside.items(): tetrad,",
"= (onz_score, chain_order_score) if score < best_score: best_score = score best_permutation = permutation",
"list(self.tetrads) best_score = 0 best_order = tetrads for ti in tetrads: score =",
"True return False def center_of_mass(atoms): coords = [atom.coordinates() for atom in atoms] xs",
"= (nt.index for nt in self.nucleotides) indices = sorted((ni, nj, nk, nl)) ni,",
"score_sequential[i]) for i in range(4)]) score_sequential = sum(score_sequential) score_stacking = sum(score_stacking) if (score,",
"best_permutation = permutation final_order.extend(best_permutation) if len(final_order) > 1: self.__reorder_chains(final_order) classifications = [t.onz for",
"and i in self.base_pair_graph[x], self.base_pair_graph[k]): if Tetrad.is_valid(i, j, k, l, self.base_pair_dict): pair_12 =",
"t: min(map(lambda nt: nt.index, t.nucleotides))) def __calculate_tetrad_scores(self) \\ -> Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple,",
"helix_tetrads = [ti, tj] helix_tetrad_pairs = [tp] if helix_tetrads: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) for",
"List[Residue3D]] = field(init=False) tetrads: List[Tetrad] = field(init=False) tetrad_scores: Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]]",
"self.__find_best_chain_order() self.sequence, self.line1, self.line2, self.shifts = self.__generate_twoline_dotbracket() self.ions = self.__find_ions() self.__assign_ions_to_tetrads() def __find_tetrads(self,",
"self.__classify_onz() self.gba_class = self.__classify_by_gba() def reorder_to_match_other_tetrad(self, order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D]): if order",
"GbaTetradClassification.IVa, 'sssa': GbaTetradClassification.IVb, 'aasa': GbaTetradClassification.Va, 'ssas': GbaTetradClassification.Vb, 'assa': GbaTetradClassification.VIa, 'saas': GbaTetradClassification.VIb, 'asss': GbaTetradClassification.VIIa,",
"gba = t.gba_class if gba is not None: gbas.add(gba.value[:-1]) # discard 'a' or",
"Classification according to Webba da Silva or n/a \"\"\" # without all nucleotides",
"-> Optional[LoopClassification]: if len(self.loops) != 3 or any([loop.loop_type is None for loop in",
"Residue3D, nt2: Residue3D, nt3: Residue3D, nt4: Residue3D, pair_dictionary: Dict[Tuple[Residue3D, Residue3D], BasePair3D]) -> bool:",
"graph of tetrads while tetrads: graph = defaultdict(list) for (ti, tj) in itertools.combinations(tetrads,",
"None) -> tempfile.NamedTemporaryFile(): onz_value = {ONZ.O_PLUS: 1, ONZ.O_MINUS: 2, ONZ.N_PLUS: 3, ONZ.N_MINUS: 4,",
"len(self.tetrads) == 1: return None if any([t.onz is None for t in self.tetrads]):",
"def reorder_to_match_other_tetrad(self, order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D]): if order == (self.nt1, self.nt2, self.nt3,",
"tetrads: graph = defaultdict(list) for (ti, tj) in itertools.combinations(tetrads, 2): if not ti.is_disjoint(tj):",
"nt in self.nucleotides]) def is_disjoint(self, other) -> bool: return frozenset(self.nucleotides).isdisjoint(frozenset(other.nucleotides)) def center(self) ->",
"nj, nk, nl)) while ni != 0: ni, nj, nk, nl = nl,",
"= min(ni, nj, nk, nl) if nmin == ni: pass elif nmin ==",
"Optional[ONZM] = field(init=False) gba_classes: List[GbaQuadruplexClassification] = field(init=False) tracts: List[Tract] = field(init=False) loops: List[Loop]",
"nmin == nj: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt2, self.nt3, self.nt4, self.nt1 self.pair_12,",
"self.__detect_loop_sign(nt_first, nt_last, tetrad_with_first) if sign is not None: return LoopType.from_value(f'lateral{sign}') return LoopType.diagonal tract_with_last",
"n3)] for nts2 in viable_permutations: score_stacking = [1 if is_next_by_stacking(nts1[i], nts2[i]) else 0",
"nt2_2.find_atom(\"C1'\").coordinates() v2 = v2 / numpy.linalg.norm(v2) return math.degrees(numpy.arccos(numpy.clip(numpy.dot(v1, v2), -1.0, 1.0))) def __str__(self):",
"__post_init__(self): self.onz_dict = {pair: tetrad.onz for tetrad in self.tetrads for pair in [tetrad.pair_12,",
"return LoopType.from_value(f'lateral{sign}') return LoopType.diagonal tract_with_last = self.__find_tract_with_nt(nt_last) if tract_with_last is not None: #",
"min_distance: min_distance = distance min_tetrad = tetrad min_nt = nt # TODO: verify",
"self.nt3, self.nt4): pass elif order == (self.nt2, self.nt3, self.nt4, self.nt1): self.pair_12, self.pair_23, self.pair_34,",
"is None: logging.warning(f'Failed to classify the loop between {nt_first} and {nt_last}') return None",
"in self.tetrad_pairs: ti, tj = tp.tetrad1, tp.tetrad2 if not helix_tetrads: helix_tetrads.append(ti) score =",
"nt in self.nucleotides] inner = [nt.innermost_atom for nt in self.nucleotides] return numpy.linalg.norm(center_of_mass(outer) -",
"self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() # ONZ and da Silva's classification are valid in",
"self.pair_41 = self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse() elif order == (self.nt1, self.nt4, self.nt3, self.nt2):",
"line1, line2, shifts def __elimination_conflicts(self, pairs: List[BasePair3D]) -> Tuple[str, str, Dict[Residue3D, int]]: orders",
"nt4: Residue3D, pair_dictionary: Dict[Tuple[Residue3D, Residue3D], BasePair3D]) -> bool: lw1 = pair_dictionary[(nt1, nt2)].lw lw2",
"gba_classes: logging.error(f'Impossible combination of syn/anti: {[nt.chi_class for nt in self.nucleotides]}') return None return",
"in filter(lambda x: x not in (i, j), self.graph[j]): for l in filter(lambda",
"in self.tetrads]) plus_minus, support = counter.most_common()[0] if support != len(self.tetrads): plus_minus = '*'",
"conflicts the most with others # in case of a tie, remove one",
"ONZ.O_PLUS elif order == (3, 2, 1): return ONZ.O_MINUS elif order == (1,",
"residue, ions in self.ions_outside.items(): result.append(f'{residue.full_name}: [{\",\".join([ion.atomName for ion in ions])}]') return 'ions_outside=' +",
"Optional, Set import numpy from eltetrado.model import Atom3D, Structure3D, Structure2D, BasePair3D, Residue3D, GlycosidicBond,",
"i in range(4)]) score_sequential = sum(score_sequential) score_stacking = sum(score_stacking) if (score, score_sequential, score_stacking)",
"Ion, Direction, LoopType, ONZM, GbaQuadruplexClassification, LoopClassification logging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"INFO\")) @dataclass(order=True) class Tetrad: @staticmethod def",
"return None def __find_tract_with_nt(self, nt: Residue3D) -> Optional[Tract]: for tract in self.tracts: if",
"List[Tetrad] complete2d: bool onz_dict: Dict[BasePair3D, ONZ] = field(init=False) def __post_init__(self): self.onz_dict = {pair:",
"= self.onz_dict[pair] helix.write(f'{x}\\t{y}\\t1\\t{onz_value.get(onz, 7)}\\n') if canonical: for pair in canonical: x, y =",
"best_order = order if best_score == (len(self.tetrads) - 1) * 4: break tetrad_pairs",
"self.__find_loops() self.loop_class = self.__classify_by_loops() def __classify_onzm(self) -> Optional[ONZM]: if len(self.tetrads) == 1: return",
"self.nt3, self.nt2, self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse() elif",
"classifications) chain_order_score = self.__chain_order_score(permutation) score = (onz_score, chain_order_score) if score < best_score: best_score",
"== nk: self.nt1, self.nt2, self.nt3, self.nt4 = self.nt3, self.nt4, self.nt1, self.nt2 self.pair_12, self.pair_23,",
"line2, shifts def __elimination_conflicts(self, pairs: List[BasePair3D]) -> Tuple[str, str, Dict[Residue3D, int]]: orders =",
"an ion, because it is too far from any tetrad (distance={min_distance})') for tetrad,",
"others # in case of a tie, remove one which has the worst",
"str): fasta = tempfile.NamedTemporaryFile('w+', suffix='.fasta') fasta.write(f'>{prefix}-{suffix}\\n') fasta.write(self.analysis.sequence) fasta.flush() layer1, layer2 = [], []",
"+= '-' shift_value += 1 sequence += nt.one_letter_name structure += dotbracket.get(nt, '.') shifts[nt]",
"tetrad.ions_outside[residue] = ions def __generate_twoline_dotbracket(self) -> Tuple[str, str, str, Dict[Residue3D, int]]: layer1, layer2",
"best_score = 0 best_score_sequential = 0 best_score_stacking = 0 best_order = tj.nucleotides n1,",
"pair_dictionary[(nt1, nt2)].lw lw2 = pair_dictionary[(nt2, nt3)].lw lw3 = pair_dictionary[(nt3, nt4)].lw lw4 = pair_dictionary[(nt4,",
"' '.join(result) return '' @dataclass class TetradPair: tetrad1: Tetrad tetrad2: Tetrad stacked: Dict[Residue3D,",
"self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12 elif nmin == nk:",
"any([group.issuperset(candidate) for group in groups]): continue groups.append(candidate) return sorted([sorted(group) for group in groups],",
"changed = True break candidates = sorted(candidates, key=lambda x: len(x), reverse=True) groups =",
"GbaTetradClassification.VIIIb } if fingerprint not in gba_classes: logging.error(f'Impossible combination of syn/anti: {[nt.chi_class for",
"tetrads: List[Tetrad] = field(init=False) tetrad_scores: Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]] = field(init=False) tetrad_pairs:",
"return None if any([t.onz is None for t in self.tetrads]): return None counter",
"nt1.chain == nt2.chain and abs(nt1.index - nt2.index) == 1 tetrad_scores = defaultdict(dict) for",
"__group_related_chains(self) -> List[List[str]]: candidates = set() for h in self.helices: for t in",
"n1), (n3, n2, n1, n4), (n2, n1, n4, n3)] for nts2 in viable_permutations:",
"tetrad_pair.tetrad2_nts_best_order[0], tetrad_pair.tetrad1.nt2: tetrad_pair.tetrad2_nts_best_order[1], tetrad_pair.tetrad1.nt3: tetrad_pair.tetrad2_nts_best_order[2], tetrad_pair.tetrad1.nt4: tetrad_pair.tetrad2_nts_best_order[3], } for i in range(4): tracts[i].append(nt_dict[tracts[i][-1]])",
"return LoopType.from_value(f'propeller{sign}') logging.warning(f'Failed to classify the loop between {nt_first} and {nt_last}') return None",
"< best_score: best_score = score best_permutation = permutation elif score == best_score: #",
"self.pair_12, self.pair_23, self.pair_34 # flip order if necessary if self.pair_12.score() > self.pair_41.reverse().score(): self.nt1,",
"tracts: List[Tract] = field(init=False) loops: List[Loop] = field(init=False) loop_class: Optional[LoopClassification] = field(init=False) def",
"ys = (coord[1] for coord in coords) zs = (coord[2] for coord in",
"GbaQuadruplexClassification, LoopClassification logging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"INFO\")) @dataclass(order=True) class Tetrad: @staticmethod def is_valid(nt1: Residue3D, nt2: Residue3D,",
"else: raise RuntimeError(f'Cannot apply order: {order}') self.nt1, self.nt2, self.nt3, self.nt4 = order def",
"is not None: return LoopType.from_value(f'lateral{sign}') return LoopType.diagonal tract_with_last = self.__find_tract_with_nt(nt_last) if tract_with_last is",
"-1.0, 1.0))) def __str__(self): return f' direction={self.direction.value} rise={round(self.rise, 2)} twist={round(self.twist, 2)}\\n' @dataclass class",
"outer = [nt.outermost_atom for nt in self.nucleotides] inner = [nt.innermost_atom for nt in",
"Tuple[str, str, str, Dict[Residue3D, int]]: layer1, layer2 = [], [] for tetrad in",
"orders = dict() order = 0 queue = list(pairs) removed = [] while",
"and ncur.chain == nprev.chain: for tract in self.tracts: if nprev in tract.nucleotides and",
"+ 1 + shifts[y] onz = self.onz_dict[pair] helix.write(f'{x}\\t{y}\\t1\\t{onz_value.get(onz, 7)}\\n') if canonical: for pair",
"0 for i in range(4)] score = sum([max(score_stacking[i], score_sequential[i]) for i in range(4)])",
"if nmin == ni: pass elif nmin == nj: self.nt1, self.nt2, self.nt3, self.nt4",
"min_tetrad.nt1 for tetrad in self.tetrads: for nt in tetrad.nucleotides: for atom in nt.atoms:",
"self.__calculate_planarity_deviation() def reorder_to_match_5p_3p(self): # transform into (0, 1, 2, 3) ni, nj, nk,",
"candidates = set() for h in self.helices: for t in h.tetrads: candidates.add(frozenset([t.nt1.chain, t.nt2.chain,",
"= [] for h in self.helices: for t in h.tetrads: for p in",
"tp.stacked[tp.tetrad1.nt4]) tp.tetrad2.reorder_to_match_5p_3p() # this is required to recalculate ONZ tp.tetrad2.reorder_to_match_other_tetrad(order) def __chain_order_score(self, chain_order:",
"= 0 for c1, c2 in chain_pairs: sum_sq += (chain_order.index(c1) - chain_order.index(c2)) **",
"Residue3D, Residue3D]): if order == (self.nt1, self.nt2, self.nt3, self.nt4): pass elif order ==",
"first and last nt of a loop is in the same tetrad sign",
"= (stacked[ti.nt1], stacked[ti.nt2], stacked[ti.nt3], stacked[ti.nt4]) tj.reorder_to_match_other_tetrad(order) return tetrad_pairs def __find_helices(self): helices = []",
"t in self.tetrads: gba = t.gba_class if gba is not None: gbas.add(gba.value[:-1]) #",
"loop_classes: logging.error(f'Unknown loop classification: {fingerprint}') return None subtype = 'a' if self.loops[0 if",
"1 + shifts[y] onz = self.onz_dict[pair] helix.write(f'{x}\\t{y}\\t1\\t{onz_value.get(onz, 7)}\\n') if canonical: for pair in",
"...]) -> int: chain_pairs = [] for h in self.helices: for t in",
"'aass': GbaTetradClassification.Ia, 'ssaa': GbaTetradClassification.Ib, 'asas': GbaTetradClassification.IIa, 'sasa': GbaTetradClassification.IIb, 'asaa': GbaTetradClassification.IIIa, 'sass': GbaTetradClassification.IIIb, 'aaas':",
"v2 / numpy.linalg.norm(v2) return math.degrees(numpy.arccos(numpy.clip(numpy.dot(v1, v2), -1.0, 1.0))) def __str__(self): return f' direction={self.direction.value}",
"0: self.tetrad_pairs[0].tetrad1.reorder_to_match_5p_3p() for tp in self.tetrad_pairs: order = (tp.stacked[tp.tetrad1.nt1], tp.stacked[tp.tetrad1.nt2], tp.stacked[tp.tetrad1.nt3], tp.stacked[tp.tetrad1.nt4]) tp.tetrad2.reorder_to_match_5p_3p()",
"os.path.dirname(os.path.realpath(__file__)) output_pdf = f'{prefix}-{suffix}.pdf' run = subprocess.run([os.path.join(currdir, 'quadraw.R'), fasta.name, helix1.name, helix2.name, output_pdf], stdout=subprocess.PIPE,",
"= [set(c) for c in candidates] changed = True while changed: changed =",
"Dict[Residue3D, Residue3D] tetrad2_nts_best_order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D] = field(init=False) direction: Direction = field(init=False)",
"tetrads\\n' builder += str(self.tetrad_pairs[0].tetrad1) for tetrad_pair in self.tetrad_pairs: builder += str(tetrad_pair) builder +=",
"- nt1_2.find_atom(\"C1'\").coordinates() v1 = v1 / numpy.linalg.norm(v1) v2 = nt2_1.find_atom(\"C1'\").coordinates() - nt2_2.find_atom(\"C1'\").coordinates() v2",
"= field(init=False) tetrad_pairs: List[TetradPair] = field(init=False) helices: List[Helix] = field(init=False) ions: List[Atom3D] =",
"__find_tetrads(self, no_reorder=False) -> List[Tetrad]: # search for a tetrad: i -> j ->",
"numpy.linalg.norm(ion.coordinates() - tetrad.center()) if distance < min_distance: min_distance = distance min_tetrad = tetrad",
"score_stacking best_order = nts2 if best_score == 4: break tetrad_scores[ti][tj] = (best_score, nts1,",
"ONZ.O_MINUS elif order == (1, 3, 2): return ONZ.N_PLUS elif order == (2,",
"not t.chains().isdisjoint(chains) def check_pair(tp: TetradPair) -> bool: return check_tetrad(tp.tetrad1) and check_tetrad(tp.tetrad2) return list(filter(check_pair,",
"if not self.no_reorder: self.__find_best_chain_order() self.sequence, self.line1, self.line2, self.shifts = self.__generate_twoline_dotbracket() self.ions = self.__find_ions()",
"builder += f' quadruplex with {len(self.tetrads)} tetrads\\n' builder += str(self.tetrad_pairs[0].tetrad1) for tetrad_pair in",
"__classify_onz(self) -> ONZ: # transform into (0, 1, 2, 3) ni, nj, nk,",
"[Quadruplex(self.tetrads, [], self.structure3d)] quadruplexes = list() tetrads = list() for tetrad in [self.tetrad_pairs[0].tetrad1]",
"= self.__elimination_conflicts(layer2) return sequence, line1, line2, shifts def __elimination_conflicts(self, pairs: List[BasePair3D]) -> Tuple[str,",
"in tract_with_last.nucleotides: if nt in tetrad_with_first.nucleotides: sign = self.__detect_loop_sign(nt_first, nt, tetrad_with_first) if sign",
"1 tetrad_scores = defaultdict(dict) for ti, tj in itertools.combinations(self.tetrads, 2): nts1 = ti.nucleotides",
"self.graph[i], self.graph[k]): if Tetrad.is_valid(i, j, k, l, self.pair_dict): tetrads.add(frozenset([i, j, k, l])) if",
"return ONZ.N_MINUS elif order == (2, 1, 3): return ONZ.Z_PLUS elif order ==",
"if gba is not None: gbas.add(gba.value[:-1]) # discard 'a' or 'b' subvariant roman_numerals",
"i)] tetrads.append(Tetrad(i, j, k, l, pair_12, pair_23, pair_34, pair_41)) # build graph of",
"(i, j), self.base_pair_graph[j]): for l in filter(lambda x: x not in (i, j,",
"self.nt3, self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() # ONZ",
"set(self.tetrads) - {ti} while candidates: tj = max([tj for tj in candidates], key=lambda",
"for helix in helices]): helices.append(Helix([tetrad], [], self.structure3d)) return helices def __find_best_chain_order(self): chain_groups =",
"= closing[order] sequence = '' structure = '' shifts = dict() shift_value =",
"ti.nucleotides best_score = 0 best_score_sequential = 0 best_score_stacking = 0 best_order = tj.nucleotides",
"self.nt1, self.nt2, self.nt3, self.nt4 = order def __classify_onz(self) -> ONZ: # transform into",
"__elimination_conflicts(self, pairs: List[BasePair3D]) -> Tuple[str, str, Dict[Residue3D, int]]: orders = dict() order =",
"Chemistry - A European Journal, 13(35), 9738–9745. https://doi.org/10.1002/chem.200701255 :return: Classification according to Webba",
"Residue3D], BasePair3D] = structure3d.base_pair_dict(structure2d) def has_tetrads(self): tetrads = set() for i in self.graph:",
"j in zip(indices1, indices2)) direction, count = counter.most_common()[0] if count == 4: #",
"> 0 else -1 for i, j in zip(indices1, indices2)) direction, count =",
"in self.ions_outside.items(): result.append(f'{residue.full_name}: [{\",\".join([ion.atomName for ion in ions])}]') return 'ions_outside=' + ' '.join(result)",
"fingerprint not in gba_classes: logging.error(f'Impossible combination of syn/anti: {[nt.chi_class for nt in self.nucleotides]}')",
"\".join(map(lambda onz: onz.value, classifications))}') self.tetrads = self.__find_tetrads(True) self.tetrad_scores = self.__calculate_tetrad_scores() self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch)",
"def __str__(self): return f' {self.loop_type.value if self.loop_type else \"n/a\"} ' \\ f'{\", \".join(map(lambda",
"Tuple, Tuple]]]: def is_next_by_stacking(nt1: Residue3D, nt2: Residue3D) -> bool: return nt2 in self.stacking_graph.get(nt1,",
"(len(self.tetrads) - 1) * 4: break tetrad_pairs = [] for i in range(1,",
"structure += dotbracket.get(nt, '.') shifts[nt] = shift_value chain = nt.chain return sequence, structure,",
"shifts: Dict[Residue3D, int] = field(init=False) def __post_init__(self): self.base_pairs = self.structure3d.base_pairs(self.structure2d) self.base_pair_graph = self.structure3d.base_pair_graph(self.structure2d,",
"n2, n3, n4 = tj.nucleotides viable_permutations = [(n1, n2, n3, n4), (n2, n3,",
"tract in self.tracts: if nt in tract.nucleotides: return tract return None def __detect_loop_sign(self,",
"tetrads.add(frozenset([i, j, k, l])) if len(tetrads) > 1: return True return False def",
"score += self.tetrad_scores[ti][tj][0] order.append(tj) candidates.remove(tj) ti = tj if score > best_score: best_score",
"(distance={min_distance})') for tetrad, ions in ions_channel.items(): tetrad.ions_channel = ions for pair, ions in",
"far from any tetrad (distance={min_distance})') for tetrad, ions in ions_channel.items(): tetrad.ions_channel = ions",
"break candidates = sorted(candidates, key=lambda x: len(x), reverse=True) groups = [] for candidate",
"not self.no_reorder: self.__find_best_chain_order() self.sequence, self.line1, self.line2, self.shifts = self.__generate_twoline_dotbracket() self.ions = self.__find_ions() self.__assign_ions_to_tetrads()",
"= [nt.outermost_atom for nt in self.nucleotides] inner = [nt.innermost_atom for nt in self.nucleotides]",
"int) -> Analysis: return Analysis(structure2d, structure3d, strict, no_reorder, stacking_mismatch) def has_tetrad(structure2d: Structure2D, structure3d:",
"# TODO: verify threshold of 6A between an ion and tetrad channel if",
"in self.loops]) if fingerprint not in loop_classes: logging.error(f'Unknown loop classification: {fingerprint}') return None",
"List[Tetrad]: # search for a tetrad: i -> j -> k -> l",
"+ ' '.join(result) return '' @dataclass class TetradPair: tetrad1: Tetrad tetrad2: Tetrad stacked:",
"elif order == (self.nt1, self.nt4, self.nt3, self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(),",
"max([tj for tj in candidates], key=lambda tk: self.tetrad_scores[ti][tk][0]) score += self.tetrad_scores[ti][tj][0] order.append(tj) candidates.remove(tj)",
"'' structure = '' shifts = dict() shift_value = 0 chain = None",
"= pair_dictionary[(nt2, nt3)].lw lw3 = pair_dictionary[(nt3, nt4)].lw lw4 = pair_dictionary[(nt4, nt1)].lw for lw_i,",
"f'{self.pair_12.lw.value} {self.pair_23.lw.value} {self.pair_34.lw.value} {self.pair_41.lw.value} ' \\ f'{self.onz.value} {self.gba_class.value} ' \\ f'planarity={round(self.planarity_deviation, 2)} '",
"for loop in self.loops: builder += f'{loop}\\n' builder += '\\n' return builder @dataclass",
"= list(map(lambda nt: nt.index, self.tetrad2_nts_best_order)) # count directions 5' -> 3' as +1",
"tp.tetrad2 if not helix_tetrads: helix_tetrads.append(ti) score = self.tetrad_scores[helix_tetrads[-1]][tj][0] if score >= (4 -",
"== (self.nt4, self.nt1, self.nt2, self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23,",
"import Atom3D, Structure3D, Structure2D, BasePair3D, Residue3D, GlycosidicBond, ONZ, \\ GbaTetradClassification, Ion, Direction, LoopType,",
"'plp': '3', 'lpp': '4', 'pdp': '5', 'lll': '6', 'llp': '7', 'lpl': '8', 'pll':",
"j, k, l, pair_12, pair_23, pair_34, pair_41)) # build graph of tetrads while",
"t.pair_41]: c1 = p.nt1.chain c2 = p.nt2.chain if c1 != c2 and c1",
"in self.nucleotides]}') return None return gba_classes[fingerprint] def __calculate_planarity_deviation(self) -> float: outer = [nt.outermost_atom",
"float: outer = [nt.outermost_atom for nt in self.nucleotides] inner = [nt.innermost_atom for nt",
"Direction.parallel elif count == 2: # two in +, one in - direction",
"h in self.helices for t in h.tetrads] logging.debug(f'Selected chain order: {\" \".join(final_order)} '",
"self.pair_23 elif order == (self.nt4, self.nt1, self.nt2, self.nt3): self.pair_12, self.pair_23, self.pair_34, self.pair_41 =",
"if order == (1, 2, 3): return ONZ.O_PLUS elif order == (3, 2,",
"the worst planarity deviation candidates = sorted(tetrads, key=lambda t: (len(graph[t]), t.planarity_deviation), reverse=True) if",
"return loops def __detect_loop_type(self, nt_first: Residue3D, nt_last: Residue3D) -> Optional[LoopType]: tetrad_with_first = self.__find_tetrad_with_nt(nt_first)",
"' \\ f'{self.__ions_outside_str()}\\n' def chains(self) -> Set[str]: return set([nt.chain for nt in self.nucleotides])",
"None # this will create a 4-letter string made of 's' for syn",
"t1 = self.tetrad1.outer_and_inner_atoms() t2 = self.tetrad2.outer_and_inner_atoms() return numpy.linalg.norm(center_of_mass(t1) - center_of_mass(t2)) def __calculate_twist(self) ->",
"[] for i in range(1, len(best_order)): ti, tj = best_order[i - 1], best_order[i]",
"[] for candidate in candidates: if any([group.issuperset(candidate) for group in groups]): continue groups.append(candidate)",
"[tp] if helix_tetrads: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) for tetrad in self.tetrads: if not any([tetrad",
"ti in tetrads: score = 0 order = [ti] candidates = set(self.tetrads) -",
"nt.index, self.nucleotides) indices = sorted((ni, nj, nk, nl)) ni, nj, nk, nl =",
"= ')]}>' + string.ascii_lowercase dotbracket = dict() for pair, order in orders.items(): nt1,",
"classifications = [t.onz for h in self.helices for t in h.tetrads] logging.debug( f'Checking",
"for tp in self.tetrad_pairs: order = (tp.stacked[tp.tetrad1.nt1], tp.stacked[tp.tetrad1.nt2], tp.stacked[tp.tetrad1.nt3], tp.stacked[tp.tetrad1.nt4]) tp.tetrad2.reorder_to_match_5p_3p() # this",
"!= nt.chain: sequence += '-' structure += '-' shift_value += 1 sequence +=",
"\\ list(map(lambda residue: residue.innermost_atom, self.nucleotides)) def __ions_channel_str(self) -> str: if self.ions_channel: return 'ions_channel='",
"= self.tetrad_scores[ti][tj][1:] stacked = {nts1[i]: nts2[i] for i in range(4)} stacked.update({v: k for",
"self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() else: raise RuntimeError(f'Cannot apply order: {order}')",
"else 'b' return LoopClassification.from_value(f'{loop_classes[fingerprint]}{subtype}') def __str__(self): builder = '' if len(self.tetrads) == 1:",
"[tetrad_pair.tetrad2 for tetrad_pair in self.tetrad_pairs]: if tetrads: if tetrad.chains().isdisjoint(tetrads[-1].chains()): quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d)) tetrads",
"@dataclass class Analysis: structure2d: Structure2D structure3d: Structure3D strict: bool no_reorder: bool stacking_mismatch: int",
"Tuple[int, Tuple, Tuple]]] = field(init=False) tetrad_pairs: List[TetradPair] = field(init=False) helices: List[Helix] = field(init=False)",
"'single tetrad without stacking\\n' builder += str(self.tetrads[0]) return builder @dataclass class Analysis: structure2d:",
"= field(init=False) def __post_init__(self): self.quadruplexes = self.__find_quadruplexes() def __find_quadruplexes(self): if len(self.tetrad_pairs) == 0:",
"self.loop_type else \"n/a\"} ' \\ f'{\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}' @dataclass class Quadruplex:",
"anti fingerprint = ''.join([nt.chi_class.value[0] for nt in self.nucleotides]) # this dict has all",
"group in groups], key=lambda x: x[0]) def __reorder_chains(self, chain_order: Iterable[str]): i = 1",
"x: x not in (i, j, k) and x in self.graph[i], self.graph[k]): if",
"1, 2, 3) ni, nj, nk, nl = map(lambda nt: nt.index, self.nucleotides) indices",
"-> List[TetradPair]: chains = set() for tetrad in tetrads: chains.update(tetrad.chains()) def check_tetrad(t: Tetrad)",
"@property def nucleotides(self) -> Tuple[Residue3D, Residue3D, Residue3D, Residue3D]: return self.nt1, self.nt2, self.nt3, self.nt4",
"__generate_twoline_dotbracket(self) -> Tuple[str, str, str, Dict[Residue3D, int]]: layer1, layer2 = [], [] for",
"List[TetradPair] = field(init=False) helices: List[Helix] = field(init=False) ions: List[Atom3D] = field(init=False) sequence: str",
"self.pair_34 elif order == (self.nt4, self.nt3, self.nt2, self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41 =",
"p in [t.pair_12, t.pair_23, t.pair_34, t.pair_41]: c1 = p.nt1.chain c2 = p.nt2.chain if",
"tetrad in self.tetrads for pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]} def visualize(self, prefix:",
"+= '\\n Loops:\\n' for loop in self.loops: builder += f'{loop}\\n' builder += '\\n'",
"'.') shifts[nt] = shift_value chain = nt.chain return sequence, structure, shifts def __str__(self):",
"numpy.array((sum(xs) / len(coords), sum(ys) / len(coords), sum(zs) / len(coords))) def eltetrado(structure2d: Structure2D, structure3d:",
"tetrad1: Tetrad tetrad2: Tetrad stacked: Dict[Residue3D, Residue3D] tetrad2_nts_best_order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D] =",
"t in h.tetrads: for p in [t.pair_12, t.pair_23, t.pair_34, t.pair_41]: c1 = p.nt1.chain",
"output_pdf], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if run.returncode == 0: print('\\nPlot:', output_pdf) else: logging.error(f'Failed to prepare",
"{ni} {nj} {nk} {nl}') def __classify_by_gba(self) -> Optional[GbaTetradClassification]: \"\"\" See: <NAME>. (2007). Geometric",
"Structure3D, Structure2D, BasePair3D, Residue3D, GlycosidicBond, ONZ, \\ GbaTetradClassification, Ion, Direction, LoopType, ONZM, GbaQuadruplexClassification,",
"return tetrad return None def __find_tract_with_nt(self, nt: Residue3D) -> Optional[Tract]: for tract in",
"for ti, tj in itertools.combinations(self.tetrads, 2): nts1 = ti.nucleotides best_score = 0 best_score_sequential",
"in range(4): tracts[i].append(nt_dict[tracts[i][-1]]) return [Tract(nts) for nts in tracts] def __find_loops(self) -> List[Loop]:",
"stacking_mismatch: int base_pairs: List[BasePair3D] = field(init=False) base_pair_graph: Dict[Residue3D, List[Residue3D]] = field(init=False) base_pair_dict: Dict[Tuple[Residue3D,",
"int]]: layer1, layer2 = [], [] for tetrad in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23,",
"ni, nj, nk, nl = (nt.index for nt in self.nucleotides) indices = sorted((ni,",
"y = nucleotides.index(x) + 1 + shifts[x], nucleotides.index(y) + 1 + shifts[y] onz",
"List[BasePair3D], canonical: Optional[List[BasePair3D]] = None) -> tempfile.NamedTemporaryFile(): onz_value = {ONZ.O_PLUS: 1, ONZ.O_MINUS: 2,",
"{ tetrad_pair.tetrad1.nt1: tetrad_pair.tetrad2_nts_best_order[0], tetrad_pair.tetrad1.nt2: tetrad_pair.tetrad2_nts_best_order[1], tetrad_pair.tetrad1.nt3: tetrad_pair.tetrad2_nts_best_order[2], tetrad_pair.tetrad1.nt4: tetrad_pair.tetrad2_nts_best_order[3], } for i in",
"= [ti, tj] helix_tetrad_pairs = [tp] if helix_tetrads: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) for tetrad",
"self.nt2, self.nt3, self.nt4 = self.nt2, self.nt3, self.nt4, self.nt1 self.pair_12, self.pair_23, self.pair_34, self.pair_41 =",
"nl)) nmin = min(ni, nj, nk, nl) if nmin == ni: pass elif",
"self.stacking_mismatch): helix_tetrads.append(tj) helix_tetrad_pairs.append(tp) else: helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) helix_tetrads = [ti, tj] helix_tetrad_pairs =",
"for atom in nt.atoms: distance = numpy.linalg.norm(ion.coordinates() - atom.coordinates()) if distance < min_distance:",
"pair_41: BasePair3D onz: ONZ = field(init=False) gba_class: Optional[GbaTetradClassification] = field(init=False) planarity_deviation: float =",
"ncur.chain == nprev.chain: for tract in self.tracts: if nprev in tract.nucleotides and ncur",
"for tetrad in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41]) helix1 = self.__to_helix(layer1, self.analysis.canonical() if",
"tetrad.nucleotides: for atom in nt.atoms: distance = numpy.linalg.norm(ion.coordinates() - atom.coordinates()) if distance <",
"pair in layer: x, y = pair.nt1, pair.nt2 x, y = nucleotides.index(x) +",
"self.base_pairs if base_pair.is_canonical()] @dataclass class Visualizer: analysis: Analysis tetrads: List[Tetrad] complete2d: bool onz_dict:",
"__post_init__(self): self.quadruplexes = self.__find_quadruplexes() def __find_quadruplexes(self): if len(self.tetrad_pairs) == 0: return [Quadruplex(self.tetrads, [],",
"+= str(self.tetrads[0]) return builder @dataclass class Analysis: structure2d: Structure2D structure3d: Structure3D strict: bool",
"= 0 chain = None for nt in sorted(filter(lambda nt: nt.is_nucleotide, self.structure3d.residues), key=lambda",
"for i in range(4)] score_sequential = [1 if is_next_sequentially(nts1[i], nts2[i]) else 0 for",
"bool onz_dict: Dict[BasePair3D, ONZ] = field(init=False) def __post_init__(self): self.onz_dict = {pair: tetrad.onz for",
"key=lambda x: (len(x[1]), x[0].nt1)) removed.append(pair) queue.remove(pair) else: orders.update({pair: order for pair in queue})",
"def check_tetrad(t: Tetrad) -> bool: return not t.chains().isdisjoint(chains) def check_pair(tp: TetradPair) -> bool:",
"coords = [atom.coordinates() for atom in atoms] xs = (coord[0] for coord in",
"-> str: if self.ions_channel: return 'ions_channel=' + ','.join([atom.atomName for atom in self.ions_channel]) return",
"is not None: # search along the tract to check what pairs with",
"check if pair.nt1 == last and pair.nt2 == first: if pair.score() < pair.reverse().score():",
"self.base_pair_graph: for j in filter(lambda x: x != i, self.base_pair_graph[i]): for k in",
"n1, n2, n3, n4 = tj.nucleotides viable_permutations = [(n1, n2, n3, n4), (n2,",
"= (indices.index(x) for x in (ni, nj, nk, nl)) while ni != 0:",
"tetrad_pair.tetrad1.nt1: tetrad_pair.tetrad2_nts_best_order[0], tetrad_pair.tetrad1.nt2: tetrad_pair.tetrad2_nts_best_order[1], tetrad_pair.tetrad1.nt3: tetrad_pair.tetrad2_nts_best_order[2], tetrad_pair.tetrad1.nt4: tetrad_pair.tetrad2_nts_best_order[3], } for i in range(4):",
"in atoms] xs = (coord[0] for coord in coords) ys = (coord[1] for",
"len(tetrad_nucleotides)): nprev = tetrad_nucleotides[i - 1] ncur = tetrad_nucleotides[i] if ncur.index - nprev.index",
"one in - direction return Direction.antiparallel return Direction.hybrid def __calculate_rise(self) -> float: t1",
"classify the loop between {nt_first} and {nt_last}') return None if tetrad_with_first == tetrad_with_last:",
"__find_helices(self): helices = [] helix_tetrads = [] helix_tetrad_pairs = [] for tp in",
"= score, score_sequential, score_stacking best_order = nts2 if best_score == 4: break tetrad_scores[ti][tj]",
"counter = Counter([t.onz.value[0] for t in self.tetrads]) onz, support = counter.most_common()[0] if support",
"return helix class AnalysisSimple: def __init__(self, structure2d: Structure2D, structure3d: Structure3D): self.pairs: List[BasePair3D] =",
"x in self.graph[i], self.graph[k]): if Tetrad.is_valid(i, j, k, l, self.pair_dict): tetrads.add(frozenset([i, j, k,",
"Residue3D) -> bool: return nt1.chain == nt2.chain and abs(nt1.index - nt2.index) == 1",
"t2 = self.tetrad2.outer_and_inner_atoms() return numpy.linalg.norm(center_of_mass(t1) - center_of_mass(t2)) def __calculate_twist(self) -> float: nt1_1, nt1_2,",
"nts2 in viable_permutations: score_stacking = [1 if is_next_by_stacking(nts1[i], nts2[i]) else 0 for i",
"-> ONZ: # transform into (0, 1, 2, 3) ni, nj, nk, nl",
"< pair.reverse().score(): return '-' return '+' # reverse check if pair.nt1 == last",
"self.strict) self.base_pair_dict = self.structure3d.base_pair_dict(self.structure2d, self.strict) self.stacking_graph = self.structure3d.stacking_graph(self.structure2d) self.tetrads = self.__find_tetrads(self.no_reorder) self.tetrad_scores =",
"self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse() elif order == (self.nt1, self.nt4, self.nt3, self.nt2): self.pair_12, self.pair_23, self.pair_34,",
"if atom.atomName.upper() in metal_atom_names: coordinates = tuple(atom.coordinates()) if coordinates not in used: ions.append(atom)",
"f' {self.loop_class.value} {self.loop_class.loop_progression()}' else: builder += f' n/a' builder += f' quadruplex with",
"defaultdict(list) for (ti, tj) in itertools.combinations(tetrads, 2): if not ti.is_disjoint(tj): graph[ti].append(tj) graph[tj].append(ti) #",
"{nt_first} and {nt_last}') return None if tetrad_with_first == tetrad_with_last: # diagonal or laterals",
"candidates[j] changed = True break candidates = sorted(candidates, key=lambda x: len(x), reverse=True) groups",
"defaultdict(list) ions_outside = defaultdict(list) for ion in self.ions: min_distance = math.inf min_tetrad =",
"sign is not None: return LoopType.from_value(f'propeller{sign}') logging.warning(f'Failed to classify the loop between {nt_first}",
"best_permutation, best_score = chains, (1e10, 1e10) if len(chains) > 1: for permutation in",
"Residue3D, Residue3D, Residue3D] = field(init=False) direction: Direction = field(init=False) rise: float = field(init=False)",
"order == (self.nt3, self.nt2, self.nt1, self.nt4): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23.reverse(), self.pair_12.reverse(),",
"v1 / numpy.linalg.norm(v1) v2 = nt2_1.find_atom(\"C1'\").coordinates() - nt2_2.find_atom(\"C1'\").coordinates() v2 = v2 / numpy.linalg.norm(v2)",
"classify the loop between {nt_first} and {nt_last}') return None def __find_tetrad_with_nt(self, nt: Residue3D)",
"} fingerprint = ''.join([loop.loop_type.value[0] for loop in self.loops]) if fingerprint not in loop_classes:",
"in self.tetrads for pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]} def visualize(self, prefix: str,",
"= self.tetrad2_nts_best_order v1 = nt1_1.find_atom(\"C1'\").coordinates() - nt1_2.find_atom(\"C1'\").coordinates() v1 = v1 / numpy.linalg.norm(v1) v2",
"nprev in tract.nucleotides and ncur in tract.nucleotides: break else: nts = list(filter(lambda nt:",
"self.nt4, self.nt1, self.nt2): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23 elif",
"self.pair_23, self.pair_34, self.pair_41 = self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse() elif order == (self.nt3, self.nt2,",
"def __find_ions(self) -> List[Atom3D]: metal_atom_names = set([ion.value.upper() for ion in Ion]) ions =",
"+= 1 if len(self.tetrad_pairs) > 0: self.tetrad_pairs[0].tetrad1.reorder_to_match_5p_3p() for tp in self.tetrad_pairs: order =",
"self.__elimination_conflicts(layer2) return sequence, line1, line2, shifts def __elimination_conflicts(self, pairs: List[BasePair3D]) -> Tuple[str, str,",
"((lw1, lw4), (lw2, lw1), (lw3, lw2), (lw4, lw3)): if lw_i.name[1] == lw_j.name[2]: return",
"'VIII': 8} gbas = sorted(gbas, key=lambda gba: roman_numerals.get(gba, 100)) return list(map(lambda x: GbaQuadruplexClassification[x],",
"Direction.hybrid def __calculate_rise(self) -> float: t1 = self.tetrad1.outer_and_inner_atoms() t2 = self.tetrad2.outer_and_inner_atoms() return numpy.linalg.norm(center_of_mass(t1)",
"Tuple]]]: def is_next_by_stacking(nt1: Residue3D, nt2: Residue3D) -> bool: return nt2 in self.stacking_graph.get(nt1, [])",
"n2, n1, n4), (n2, n1, n4, n3)] for nts2 in viable_permutations: score_stacking =",
"self.nt4, self.nt3, self.nt2 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() #",
"tetrads: List[Tetrad]) -> List[TetradPair]: chains = set() for tetrad in tetrads: chains.update(tetrad.chains()) def",
"= field(init=False) line1: str = field(init=False) line2: str = field(init=False) shifts: Dict[Residue3D, int]",
"candidates = sorted(tetrads, key=lambda t: (len(graph[t]), t.planarity_deviation), reverse=True) if len(graph[candidates[0]]) > 0: tetrads.remove(candidates[0])",
"self.nt4, self.nt1, self.nt2, self.nt3 self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34",
"and da Silva's classification are valid in 5'-3' order self.onz = self.__classify_onz() self.gba_class",
"self.base_pair_graph[i]): for k in filter(lambda x: x not in (i, j), self.base_pair_graph[j]): for",
"stacked[ti.nt4]) tj.reorder_to_match_other_tetrad(order) return tetrad_pairs def __find_helices(self): helices = [] helix_tetrads = [] helix_tetrad_pairs",
"if len(chains) > 1: for permutation in itertools.permutations(chains): self.__reorder_chains(permutation) classifications = [t.onz for",
"candidates = [set(c) for c in candidates] changed = True while changed: changed",
"[t.pair_12, t.pair_23, t.pair_34, t.pair_41]: c1 = p.nt1.chain c2 = p.nt2.chain if c1 !=",
"RuntimeError(f'Cannot apply order: {order}') self.nt1, self.nt2, self.nt3, self.nt4 = order def __classify_onz(self) ->",
"helix2 = self.__to_helix(layer2) currdir = os.path.dirname(os.path.realpath(__file__)) output_pdf = f'{prefix}-{suffix}.pdf' run = subprocess.run([os.path.join(currdir, 'quadraw.R'),",
"coordinates not in used: ions.append(atom) used.add(coordinates) return ions def __assign_ions_to_tetrads(self) \\ -> Tuple[Dict[Tetrad,",
"other) -> bool: return frozenset(self.nucleotides).isdisjoint(frozenset(other.nucleotides)) def center(self) -> numpy.ndarray: return center_of_mass(self.outer_and_inner_atoms()) def outer_and_inner_atoms(self)",
"structure3d.base_pair_dict(structure2d) def has_tetrads(self): tetrads = set() for i in self.graph: for j in",
"+ 1}\\n') helix.write('i\\tj\\tlength\\tvalue\\n') for pair in layer: x, y = pair.nt1, pair.nt2 x,",
"or 'b' subvariant roman_numerals = {'I': 1, 'II': 2, 'III': 3, 'IV': 4,",
"count == 2: # two in +, one in - direction return Direction.antiparallel",
"Tuple[Residue3D, Residue3D, Residue3D, Residue3D]: return self.nt1, self.nt2, self.nt3, self.nt4 def __hash__(self): return hash(frozenset([self.nt1,",
"+= str(tetrad_pair.tetrad2) if self.tracts: builder += '\\n Tracts:\\n' for tract in self.tracts: builder",
"> 1: self.__reorder_chains(final_order) classifications = [t.onz for h in self.helices for t in",
"GbaTetradClassification.IIb, 'asaa': GbaTetradClassification.IIIa, 'sass': GbaTetradClassification.IIIb, 'aaas': GbaTetradClassification.IVa, 'sssa': GbaTetradClassification.IVb, 'aasa': GbaTetradClassification.Va, 'ssas': GbaTetradClassification.Vb,",
"0 for c1, c2 in chain_pairs: sum_sq += (chain_order.index(c1) - chain_order.index(c2)) ** 2",
"n3, n4), (n2, n3, n4, n1), (n3, n4, n1, n2), (n4, n1, n2,",
"def __str__(self): builder = f'Chain order: {\" \".join(self.__chain_order())}\\n' for helix in self.helices: builder",
"Dict[Tetrad, Tuple[int, Tuple, Tuple]]] = field(init=False) tetrad_pairs: List[TetradPair] = field(init=False) helices: List[Helix] =",
"_ = self.tetrad2_nts_best_order v1 = nt1_1.find_atom(\"C1'\").coordinates() - nt1_2.find_atom(\"C1'\").coordinates() v1 = v1 / numpy.linalg.norm(v1)",
"3, 1): return ONZ.N_MINUS elif order == (2, 1, 3): return ONZ.Z_PLUS elif",
"while candidates: tj = max([tj for tj in candidates], key=lambda tk: self.tetrad_scores[ti][tk][0]) score",
"shift_value = 0 chain = None for nt in sorted(filter(lambda nt: nt.is_nucleotide, self.structure3d.residues),",
"best_score, best_score_sequential, best_score_stacking = score, score_sequential, score_stacking best_order = nts2 if best_score ==",
"tetrad.pair_41]: # main check if pair.nt1 == first and pair.nt2 == last: if",
"tetrad.pair_41]) sequence, line1, shifts = self.__elimination_conflicts(layer1) _, line2, _ = self.__elimination_conflicts(layer2) return sequence,",
"'sasa': GbaTetradClassification.IIb, 'asaa': GbaTetradClassification.IIIa, 'sass': GbaTetradClassification.IIIb, 'aaas': GbaTetradClassification.IVa, 'sssa': GbaTetradClassification.IVb, 'aasa': GbaTetradClassification.Va, 'ssas':",
"return f' ' \\ f'{self.nt1.full_name} {self.nt2.full_name} {self.nt3.full_name} {self.nt4.full_name} ' \\ f'{self.pair_12.lw.value} {self.pair_23.lw.value} {self.pair_34.lw.value}",
"loop_type: Optional[LoopType] def __str__(self): return f' {self.loop_type.value if self.loop_type else \"n/a\"} ' \\",
"x, y = nucleotides.index(x) + 1 + shifts[x], nucleotides.index(y) + 1 + shifts[y]",
"in tract.nucleotides: return tract return None def __detect_loop_sign(self, first: Residue3D, last: Residue3D, tetrad:",
"= field(init=False) ions_channel: List[Atom3D] = field(default_factory=list) ions_outside: Dict[Residue3D, List[Atom3D]] = field(default_factory=dict) def __post_init__(self):",
"self.structure3d.base_pair_graph(self.structure2d, self.strict) self.base_pair_dict = self.structure3d.base_pair_dict(self.structure2d, self.strict) self.stacking_graph = self.structure3d.stacking_graph(self.structure2d) self.tetrads = self.__find_tetrads(self.no_reorder) self.tetrad_scores",
"nts2 = self.tetrad_scores[ti][tj][1:] stacked = {nts1[i]: nts2[i] for i in range(4)} stacked.update({v: k",
"in self.helices for t in h.tetrads] logging.debug(f'Selected chain order: {\" \".join(final_order)} ' f'{\"",
"+= 'single tetrad without stacking\\n' builder += str(self.tetrads[0]) return builder @dataclass class Analysis:",
"= self.__find_helices() if not self.no_reorder: self.__find_best_chain_order() self.sequence, self.line1, self.line2, self.shifts = self.__generate_twoline_dotbracket() self.ions",
"sequence, line1, shifts = self.__elimination_conflicts(layer1) _, line2, _ = self.__elimination_conflicts(layer2) return sequence, line1,",
"j, k, l])) if len(tetrads) > 1: return True return False def center_of_mass(atoms):",
"[self.tetrads[0].nt2], [self.tetrads[0].nt3], [self.tetrads[0].nt4]] if len(self.tetrad_pairs) > 0: for tetrad_pair in self.tetrad_pairs: nt_dict =",
"tetrad sign = self.__detect_loop_sign(nt_first, nt_last, tetrad_with_first) if sign is not None: return LoopType.from_value(f'lateral{sign}')",
"min(map(lambda nt: nt.index, t.nucleotides))) def __calculate_tetrad_scores(self) \\ -> Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]]:",
"Residue3D, Residue3D]: return self.nt1, self.nt2, self.nt3, self.nt4 def __hash__(self): return hash(frozenset([self.nt1, self.nt2, self.nt3,",
"ions_outside: Dict[Residue3D, List[Atom3D]] = field(default_factory=dict) def __post_init__(self): self.reorder_to_match_5p_3p() self.planarity_deviation = self.__calculate_planarity_deviation() def reorder_to_match_5p_3p(self):",
"k, v in stacked.items()}) tetrad_pairs.append(TetradPair(ti, tj, stacked)) order = (stacked[ti.nt1], stacked[ti.nt2], stacked[ti.nt3], stacked[ti.nt4])",
"x: x not in (i, j), self.base_pair_graph[j]): for l in filter(lambda x: x",
"str(self.tetrad_pairs[0].tetrad1) for tetrad_pair in self.tetrad_pairs: builder += str(tetrad_pair) builder += str(tetrad_pair.tetrad2) if self.tracts:",
"classification: {fingerprint}') return None subtype = 'a' if self.loops[0 if fingerprint != 'dpd'",
"residue.innermost_atom, self.nucleotides)) def __ions_channel_str(self) -> str: if self.ions_channel: return 'ions_channel=' + ','.join([atom.atomName for",
"Tuple, Tuple]]] = field(init=False) tetrad_pairs: List[TetradPair] = field(init=False) helices: List[Helix] = field(init=False) ions:",
"all([nt.chi_class in (GlycosidicBond.syn, GlycosidicBond.anti) for nt in self.nucleotides]): return None # this will",
"field(init=False) sequence: str = field(init=False) line1: str = field(init=False) line2: str = field(init=False)",
"self.onz_dict[pair] helix.write(f'{x}\\t{y}\\t1\\t{onz_value.get(onz, 7)}\\n') if canonical: for pair in canonical: x, y = pair.nt1,",
"from any tetrad (distance={min_distance})') for tetrad, ions in ions_channel.items(): tetrad.ions_channel = ions for",
"self.__determine_direction() self.rise = self.__calculate_rise() self.twist = self.__calculate_twist() def __determine_direction(self) -> Direction: indices1 =",
"self.nt4): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse() elif order ==",
"' \\ f'{self.nt1.full_name} {self.nt2.full_name} {self.nt3.full_name} {self.nt4.full_name} ' \\ f'{self.pair_12.lw.value} {self.pair_23.lw.value} {self.pair_34.lw.value} {self.pair_41.lw.value} '",
"self.rise = self.__calculate_rise() self.twist = self.__calculate_twist() def __determine_direction(self) -> Direction: indices1 = list(map(lambda",
"break return sorted(tetrads, key=lambda t: min(map(lambda nt: nt.index, t.nucleotides))) def __calculate_tetrad_scores(self) \\ ->",
"tetrad_pairs = [] for i in range(1, len(best_order)): ti, tj = best_order[i -",
"k in filter(lambda x: x not in (i, j), self.base_pair_graph[j]): for l in",
"= [] for chains in chain_groups: best_permutation, best_score = chains, (1e10, 1e10) if",
"nt: nt.full_name, self.nucleotides))}' @dataclass class Quadruplex: tetrads: List[Tetrad] tetrad_pairs: List[TetradPair] structure3d: Structure3D onzm:",
"if is_next_sequentially(nts1[i], nts2[i]) else 0 for i in range(4)] score = sum([max(score_stacking[i], score_sequential[i])",
"= Counter([t.onz.value[0] for t in self.tetrads]) onz, support = counter.most_common()[0] if support !=",
"helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d)) helix_tetrads = [ti, tj] helix_tetrad_pairs = [tp] if helix_tetrads: helices.append(Helix(helix_tetrads,",
"deviation candidates = sorted(tetrads, key=lambda t: (len(graph[t]), t.planarity_deviation), reverse=True) if len(graph[candidates[0]]) > 0:",
"self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse() # ONZ and da Silva's classification",
"layer1, layer2 = [], [] for tetrad in self.tetrads: layer1.extend([tetrad.pair_12, tetrad.pair_34]) layer2.extend([tetrad.pair_23, tetrad.pair_41])",
"self.structure3d)) for tetrad in self.tetrads: if not any([tetrad in helix.tetrads for helix in",
"in candidates], key=lambda tk: self.tetrad_scores[ti][tk][0]) score += self.tetrad_scores[ti][tj][0] order.append(tj) candidates.remove(tj) ti = tj",
"= set([ion.value.upper() for ion in Ion]) ions = [] used = set() for",
"field(init=False) shifts: Dict[Residue3D, int] = field(init=False) def __post_init__(self): self.base_pairs = self.structure3d.base_pairs(self.structure2d) self.base_pair_graph =",
"self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34 # flip order if necessary if",
"Structure3D quadruplexes: List[Quadruplex] = field(init=False) def __post_init__(self): self.quadruplexes = self.__find_quadruplexes() def __find_quadruplexes(self): if",
"pair_dictionary: Dict[Tuple[Residue3D, Residue3D], BasePair3D]) -> bool: lw1 = pair_dictionary[(nt1, nt2)].lw lw2 = pair_dictionary[(nt2,",
"' \\ f'planarity={round(self.planarity_deviation, 2)} ' \\ f'{self.__ions_channel_str()} ' \\ f'{self.__ions_outside_str()}\\n' def chains(self) ->",
"nl = (indices.index(x) for x in (ni, nj, nk, nl)) nmin = min(ni,",
"base_pairs: List[BasePair3D] = field(init=False) base_pair_graph: Dict[Residue3D, List[Residue3D]] = field(init=False) base_pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D]",
"which has the worst planarity deviation candidates = sorted(tetrads, key=lambda t: (len(graph[t]), t.planarity_deviation),",
"= math.inf min_tetrad = self.tetrads[0] min_nt = min_tetrad.nt1 for tetrad in self.tetrads: for",
"diagonal or laterals happen when first and last nt of a loop is",
"Set[str]: return set([nt.chain for nt in self.nucleotides]) def is_disjoint(self, other) -> bool: return",
"self.loop_class: builder += f' {self.loop_class.value} {self.loop_class.loop_progression()}' else: builder += f' n/a' builder +=",
"sum(score_stacking) if (score, score_sequential, score_stacking) > (best_score, best_score_sequential, best_score_stacking): best_score, best_score_sequential, best_score_stacking =",
"+= 1 opening = '([{<' + string.ascii_uppercase closing = ')]}>' + string.ascii_lowercase dotbracket",
"ncur) loops.append(Loop(nts, loop_type)) return loops def __detect_loop_type(self, nt_first: Residue3D, nt_last: Residue3D) -> Optional[LoopType]:",
"elif order == (self.nt2, self.nt3, self.nt4, self.nt1): self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23,",
"stacking\\n' builder += str(self.tetrads[0]) return builder @dataclass class Analysis: structure2d: Structure2D structure3d: Structure3D",
"== nt2.chain and abs(nt1.index - nt2.index) == 1 tetrad_scores = defaultdict(dict) for ti,",
"order in orders.items(): nt1, nt2 = sorted([pair.nt1, pair.nt2]) dotbracket[nt1] = opening[order] dotbracket[nt2] =",
"k) and x in self.graph[i], self.graph[k]): if Tetrad.is_valid(i, j, k, l, self.pair_dict): tetrads.add(frozenset([i,",
"into (0, 1, 2, 3) ni, nj, nk, nl = map(lambda nt: nt.index,",
"a valid syn/anti, this classification is impossible if not all([nt.chi_class in (GlycosidicBond.syn, GlycosidicBond.anti)"
] |
[
".database import Experiment, Movement, Trial from . import plots from . import utils",
"from .database import Experiment, Movement, Trial from . import plots from . import"
] |
[
"np.testing.assert_equal( last_row[\"midday_rgb_filename\"], \"dukehw_2020_07_15_115405.jpg\" ) np.testing.assert_equal( last_row[\"midday_ir_filename\"], \"dukehw_IR_2020_07_15_115405.jpg\" ) np.testing.assert_equal(first_row[\"ndvi_mean\"], 0.22027) np.testing.assert_equal(first_row[\"ndvi_std\"], 0.16966) np.testing.assert_equal(first_row[\"max_solar_elev\"],",
"= \"dukehw\" roiname = \"DB_1000\" ndvits = vi.get_ndvi_summary(sitename, roiname, nday=3) first_row = ndvits.rows[0]",
"check a couple of rows np.testing.assert_equal( last_row[\"midday_rgb_filename\"], \"dukehw_2020_07_15_115405.jpg\" ) np.testing.assert_equal( last_row[\"midday_ir_filename\"], \"dukehw_IR_2020_07_15_115405.jpg\" )",
"def test_reading_ndvits_summary_file(): \"\"\" test reading in existing ndvits summary timeseries \"\"\" sitename =",
"from vegindex import config from vegindex import ndvi_summary_timeseries from vegindex import vegindex as",
"\"ROI\", ndvi_file) ndvits = ndvi_summary_timeseries.NDVISummaryTimeSeries( site=sitename, ROIListID=roiname ) ndvits.readCSV(ndvi_path) first_row = ndvits.rows[0] last_row",
"\"dukehw_IR_2020_07_15_115405.jpg\" ) np.testing.assert_equal(first_row[\"ndvi_mean\"], 0.22027) np.testing.assert_equal(first_row[\"ndvi_std\"], 0.16966) np.testing.assert_equal(first_row[\"max_solar_elev\"], 75.9963) np.testing.assert_equal(len(ndvits.rows), 870) def test_get_ndvi_summary_file(): \"\"\"",
"from vegindex import ndvi_summary_timeseries from vegindex import vegindex as vi SAMPLE_DATA_DIR = os.path.join(os.path.dirname(__file__),",
"file ndvi_path = os.path.join(SAMPLE_DATA_DIR, sitename, \"ROI\", ndvi_file) ndvits = ndvi_summary_timeseries.NDVISummaryTimeSeries( site=sitename, ROIListID=roiname )",
"set up path to roistats file ndvi_path = os.path.join(SAMPLE_DATA_DIR, sitename, \"ROI\", ndvi_file) ndvits",
"np.testing.assert_equal(first_row[\"ndvi_std\"], 0.16966) np.testing.assert_equal(first_row[\"max_solar_elev\"], 75.9963) np.testing.assert_equal(len(ndvits.rows), 870) def test_get_ndvi_summary_file(): \"\"\" test reading in existing",
"\"DB_1000\" ndvi_file = \"{}_{}_ndvi_3day.csv\".format(sitename, roiname) # set up path to roistats file ndvi_path",
"nday=3) first_row = ndvits.rows[0] last_row = ndvits.rows[-1] # test that we're getting header",
"existing ndvits summary timeseries using the helper function. \"\"\" sitename = \"dukehw\" roiname",
"test reading in existing ndvits summary timeseries \"\"\" sitename = \"dukehw\" roiname =",
"ndvi_summary_timeseries.NDVISummaryTimeSeries( site=sitename, ROIListID=roiname ) ndvits.readCSV(ndvi_path) first_row = ndvits.rows[0] last_row = ndvits.rows[-1] # test",
"-*- coding: utf-8 -*- \"\"\" test_ndvisummarytimeseries -------------------------- Tests for `vegindex.ndvi_summary_timeseries` module. \"\"\" import",
"= ndvi_summary_timeseries.NDVISummaryTimeSeries( site=sitename, ROIListID=roiname ) ndvits.readCSV(ndvi_path) first_row = ndvits.rows[0] last_row = ndvits.rows[-1] #",
"\"\"\" test reading in existing ndvits summary timeseries using the helper function. \"\"\"",
"correctly np.testing.assert_equal(ndvits.site, \"dukehw\") np.testing.assert_equal(ndvits.nday, 3) np.testing.assert_equal(ndvits.roitype, \"DB\") np.testing.assert_equal(ndvits.sequence_number, \"1000\") # spot check a",
") ndvits.readCSV(ndvi_path) first_row = ndvits.rows[0] last_row = ndvits.rows[-1] # test that we're getting",
"\"dukehw\") np.testing.assert_equal(ndvits.nday, 3) np.testing.assert_equal(ndvits.roitype, \"DB\") np.testing.assert_equal(ndvits.sequence_number, \"1000\") # spot check a couple of",
"= SAMPLE_DATA_DIR def test_reading_ndvits_summary_file(): \"\"\" test reading in existing ndvits summary timeseries \"\"\"",
"np.testing.assert_equal(first_row[\"max_solar_elev\"], 75.9963) np.testing.assert_equal(len(ndvits.rows), 870) def test_get_ndvi_summary_file(): \"\"\" test reading in existing ndvits summary",
"sitename = \"dukehw\" roiname = \"DB_1000\" ndvi_file = \"{}_{}_ndvi_3day.csv\".format(sitename, roiname) # set up",
"summary timeseries using the helper function. \"\"\" sitename = \"dukehw\" roiname = \"DB_1000\"",
"site=sitename, ROIListID=roiname ) ndvits.readCSV(ndvi_path) first_row = ndvits.rows[0] last_row = ndvits.rows[-1] # test that",
"def test_get_ndvi_summary_file(): \"\"\" test reading in existing ndvits summary timeseries using the helper",
"module. \"\"\" import os import numpy as np from PIL import Image from",
"getting header metadata correctly np.testing.assert_equal(ndvits.site, \"dukehw\") np.testing.assert_equal(ndvits.nday, 3) np.testing.assert_equal(ndvits.roitype, \"DB\") np.testing.assert_equal(ndvits.sequence_number, \"1000\") #",
"\"dukehw_2020_07_15_115405.jpg\" ) np.testing.assert_equal( last_row[\"midday_ir_filename\"], \"dukehw_IR_2020_07_15_115405.jpg\" ) np.testing.assert_equal(first_row[\"ndvi_mean\"], 0.22027) np.testing.assert_equal(first_row[\"ndvi_std\"], 0.16966) np.testing.assert_equal(first_row[\"max_solar_elev\"], 75.9963) np.testing.assert_equal(len(ndvits.rows),",
"resource_filename from vegindex import config from vegindex import ndvi_summary_timeseries from vegindex import vegindex",
"ndvits.readCSV(ndvi_path) first_row = ndvits.rows[0] last_row = ndvits.rows[-1] # test that we're getting header",
"\"\"\" import os import numpy as np from PIL import Image from pkg_resources",
"vegindex import ndvi_summary_timeseries from vegindex import vegindex as vi SAMPLE_DATA_DIR = os.path.join(os.path.dirname(__file__), \"sample_data\")",
"ndvi_path = os.path.join(SAMPLE_DATA_DIR, sitename, \"ROI\", ndvi_file) ndvits = ndvi_summary_timeseries.NDVISummaryTimeSeries( site=sitename, ROIListID=roiname ) ndvits.readCSV(ndvi_path)",
"sitename = \"dukehw\" roiname = \"DB_1000\" ndvits = vi.get_ndvi_summary(sitename, roiname, nday=3) first_row =",
"test_reading_ndvits_summary_file(): \"\"\" test reading in existing ndvits summary timeseries \"\"\" sitename = \"dukehw\"",
"a couple of rows np.testing.assert_equal( last_row[\"midday_rgb_filename\"], \"dukehw_2020_07_15_115405.jpg\" ) np.testing.assert_equal( last_row[\"midday_ir_filename\"], \"dukehw_IR_2020_07_15_115405.jpg\" ) np.testing.assert_equal(first_row[\"ndvi_mean\"],",
"= os.path.join(os.path.dirname(__file__), \"sample_data\") config.archive_dir = SAMPLE_DATA_DIR def test_reading_ndvits_summary_file(): \"\"\" test reading in existing",
"test reading in existing ndvits summary timeseries using the helper function. \"\"\" sitename",
"\"DB\") np.testing.assert_equal(ndvits.sequence_number, \"1000\") # spot check a couple of rows np.testing.assert_equal( last_row[\"midday_rgb_filename\"], \"dukehw_2020_07_15_115405.jpg\"",
"<reponame>tmilliman/python-vegindex # -*- coding: utf-8 -*- \"\"\" test_ndvisummarytimeseries -------------------------- Tests for `vegindex.ndvi_summary_timeseries` module.",
"ndvi_summary_timeseries from vegindex import vegindex as vi SAMPLE_DATA_DIR = os.path.join(os.path.dirname(__file__), \"sample_data\") config.archive_dir =",
"870) def test_get_ndvi_summary_file(): \"\"\" test reading in existing ndvits summary timeseries using the",
"import Requirement from pkg_resources import resource_filename from vegindex import config from vegindex import",
"Image from pkg_resources import Requirement from pkg_resources import resource_filename from vegindex import config",
"from vegindex import vegindex as vi SAMPLE_DATA_DIR = os.path.join(os.path.dirname(__file__), \"sample_data\") config.archive_dir = SAMPLE_DATA_DIR",
"os.path.join(SAMPLE_DATA_DIR, sitename, \"ROI\", ndvi_file) ndvits = ndvi_summary_timeseries.NDVISummaryTimeSeries( site=sitename, ROIListID=roiname ) ndvits.readCSV(ndvi_path) first_row =",
"roiname = \"DB_1000\" ndvits = vi.get_ndvi_summary(sitename, roiname, nday=3) first_row = ndvits.rows[0] last_row =",
"\"{}_{}_ndvi_3day.csv\".format(sitename, roiname) # set up path to roistats file ndvi_path = os.path.join(SAMPLE_DATA_DIR, sitename,",
"timeseries using the helper function. \"\"\" sitename = \"dukehw\" roiname = \"DB_1000\" ndvits",
"reading in existing ndvits summary timeseries using the helper function. \"\"\" sitename =",
"header metadata correctly np.testing.assert_equal(ndvits.site, \"dukehw\") np.testing.assert_equal(ndvits.nday, 3) np.testing.assert_equal(ndvits.roitype, \"DB\") np.testing.assert_equal(ndvits.sequence_number, \"1000\") # spot",
"pkg_resources import resource_filename from vegindex import config from vegindex import ndvi_summary_timeseries from vegindex",
"roiname) # set up path to roistats file ndvi_path = os.path.join(SAMPLE_DATA_DIR, sitename, \"ROI\",",
"import numpy as np from PIL import Image from pkg_resources import Requirement from",
"0.16966) np.testing.assert_equal(first_row[\"max_solar_elev\"], 75.9963) np.testing.assert_equal(len(ndvits.rows), 870) def test_get_ndvi_summary_file(): \"\"\" test reading in existing ndvits",
"os.path.join(os.path.dirname(__file__), \"sample_data\") config.archive_dir = SAMPLE_DATA_DIR def test_reading_ndvits_summary_file(): \"\"\" test reading in existing ndvits",
"\"\"\" test reading in existing ndvits summary timeseries \"\"\" sitename = \"dukehw\" roiname",
"config from vegindex import ndvi_summary_timeseries from vegindex import vegindex as vi SAMPLE_DATA_DIR =",
"0.22027) np.testing.assert_equal(first_row[\"ndvi_std\"], 0.16966) np.testing.assert_equal(first_row[\"max_solar_elev\"], 75.9963) np.testing.assert_equal(len(ndvits.rows), 870) def test_get_ndvi_summary_file(): \"\"\" test reading in",
"vegindex import config from vegindex import ndvi_summary_timeseries from vegindex import vegindex as vi",
"-*- \"\"\" test_ndvisummarytimeseries -------------------------- Tests for `vegindex.ndvi_summary_timeseries` module. \"\"\" import os import numpy",
"= ndvits.rows[-1] # test that we're getting header metadata correctly np.testing.assert_equal(ndvits.site, \"dukehw\") np.testing.assert_equal(ndvits.nday,",
"\"dukehw\" roiname = \"DB_1000\" ndvits = vi.get_ndvi_summary(sitename, roiname, nday=3) first_row = ndvits.rows[0] last_row",
"\"\"\" test_ndvisummarytimeseries -------------------------- Tests for `vegindex.ndvi_summary_timeseries` module. \"\"\" import os import numpy as",
"vegindex import vegindex as vi SAMPLE_DATA_DIR = os.path.join(os.path.dirname(__file__), \"sample_data\") config.archive_dir = SAMPLE_DATA_DIR def",
"of rows np.testing.assert_equal( last_row[\"midday_rgb_filename\"], \"dukehw_2020_07_15_115405.jpg\" ) np.testing.assert_equal( last_row[\"midday_ir_filename\"], \"dukehw_IR_2020_07_15_115405.jpg\" ) np.testing.assert_equal(first_row[\"ndvi_mean\"], 0.22027) np.testing.assert_equal(first_row[\"ndvi_std\"],",
"SAMPLE_DATA_DIR def test_reading_ndvits_summary_file(): \"\"\" test reading in existing ndvits summary timeseries \"\"\" sitename",
"= \"DB_1000\" ndvits = vi.get_ndvi_summary(sitename, roiname, nday=3) first_row = ndvits.rows[0] last_row = ndvits.rows[-1]",
"`vegindex.ndvi_summary_timeseries` module. \"\"\" import os import numpy as np from PIL import Image",
"existing ndvits summary timeseries \"\"\" sitename = \"dukehw\" roiname = \"DB_1000\" ndvi_file =",
"ndvits summary timeseries using the helper function. \"\"\" sitename = \"dukehw\" roiname =",
"75.9963) np.testing.assert_equal(len(ndvits.rows), 870) def test_get_ndvi_summary_file(): \"\"\" test reading in existing ndvits summary timeseries",
"import ndvi_summary_timeseries from vegindex import vegindex as vi SAMPLE_DATA_DIR = os.path.join(os.path.dirname(__file__), \"sample_data\") config.archive_dir",
"SAMPLE_DATA_DIR = os.path.join(os.path.dirname(__file__), \"sample_data\") config.archive_dir = SAMPLE_DATA_DIR def test_reading_ndvits_summary_file(): \"\"\" test reading in",
"import os import numpy as np from PIL import Image from pkg_resources import",
"the helper function. \"\"\" sitename = \"dukehw\" roiname = \"DB_1000\" ndvits = vi.get_ndvi_summary(sitename,",
"to roistats file ndvi_path = os.path.join(SAMPLE_DATA_DIR, sitename, \"ROI\", ndvi_file) ndvits = ndvi_summary_timeseries.NDVISummaryTimeSeries( site=sitename,",
"as np from PIL import Image from pkg_resources import Requirement from pkg_resources import",
"vi.get_ndvi_summary(sitename, roiname, nday=3) first_row = ndvits.rows[0] last_row = ndvits.rows[-1] # test that we're",
"from PIL import Image from pkg_resources import Requirement from pkg_resources import resource_filename from",
"PIL import Image from pkg_resources import Requirement from pkg_resources import resource_filename from vegindex",
"from pkg_resources import Requirement from pkg_resources import resource_filename from vegindex import config from",
"Requirement from pkg_resources import resource_filename from vegindex import config from vegindex import ndvi_summary_timeseries",
"np.testing.assert_equal(ndvits.site, \"dukehw\") np.testing.assert_equal(ndvits.nday, 3) np.testing.assert_equal(ndvits.roitype, \"DB\") np.testing.assert_equal(ndvits.sequence_number, \"1000\") # spot check a couple",
"np.testing.assert_equal(ndvits.roitype, \"DB\") np.testing.assert_equal(ndvits.sequence_number, \"1000\") # spot check a couple of rows np.testing.assert_equal( last_row[\"midday_rgb_filename\"],",
"# spot check a couple of rows np.testing.assert_equal( last_row[\"midday_rgb_filename\"], \"dukehw_2020_07_15_115405.jpg\" ) np.testing.assert_equal( last_row[\"midday_ir_filename\"],",
"ndvi_file = \"{}_{}_ndvi_3day.csv\".format(sitename, roiname) # set up path to roistats file ndvi_path =",
"ndvits summary timeseries \"\"\" sitename = \"dukehw\" roiname = \"DB_1000\" ndvi_file = \"{}_{}_ndvi_3day.csv\".format(sitename,",
"= \"DB_1000\" ndvi_file = \"{}_{}_ndvi_3day.csv\".format(sitename, roiname) # set up path to roistats file",
"import Image from pkg_resources import Requirement from pkg_resources import resource_filename from vegindex import",
"ndvits.rows[0] last_row = ndvits.rows[-1] # test that we're getting header metadata correctly np.testing.assert_equal(ndvits.site,",
"function. \"\"\" sitename = \"dukehw\" roiname = \"DB_1000\" ndvits = vi.get_ndvi_summary(sitename, roiname, nday=3)",
"using the helper function. \"\"\" sitename = \"dukehw\" roiname = \"DB_1000\" ndvits =",
"# set up path to roistats file ndvi_path = os.path.join(SAMPLE_DATA_DIR, sitename, \"ROI\", ndvi_file)",
"np.testing.assert_equal( last_row[\"midday_ir_filename\"], \"dukehw_IR_2020_07_15_115405.jpg\" ) np.testing.assert_equal(first_row[\"ndvi_mean\"], 0.22027) np.testing.assert_equal(first_row[\"ndvi_std\"], 0.16966) np.testing.assert_equal(first_row[\"max_solar_elev\"], 75.9963) np.testing.assert_equal(len(ndvits.rows), 870) def",
"roistats file ndvi_path = os.path.join(SAMPLE_DATA_DIR, sitename, \"ROI\", ndvi_file) ndvits = ndvi_summary_timeseries.NDVISummaryTimeSeries( site=sitename, ROIListID=roiname",
"np.testing.assert_equal(len(ndvits.rows), 870) def test_get_ndvi_summary_file(): \"\"\" test reading in existing ndvits summary timeseries using",
"first_row = ndvits.rows[0] last_row = ndvits.rows[-1] # test that we're getting header metadata",
"vi SAMPLE_DATA_DIR = os.path.join(os.path.dirname(__file__), \"sample_data\") config.archive_dir = SAMPLE_DATA_DIR def test_reading_ndvits_summary_file(): \"\"\" test reading",
"metadata correctly np.testing.assert_equal(ndvits.site, \"dukehw\") np.testing.assert_equal(ndvits.nday, 3) np.testing.assert_equal(ndvits.roitype, \"DB\") np.testing.assert_equal(ndvits.sequence_number, \"1000\") # spot check",
"in existing ndvits summary timeseries using the helper function. \"\"\" sitename = \"dukehw\"",
"that we're getting header metadata correctly np.testing.assert_equal(ndvits.site, \"dukehw\") np.testing.assert_equal(ndvits.nday, 3) np.testing.assert_equal(ndvits.roitype, \"DB\") np.testing.assert_equal(ndvits.sequence_number,",
"last_row[\"midday_ir_filename\"], \"dukehw_IR_2020_07_15_115405.jpg\" ) np.testing.assert_equal(first_row[\"ndvi_mean\"], 0.22027) np.testing.assert_equal(first_row[\"ndvi_std\"], 0.16966) np.testing.assert_equal(first_row[\"max_solar_elev\"], 75.9963) np.testing.assert_equal(len(ndvits.rows), 870) def test_get_ndvi_summary_file():",
"from pkg_resources import resource_filename from vegindex import config from vegindex import ndvi_summary_timeseries from",
"roiname, nday=3) first_row = ndvits.rows[0] last_row = ndvits.rows[-1] # test that we're getting",
"\"\"\" sitename = \"dukehw\" roiname = \"DB_1000\" ndvits = vi.get_ndvi_summary(sitename, roiname, nday=3) first_row",
"3) np.testing.assert_equal(ndvits.roitype, \"DB\") np.testing.assert_equal(ndvits.sequence_number, \"1000\") # spot check a couple of rows np.testing.assert_equal(",
"coding: utf-8 -*- \"\"\" test_ndvisummarytimeseries -------------------------- Tests for `vegindex.ndvi_summary_timeseries` module. \"\"\" import os",
"= \"{}_{}_ndvi_3day.csv\".format(sitename, roiname) # set up path to roistats file ndvi_path = os.path.join(SAMPLE_DATA_DIR,",
"path to roistats file ndvi_path = os.path.join(SAMPLE_DATA_DIR, sitename, \"ROI\", ndvi_file) ndvits = ndvi_summary_timeseries.NDVISummaryTimeSeries(",
"= ndvits.rows[0] last_row = ndvits.rows[-1] # test that we're getting header metadata correctly",
"-------------------------- Tests for `vegindex.ndvi_summary_timeseries` module. \"\"\" import os import numpy as np from",
"ndvits.rows[-1] # test that we're getting header metadata correctly np.testing.assert_equal(ndvits.site, \"dukehw\") np.testing.assert_equal(ndvits.nday, 3)",
"rows np.testing.assert_equal( last_row[\"midday_rgb_filename\"], \"dukehw_2020_07_15_115405.jpg\" ) np.testing.assert_equal( last_row[\"midday_ir_filename\"], \"dukehw_IR_2020_07_15_115405.jpg\" ) np.testing.assert_equal(first_row[\"ndvi_mean\"], 0.22027) np.testing.assert_equal(first_row[\"ndvi_std\"], 0.16966)",
"config.archive_dir = SAMPLE_DATA_DIR def test_reading_ndvits_summary_file(): \"\"\" test reading in existing ndvits summary timeseries",
"couple of rows np.testing.assert_equal( last_row[\"midday_rgb_filename\"], \"dukehw_2020_07_15_115405.jpg\" ) np.testing.assert_equal( last_row[\"midday_ir_filename\"], \"dukehw_IR_2020_07_15_115405.jpg\" ) np.testing.assert_equal(first_row[\"ndvi_mean\"], 0.22027)",
"spot check a couple of rows np.testing.assert_equal( last_row[\"midday_rgb_filename\"], \"dukehw_2020_07_15_115405.jpg\" ) np.testing.assert_equal( last_row[\"midday_ir_filename\"], \"dukehw_IR_2020_07_15_115405.jpg\"",
"# test that we're getting header metadata correctly np.testing.assert_equal(ndvits.site, \"dukehw\") np.testing.assert_equal(ndvits.nday, 3) np.testing.assert_equal(ndvits.roitype,",
"last_row = ndvits.rows[-1] # test that we're getting header metadata correctly np.testing.assert_equal(ndvits.site, \"dukehw\")",
"np from PIL import Image from pkg_resources import Requirement from pkg_resources import resource_filename",
"ndvi_file) ndvits = ndvi_summary_timeseries.NDVISummaryTimeSeries( site=sitename, ROIListID=roiname ) ndvits.readCSV(ndvi_path) first_row = ndvits.rows[0] last_row =",
"import resource_filename from vegindex import config from vegindex import ndvi_summary_timeseries from vegindex import",
"as vi SAMPLE_DATA_DIR = os.path.join(os.path.dirname(__file__), \"sample_data\") config.archive_dir = SAMPLE_DATA_DIR def test_reading_ndvits_summary_file(): \"\"\" test",
"timeseries \"\"\" sitename = \"dukehw\" roiname = \"DB_1000\" ndvi_file = \"{}_{}_ndvi_3day.csv\".format(sitename, roiname) #",
"\"1000\") # spot check a couple of rows np.testing.assert_equal( last_row[\"midday_rgb_filename\"], \"dukehw_2020_07_15_115405.jpg\" ) np.testing.assert_equal(",
"\"\"\" sitename = \"dukehw\" roiname = \"DB_1000\" ndvi_file = \"{}_{}_ndvi_3day.csv\".format(sitename, roiname) # set",
"helper function. \"\"\" sitename = \"dukehw\" roiname = \"DB_1000\" ndvits = vi.get_ndvi_summary(sitename, roiname,",
"test that we're getting header metadata correctly np.testing.assert_equal(ndvits.site, \"dukehw\") np.testing.assert_equal(ndvits.nday, 3) np.testing.assert_equal(ndvits.roitype, \"DB\")",
"last_row[\"midday_rgb_filename\"], \"dukehw_2020_07_15_115405.jpg\" ) np.testing.assert_equal( last_row[\"midday_ir_filename\"], \"dukehw_IR_2020_07_15_115405.jpg\" ) np.testing.assert_equal(first_row[\"ndvi_mean\"], 0.22027) np.testing.assert_equal(first_row[\"ndvi_std\"], 0.16966) np.testing.assert_equal(first_row[\"max_solar_elev\"], 75.9963)",
"pkg_resources import Requirement from pkg_resources import resource_filename from vegindex import config from vegindex",
"= \"dukehw\" roiname = \"DB_1000\" ndvi_file = \"{}_{}_ndvi_3day.csv\".format(sitename, roiname) # set up path",
"test_get_ndvi_summary_file(): \"\"\" test reading in existing ndvits summary timeseries using the helper function.",
"summary timeseries \"\"\" sitename = \"dukehw\" roiname = \"DB_1000\" ndvi_file = \"{}_{}_ndvi_3day.csv\".format(sitename, roiname)",
") np.testing.assert_equal(first_row[\"ndvi_mean\"], 0.22027) np.testing.assert_equal(first_row[\"ndvi_std\"], 0.16966) np.testing.assert_equal(first_row[\"max_solar_elev\"], 75.9963) np.testing.assert_equal(len(ndvits.rows), 870) def test_get_ndvi_summary_file(): \"\"\" test",
"np.testing.assert_equal(first_row[\"ndvi_mean\"], 0.22027) np.testing.assert_equal(first_row[\"ndvi_std\"], 0.16966) np.testing.assert_equal(first_row[\"max_solar_elev\"], 75.9963) np.testing.assert_equal(len(ndvits.rows), 870) def test_get_ndvi_summary_file(): \"\"\" test reading",
"vegindex as vi SAMPLE_DATA_DIR = os.path.join(os.path.dirname(__file__), \"sample_data\") config.archive_dir = SAMPLE_DATA_DIR def test_reading_ndvits_summary_file(): \"\"\"",
"import vegindex as vi SAMPLE_DATA_DIR = os.path.join(os.path.dirname(__file__), \"sample_data\") config.archive_dir = SAMPLE_DATA_DIR def test_reading_ndvits_summary_file():",
"ndvits = ndvi_summary_timeseries.NDVISummaryTimeSeries( site=sitename, ROIListID=roiname ) ndvits.readCSV(ndvi_path) first_row = ndvits.rows[0] last_row = ndvits.rows[-1]",
"utf-8 -*- \"\"\" test_ndvisummarytimeseries -------------------------- Tests for `vegindex.ndvi_summary_timeseries` module. \"\"\" import os import",
"Tests for `vegindex.ndvi_summary_timeseries` module. \"\"\" import os import numpy as np from PIL",
"numpy as np from PIL import Image from pkg_resources import Requirement from pkg_resources",
"up path to roistats file ndvi_path = os.path.join(SAMPLE_DATA_DIR, sitename, \"ROI\", ndvi_file) ndvits =",
"\"DB_1000\" ndvits = vi.get_ndvi_summary(sitename, roiname, nday=3) first_row = ndvits.rows[0] last_row = ndvits.rows[-1] #",
"for `vegindex.ndvi_summary_timeseries` module. \"\"\" import os import numpy as np from PIL import",
"in existing ndvits summary timeseries \"\"\" sitename = \"dukehw\" roiname = \"DB_1000\" ndvi_file",
"= vi.get_ndvi_summary(sitename, roiname, nday=3) first_row = ndvits.rows[0] last_row = ndvits.rows[-1] # test that",
"\"dukehw\" roiname = \"DB_1000\" ndvi_file = \"{}_{}_ndvi_3day.csv\".format(sitename, roiname) # set up path to",
"# -*- coding: utf-8 -*- \"\"\" test_ndvisummarytimeseries -------------------------- Tests for `vegindex.ndvi_summary_timeseries` module. \"\"\"",
"ROIListID=roiname ) ndvits.readCSV(ndvi_path) first_row = ndvits.rows[0] last_row = ndvits.rows[-1] # test that we're",
"ndvits = vi.get_ndvi_summary(sitename, roiname, nday=3) first_row = ndvits.rows[0] last_row = ndvits.rows[-1] # test",
"os import numpy as np from PIL import Image from pkg_resources import Requirement",
"sitename, \"ROI\", ndvi_file) ndvits = ndvi_summary_timeseries.NDVISummaryTimeSeries( site=sitename, ROIListID=roiname ) ndvits.readCSV(ndvi_path) first_row = ndvits.rows[0]",
"= os.path.join(SAMPLE_DATA_DIR, sitename, \"ROI\", ndvi_file) ndvits = ndvi_summary_timeseries.NDVISummaryTimeSeries( site=sitename, ROIListID=roiname ) ndvits.readCSV(ndvi_path) first_row",
"\"sample_data\") config.archive_dir = SAMPLE_DATA_DIR def test_reading_ndvits_summary_file(): \"\"\" test reading in existing ndvits summary",
") np.testing.assert_equal( last_row[\"midday_ir_filename\"], \"dukehw_IR_2020_07_15_115405.jpg\" ) np.testing.assert_equal(first_row[\"ndvi_mean\"], 0.22027) np.testing.assert_equal(first_row[\"ndvi_std\"], 0.16966) np.testing.assert_equal(first_row[\"max_solar_elev\"], 75.9963) np.testing.assert_equal(len(ndvits.rows), 870)",
"np.testing.assert_equal(ndvits.sequence_number, \"1000\") # spot check a couple of rows np.testing.assert_equal( last_row[\"midday_rgb_filename\"], \"dukehw_2020_07_15_115405.jpg\" )",
"test_ndvisummarytimeseries -------------------------- Tests for `vegindex.ndvi_summary_timeseries` module. \"\"\" import os import numpy as np",
"roiname = \"DB_1000\" ndvi_file = \"{}_{}_ndvi_3day.csv\".format(sitename, roiname) # set up path to roistats",
"we're getting header metadata correctly np.testing.assert_equal(ndvits.site, \"dukehw\") np.testing.assert_equal(ndvits.nday, 3) np.testing.assert_equal(ndvits.roitype, \"DB\") np.testing.assert_equal(ndvits.sequence_number, \"1000\")",
"import config from vegindex import ndvi_summary_timeseries from vegindex import vegindex as vi SAMPLE_DATA_DIR",
"reading in existing ndvits summary timeseries \"\"\" sitename = \"dukehw\" roiname = \"DB_1000\"",
"np.testing.assert_equal(ndvits.nday, 3) np.testing.assert_equal(ndvits.roitype, \"DB\") np.testing.assert_equal(ndvits.sequence_number, \"1000\") # spot check a couple of rows"
] |
[
"%s and firmware is: %s\" % ( self.moduletype, info[0], info[1], ) def get_type(self):",
"0x01 = ON or 0x00 = OFF \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] self.write(register, state)",
"\"EC\" == self.moduletype: points = {\"dry\": 0x02, \"single\": 0x03, \"low\": 0x04, \"high\": 0x05}",
"# ----- Setters ----- ######## def set_temperature(self, t=25.0): \"\"\"Set the compensation temperature :param",
"Exception( \"only decimal address expected, convert hexa by using \\ AtlasI2c.ADDR_OEM_DECIMAL or AtlasI2c.ADDR_EZO_DECIMAL\"",
"if self.debug: print(\"Temperature to set: %.2f\" % t) print( \"%s sent converted temp",
"% t) print( \"%s sent converted temp to bytes: \" % (self.moduletype), byte_array,",
"self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_msb\"] # ec calibration wait for µSiemens byte_array = int(round(value",
"%s\" % device_type) return device_type def get_firmware(self): \"\"\" Read sensor firmware @return int",
"to get confirmation conf = self.read(register) self._check_calibration_confirm(conf) return conf def set_i2c_addr(self, addr): \"\"\"Change",
"OEM circuit :param byte: action => 0x01 = WakeUp or 0x00 = Hibernate",
"self.write(register, byte_array) if self.debug: print(\"Value to send: %.2f\" % value) print( \"%s sent",
"----- Getters ----- ######## def get_device_info(self): \"\"\" Get device information @return string module",
"state :param state: byte state => 0x01 = ON or 0x00 = OFF",
"addr not in self.ADDR_OEM_DECIMAL: raise Exception( \"only decimal address expected, convert hexa by",
"def _convert_raw_hex_to_float(self, byte_array): \"\"\" convert bytearray response to float result return float converted",
"if self.debug: print(\"Byte Array to decode: \", byte_array) print(\"Byte Array decoded to hexa",
"print(\"Firmware type is: %s\" % firmware) return firmware def get_new_read_available(self): \"\"\" New Read",
"elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self.write(register, 0x01) # send 0x01 to",
"change to: %s\" % (\"On\" if hex(0x01) == hex(state) else \"OFF\") ) def",
"converted value \"\"\" hexstr = byte_array.hex() float_from_hexa = float.fromhex(byte_array.hex()) converted = float_from_hexa if",
"is calibrated? >\", binary_calib_status[r]) return binary_calib_status[r] def get_led(self) -> int: \"\"\" Get led",
"= self.OEM_EC_REGISTERS[\"device_new_reading\"] ack = 0x00 self.write(register, ack) if self.debug: print(\"ack new reading available",
"to float result return float converted value \"\"\" hexstr = byte_array.hex() float_from_hexa =",
"else: raise Exception(\"Cannot confirm the operation was correctly executed\") # ----- Getters -----",
"\"EC\" == self.moduletype or \"PH\" == self.moduletype: device_type = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.ONE_BYTE_READ, )",
"rawhex = self.read( self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 100 if self.debug:",
"compensation temperature :param t: float temperature value \"\"\" self.set_wakeup_sleep_mode(0x01) # wake device before",
"calibration confirm register \"\"\" if self.debug: if hex(0x00) == hex(confirm): print(\"Calibration applied\") else:",
"if not \"\"\" is_new_read = self.read( self.OEM_EC_REGISTERS[\"device_new_reading\"], self.ONE_BYTE_READ, ) return is_new_read def get_read(self):",
"Active or Hibernate register is the same for EC and PH OEM circuit",
"binary_calib_status[r] def get_led(self) -> int: \"\"\" Get led state register is the same",
"to Active or Hibernate register is the same for EC and PH OEM",
"currently in mode: %s\" % (\"wakeup\" if hex(0x01) == hex(mode) else \"sleep\") )",
"= self.OEM_EC_REGISTERS[\"device_calibration_msb\"] # ec calibration wait for µSiemens byte_array = int(round(value * 100)).to_bytes(4,",
"points calibrated :rtype: \"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits",
"return is_new_read def get_read(self): \"\"\" Read sensor value @return float the sensor value",
"def get_calibration(self): \"\"\" Get current calibrations data :return: string with current points calibrated",
"set_calibration_apply /!in float micro siemens µS for EC/! /! in float for pH/!",
"in I2C mode. Atlas Scientific i2c by GreenPonik Source code is based on",
"print( \"Device is now: %s\" % (\"wakeup\" if hex(0x01) == hex(action) else \"sleep\")",
"Read available \"\"\" register = self.OEM_EC_REGISTERS[\"device_new_reading\"] ack = 0x00 self.write(register, ack) if self.debug:",
"== self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_msb\"] byte_array = int(round(value * 1000)).to_bytes(4, \"big\") self.write(register, byte_array)",
"Getters ----- ######## def get_device_info(self): \"\"\" Get device information @return string module type,",
"and PH OEM circuits \"\"\" def _convert_raw_hex_to_float(self, byte_array): \"\"\" convert bytearray response to",
"before read register to get confirmation conf = self.read(register) self._check_calibration_confirm(conf) return conf def",
"i2c address \"\"\" self.address(addr) raise NotImplementedError(\"write workflow to change physical i2c address\") def",
"\"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] mode = self.read(register) if self.debug: print( \"Device is currently",
"\"\"\" convert bytearray response to float result return float converted value \"\"\" hexstr",
"calibration is apply by using set_calibration_apply /!in float micro siemens µS for EC/!",
"\"mid\", \"high\" only \"\"\" if point not in (\"dry\", \"single\", \"low\", \"mid\", \"high\"):",
"self.debug: print(\"Firmware type is: %s\" % firmware) return firmware def get_new_read_available(self): \"\"\" New",
"\"\"\" Get current compensation temperature @return float temperature value \"\"\" if \"EC\" ==",
"4=PH) \"\"\" if \"EC\" == self.moduletype or \"PH\" == self.moduletype: device_type = self.read(",
"= float_from_hexa if self.debug: print(\"Byte Array to decode: \", byte_array) print(\"Byte Array decoded",
"self.PH_BINARY_CALIB_STATUS r = self.read(register) if self.debug: print(\"Binary result from OEM\", r) print(\"Who is",
"Hibernate device mode register is the same for EC and PH OEM circuit",
"== hex(mode) else \"sleep\") ) return mode # ----- Setters ----- ######## def",
"only \"\"\" if point not in (\"dry\", \"single\", \"low\", \"mid\", \"high\"): raise Exception(",
"Active or Hibernate device mode register is the same for EC and PH",
"self._set_calibration_registers(value) time.sleep(self.long_timeout) self.write(register, points[point]) # apply point calibration data time.sleep(self.short_timeout) # wait before",
"EC and PH OEM circuit :param byte: action => 0x01 = WakeUp or",
"%s\" % firmware) return firmware def get_new_read_available(self): \"\"\" New Read is available @return",
"self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 1000 if self.debug: print( \"%s: %s%s\" %",
"the same for EC and PH OEM circuit :return: int 0x01 = WakeUp",
"(1=EC, 4=PH) \"\"\" if \"EC\" == self.moduletype or \"PH\" == self.moduletype: device_type =",
"conf = self.read(register) self._check_calibration_confirm(conf) return conf def set_calibration_clear(self): \"\"\"clear calibration data \"\"\" if",
"int(round(value * 1000)).to_bytes(4, \"big\") self.write(register, byte_array) if self.debug: print(\"Value to send: %.2f\" %",
"0x04} register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self._set_calibration_registers(value) time.sleep(self.long_timeout) self.write(register, points[point]) # apply point calibration data",
"or \"PH\" == self.moduletype: firmware = self.read( self.OEM_EC_REGISTERS[\"device_firmware\"], self.ONE_BYTE_READ, ) if self.debug: print(\"Firmware",
"- \"high\": 3, \"\"\" binary_calib_status = self.EC_BINARY_CALIB_STATUS elif \"PH\" == self.moduletype: register =",
"\\ AtlasI2c.ADDR_OEM_DECIMAL or AtlasI2c.ADDR_EZO_DECIMAL\" ) else: \"\"\" write workflow to change physical i2c",
"== self.moduletype: device_type = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.ONE_BYTE_READ, ) if self.debug: print(\"Device type is:",
"Led state :param state: byte state => 0x01 = ON or 0x00 =",
"pH/! \"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_msb\"] # ec calibration wait",
"for µSiemens byte_array = int(round(value * 100)).to_bytes(4, \"big\") elif \"PH\" == self.moduletype: register",
"= self.OEM_EC_REGISTERS[\"device_led\"] led_status = self.read(register) if self.debug: print(\"Led status is currently: %s\" %",
"= self.read( self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 100 if self.debug: print(\"%s",
"action) if self.debug: print( \"Device is now: %s\" % (\"wakeup\" if hex(0x01) ==",
"== self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self.write(register,",
"% (self.moduletype), byte_array, ) time.sleep(self.short_timeout) self.write(register, byte_array) self.set_wakeup_sleep_mode(0x00) # sleep device after set",
"if hex(0x01) == hex(action) else \"sleep\") ) def set_ack_new_read_available(self): \"\"\"Ack new Read available",
"if \"EC\" == self.moduletype or \"PH\" == self.moduletype: info = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.TWO_BYTE_READ,",
"ack = 0x00 self.write(register, ack) if self.debug: print(\"ack new reading available register %s",
"\"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self.write(register, 0x01) # send 0x01 to clear",
"0x01 to clear calibration data time.sleep(self.short_timeout) # wait before read register to get",
"GreenPonik Source code is based on Atlas Scientific documentations: https://www.atlas-scientific.com/files/EC_oem_datasheet.pdf https://atlas-scientific.com/files/oem_pH_datasheet.pdf \"\"\" import",
"self.moduletype or \"PH\" == self.moduletype: device_type = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.ONE_BYTE_READ, ) if self.debug:",
"self.read(register) if self.debug: print( \"Device is currently in mode: %s\" % (\"wakeup\" if",
"\"\"\" if addr not in self.ADDR_OEM_HEXA and addr not in self.ADDR_OEM_DECIMAL: raise Exception(",
"in float for pH/! \"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_msb\"] #",
"the operation was correctly executed\") # ----- Getters ----- ######## def get_device_info(self): \"\"\"",
"sensor firmware @return int the firmware revision \"\"\" if \"EC\" == self.moduletype or",
"%.3f\" % float_from_hexa) return converted def _check_calibration_confirm(self, confirm): \"\"\" check the response of",
"def get_type(self): \"\"\" Read sensor type @return int the sensor type (1=EC, 4=PH)",
"not \"\"\" is_new_read = self.read( self.OEM_EC_REGISTERS[\"device_new_reading\"], self.ONE_BYTE_READ, ) return is_new_read def get_read(self): \"\"\"",
"- \"single\": 1, - \"low\": 2, - \"high\": 3, \"\"\" binary_calib_status = self.EC_BINARY_CALIB_STATUS",
"-> int: \"\"\" get Active or Hibernate device mode register is the same",
"argument, \\ can only be \"dry\", \"single\", \"low\", \"mid\", \"high\"' ) if \"EC\"",
"\"single\", \"low\", \"mid\", \"high\"' ) if \"EC\" == self.moduletype: points = {\"dry\": 0x02,",
"conf def set_calibration_clear(self): \"\"\"clear calibration data \"\"\" if \"EC\" == self.moduletype: register =",
"self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self.write(register, 0x01) # send 0x01",
"methods for EC and PH OEM circuits \"\"\" def _convert_raw_hex_to_float(self, byte_array): \"\"\" convert",
"self.OEM_EC_REGISTERS[\"device_type\"], self.TWO_BYTE_READ, ) return \"SUCCESS: %s, module type: %s and firmware is: %s\"",
"register = self.OEM_EC_REGISTERS[\"device_new_reading\"] ack = 0x00 self.write(register, ack) if self.debug: print(\"ack new reading",
"return binary_calib_status[r] def get_led(self) -> int: \"\"\" Get led state register is the",
"else \"OFF\") ) def set_wakeup_sleep_mode(self, action=0x01): \"\"\"change device mode to Active or Hibernate",
"( self.moduletype, value, \"µs\" if \"EC\" == self.moduletype else \"\", ) ) #",
"bytearray response to float result return float converted value \"\"\" hexstr = byte_array.hex()",
"string: %s\" % hexstr) print(\"float from hexa: %.3f\" % float_from_hexa) return converted def",
"by GreenPonik Source code is based on Atlas Scientific documentations: https://www.atlas-scientific.com/files/EC_oem_datasheet.pdf https://atlas-scientific.com/files/oem_pH_datasheet.pdf \"\"\"",
"\"\"\"apply the calibration :param value: float solution calibration value converted in float. EC",
"the sensor type (1=EC, 4=PH) \"\"\" if \"EC\" == self.moduletype or \"PH\" ==",
"float_from_hexa) return converted def _check_calibration_confirm(self, confirm): \"\"\" check the response of calibration confirm",
"== self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) elif \"PH\" == self.moduletype: rawhex",
"get Active or Hibernate device mode register is the same for EC and",
"def get_led(self) -> int: \"\"\" Get led state register is the same for",
"print( \"%s sent converted value to bytes: \" % (self.moduletype), byte_array, ) def",
"\"sleep\") ) def set_ack_new_read_available(self): \"\"\"Ack new Read available \"\"\" register = self.OEM_EC_REGISTERS[\"device_new_reading\"] ack",
"not in self.ADDR_OEM_DECIMAL: raise Exception( \"only decimal address expected, convert hexa by using",
"= self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"] elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"] byte_array = int(round(t *",
"based on Atlas Scientific documentations: https://www.atlas-scientific.com/files/EC_oem_datasheet.pdf https://atlas-scientific.com/files/oem_pH_datasheet.pdf \"\"\" import time from GreenPonik_Atlas_Scientific_OEM_i2c.AtlasOEMI2c import",
"or AtlasI2c.ADDR_EZO_DECIMAL\" ) else: \"\"\" write workflow to change physical i2c address \"\"\"",
"time from GreenPonik_Atlas_Scientific_OEM_i2c.AtlasOEMI2c import _AtlasOEMI2c class _CommonsI2c(_AtlasOEMI2c): \"\"\" commons methods for EC and",
"self._convert_raw_hex_to_float(rawhex) / 100 if self.debug: print(\"%s compensation Temperature: %s°c\" % (self.moduletype, value)) return",
"to change physical i2c address \"\"\" self.address(addr) raise NotImplementedError(\"write workflow to change physical",
"def set_wakeup_sleep_mode(self, action=0x01): \"\"\"change device mode to Active or Hibernate register is the",
"r) print(\"Who is calibrated? >\", binary_calib_status[r]) return binary_calib_status[r] def get_led(self) -> int: \"\"\"",
"is the same for EC and PH OEM circuit :return: int 0x01 =",
"return firmware def get_new_read_available(self): \"\"\" New Read is available @return int 1 if",
"the firmware revision \"\"\" if \"EC\" == self.moduletype or \"PH\" == self.moduletype: firmware",
"e.g. 1.413 = > 1413.0 :param point: string \"dry\", \"single\", \"low\", \"mid\", \"high\"",
"new Read available \"\"\" register = self.OEM_EC_REGISTERS[\"device_new_reading\"] ack = 0x00 self.write(register, ack) if",
") def get_type(self): \"\"\" Read sensor type @return int the sensor type (1=EC,",
"temperature :param t: float temperature value \"\"\" self.set_wakeup_sleep_mode(0x01) # wake device before set",
"New Read is available @return int 1 if new read available, 0 if",
"import _AtlasOEMI2c class _CommonsI2c(_AtlasOEMI2c): \"\"\" commons methods for EC and PH OEM circuits",
"value \"\"\" self.set_wakeup_sleep_mode(0x01) # wake device before set temperature time.sleep(self._long_timeout) if \"EC\" ==",
"self.read( self.OEM_PH_REGISTERS[\"device_ph_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 1000 if self.debug: print( \"%s:",
"self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 100 if self.debug: print(\"%s compensation Temperature: %s°c\"",
"self.debug: print( \"Device is currently in mode: %s\" % (\"wakeup\" if hex(0x01) ==",
"register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self.write(register, 0x01) # send 0x01 to clear calibration data time.sleep(self.short_timeout)",
"decoded to hexa string: %s\" % hexstr) print(\"float from hexa: %.3f\" % float_from_hexa)",
"i2c add \"\"\" if addr not in self.ADDR_OEM_HEXA and addr not in self.ADDR_OEM_DECIMAL:",
"100)).to_bytes(4, \"big\") elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_msb\"] byte_array = int(round(value *",
"def set_calibration_clear(self): \"\"\"clear calibration data \"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_request\"]",
"to clear calibration data time.sleep(self.short_timeout) # wait before read register to get confirmation",
"commons methods for EC and PH OEM circuits \"\"\" def _convert_raw_hex_to_float(self, byte_array): \"\"\"",
"Hibernate \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] self.write(register, action) if self.debug: print( \"Device is now:",
"calibration value converted in float. EC waiting for µS e.g. 1.413 = >",
"or \"PH\" == self.moduletype: info = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.TWO_BYTE_READ, ) return \"SUCCESS: %s,",
"\"\"\" Read sensor type @return int the sensor type (1=EC, 4=PH) \"\"\" if",
"elif \"PH\" == self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex)",
"Scientific i2c by GreenPonik Source code is based on Atlas Scientific documentations: https://www.atlas-scientific.com/files/EC_oem_datasheet.pdf",
"else \"\", ) ) # self.set_wakeup_sleep_mode(0x00) # sleep device after read return value",
"or Hibernate device mode register is the same for EC and PH OEM",
"self.ONE_BYTE_READ, ) if self.debug: print(\"Firmware type is: %s\" % firmware) return firmware def",
"== self.moduletype: info = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.TWO_BYTE_READ, ) return \"SUCCESS: %s, module type:",
"\"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] led_status = self.read(register) if self.debug: print(\"Led status is currently:",
"for pH/! \"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_msb\"] # ec calibration",
"== self.moduletype or \"PH\" == self.moduletype: firmware = self.read( self.OEM_EC_REGISTERS[\"device_firmware\"], self.ONE_BYTE_READ, ) if",
"= self.read( self.OEM_EC_REGISTERS[\"device_ec_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 100 elif \"PH\" ==",
"\"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_msb\"] byte_array = int(round(value * 1000)).to_bytes(4, \"big\") self.write(register,",
"self.moduletype or \"PH\" == self.moduletype: firmware = self.read( self.OEM_EC_REGISTERS[\"device_firmware\"], self.ONE_BYTE_READ, ) if self.debug:",
"return converted def _check_calibration_confirm(self, confirm): \"\"\" check the response of calibration confirm register",
"led_status = self.read(register) if self.debug: print(\"Led status is currently: %s\" % hex(led_status)) return",
"\"low\": 1, - \"mid\": 2, - \"high\": 3, \"\"\" binary_calib_status = self.PH_BINARY_CALIB_STATUS r",
"confirmation conf = self.read(register) self._check_calibration_confirm(conf) return conf def set_calibration_clear(self): \"\"\"clear calibration data \"\"\"",
"the device i2c address :param addr: int = new i2c add \"\"\" if",
"if self.debug: if hex(0x00) == hex(confirm): print(\"Calibration applied\") else: raise Exception(\"Cannot confirm the",
"to set: %.2f\" % t) print( \"%s sent converted temp to bytes: \"",
"is_new_read def get_read(self): \"\"\" Read sensor value @return float the sensor value \"\"\"",
"return led_status def get_wakeup_sleep_mode(self) -> int: \"\"\" get Active or Hibernate device mode",
"set temperature def _set_calibration_registers(self, value): \"\"\"calibration registers do not use alone because calibration",
"self.OEM_EC_REGISTERS[\"device_calibration_msb\"] # ec calibration wait for µSiemens byte_array = int(round(value * 100)).to_bytes(4, \"big\")",
"\"high\"' ) if \"EC\" == self.moduletype: points = {\"dry\": 0x02, \"single\": 0x03, \"low\":",
"float the sensor value \"\"\" # self.set_wakeup_sleep_mode(0x01) # wake device before read time.sleep(self._long_timeout)",
"calibrations data :return: string with current points calibrated :rtype: \"\"\" if \"EC\" ==",
"hex(0x00) == hex(confirm): print(\"Calibration applied\") else: raise Exception(\"Cannot confirm the operation was correctly",
"def set_ack_new_read_available(self): \"\"\"Ack new Read available \"\"\" register = self.OEM_EC_REGISTERS[\"device_new_reading\"] ack = 0x00",
"self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype: points = {\"low\": 0x02, \"mid\": 0x03, \"high\": 0x04}",
"on Atlas Scientific documentations: https://www.atlas-scientific.com/files/EC_oem_datasheet.pdf https://atlas-scientific.com/files/oem_pH_datasheet.pdf \"\"\" import time from GreenPonik_Atlas_Scientific_OEM_i2c.AtlasOEMI2c import _AtlasOEMI2c",
"OEM sensors in I2C mode. Atlas Scientific i2c by GreenPonik Source code is",
"= self._convert_raw_hex_to_float(rawhex) / 100 if self.debug: print(\"%s compensation Temperature: %s°c\" % (self.moduletype, value))",
"with current points calibrated :rtype: \"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_confirm\"]",
"self.read(register) self._check_calibration_confirm(conf) return conf def set_calibration_clear(self): \"\"\"clear calibration data \"\"\" if \"EC\" ==",
"state: byte state => 0x01 = ON or 0x00 = OFF \"\"\" register",
"in self.ADDR_OEM_DECIMAL: raise Exception( \"only decimal address expected, convert hexa by using \\",
"Scientific OEM sensors in I2C mode. Atlas Scientific i2c by GreenPonik Source code",
"new i2c add \"\"\" if addr not in self.ADDR_OEM_HEXA and addr not in",
"if hex(0x01) == hex(mode) else \"sleep\") ) return mode # ----- Setters -----",
"= self.OEM_PH_REGISTERS[\"device_calibration_request\"] self._set_calibration_registers(value) time.sleep(self.long_timeout) self.write(register, points[point]) # apply point calibration data time.sleep(self.short_timeout) #",
"i2c address\") def set_led(self, state=0x01): \"\"\"Change Led state :param state: byte state =>",
"type is: %s\" % device_type) return device_type def get_firmware(self): \"\"\" Read sensor firmware",
"new read available, 0 if not \"\"\" is_new_read = self.read( self.OEM_EC_REGISTERS[\"device_new_reading\"], self.ONE_BYTE_READ, )",
"if \"EC\" == self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) elif \"PH\" ==",
"WakeUp or 0x00 = Hibernate \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] self.write(register, action) if self.debug:",
"\"\"\" is_new_read = self.read( self.OEM_EC_REGISTERS[\"device_new_reading\"], self.ONE_BYTE_READ, ) return is_new_read def get_read(self): \"\"\" Read",
"else \"sleep\") ) return mode # ----- Setters ----- ######## def set_temperature(self, t=25.0):",
"info[0], info[1], ) def get_type(self): \"\"\" Read sensor type @return int the sensor",
"\"low\": 2, - \"high\": 3, \"\"\" binary_calib_status = self.EC_BINARY_CALIB_STATUS elif \"PH\" == self.moduletype:",
"== self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"low\": 1, - \"mid\": 2,",
"= {\"low\": 0x02, \"mid\": 0x03, \"high\": 0x04} register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self._set_calibration_registers(value) time.sleep(self.long_timeout) self.write(register,",
"WakeUp or 0x00 = Hibernate :rtype: int \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] mode =",
"hexa by using \\ AtlasI2c.ADDR_OEM_DECIMAL or AtlasI2c.ADDR_EZO_DECIMAL\" ) else: \"\"\" write workflow to",
"byte_array = int(round(t * 100)).to_bytes(4, \"big\") if self.debug: print(\"Temperature to set: %.2f\" %",
"get_temperature(self): \"\"\" Get current compensation temperature @return float temperature value \"\"\" if \"EC\"",
"1000 if self.debug: print( \"%s: %s%s\" % ( self.moduletype, value, \"µs\" if \"EC\"",
"sensors in I2C mode. Atlas Scientific i2c by GreenPonik Source code is based",
"OEM circuit :return: int 0x00 = OFF or 0x01 = ON :rtype: int",
"if new read available, 0 if not \"\"\" is_new_read = self.read( self.OEM_EC_REGISTERS[\"device_new_reading\"], self.ONE_BYTE_READ,",
"binary_calib_status = self.EC_BINARY_CALIB_STATUS elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits -",
"self._check_calibration_confirm(conf) return conf def set_calibration_clear(self): \"\"\"clear calibration data \"\"\" if \"EC\" == self.moduletype:",
"= self.PH_BINARY_CALIB_STATUS r = self.read(register) if self.debug: print(\"Binary result from OEM\", r) print(\"Who",
"calibrated? >\", binary_calib_status[r]) return binary_calib_status[r] def get_led(self) -> int: \"\"\" Get led state",
"same for EC and PH OEM circuit :return: int 0x01 = WakeUp or",
"by using set_calibration_apply /!in float micro siemens µS for EC/! /! in float",
"apply point calibration data time.sleep(self.short_timeout) # wait before read register to get confirmation",
"device before read time.sleep(self._long_timeout) if \"EC\" == self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_ec_msb\"], self.FOUR_BYTE_READ,",
"info = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.TWO_BYTE_READ, ) return \"SUCCESS: %s, module type: %s and",
"ON or 0x00 = OFF \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] self.write(register, state) if self.debug:",
"\"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"] elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"]",
"type (1=EC, 4=PH) \"\"\" if \"EC\" == self.moduletype or \"PH\" == self.moduletype: device_type",
"0, - \"single\": 1, - \"low\": 2, - \"high\": 3, \"\"\" binary_calib_status =",
"* 100)).to_bytes(4, \"big\") elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_msb\"] byte_array = int(round(value",
"OEM\", r) print(\"Who is calibrated? >\", binary_calib_status[r]) return binary_calib_status[r] def get_led(self) -> int:",
"self.debug: print(\"Led status is currently: %s\" % hex(led_status)) return led_status def get_wakeup_sleep_mode(self) ->",
"set_led(self, state=0x01): \"\"\"Change Led state :param state: byte state => 0x01 = ON",
"def get_read(self): \"\"\" Read sensor value @return float the sensor value \"\"\" #",
"register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype: points = {\"low\": 0x02, \"mid\": 0x03,",
"raise Exception(\"Cannot confirm the operation was correctly executed\") # ----- Getters ----- ########",
"bytes: \" % (self.moduletype), byte_array, ) time.sleep(self.short_timeout) self.write(register, byte_array) self.set_wakeup_sleep_mode(0x00) # sleep device",
":param point: string \"dry\", \"single\", \"low\", \"mid\", \"high\" only \"\"\" if point not",
"\"\"\" bits - \"dry\": 0, - \"single\": 1, - \"low\": 2, - \"high\":",
"\"single\", \"low\", \"mid\", \"high\"): raise Exception( 'missing string point argument, \\ can only",
"byte state => 0x01 = ON or 0x00 = OFF \"\"\" register =",
"or Hibernate register is the same for EC and PH OEM circuit :param",
"# wake device before set temperature time.sleep(self._long_timeout) if \"EC\" == self.moduletype: register =",
"string module type, firmware version \"\"\" if \"EC\" == self.moduletype or \"PH\" ==",
"% firmware) return firmware def get_new_read_available(self): \"\"\" New Read is available @return int",
"using set_calibration_apply /!in float micro siemens µS for EC/! /! in float for",
"device information @return string module type, firmware version \"\"\" if \"EC\" == self.moduletype",
"sleep device after set temperature def _set_calibration_registers(self, value): \"\"\"calibration registers do not use",
"= self._convert_raw_hex_to_float(rawhex) / 100 elif \"PH\" == self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_ph_msb\"], self.FOUR_BYTE_READ,",
"= new i2c add \"\"\" if addr not in self.ADDR_OEM_HEXA and addr not",
"----- ######## def get_device_info(self): \"\"\" Get device information @return string module type, firmware",
"% ( self.moduletype, info[0], info[1], ) def get_type(self): \"\"\" Read sensor type @return",
"self.moduletype, info[0], info[1], ) def get_type(self): \"\"\" Read sensor type @return int the",
"Read sensor firmware @return int the firmware revision \"\"\" if \"EC\" == self.moduletype",
"0x00 = OFF or 0x01 = ON :rtype: int \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"]",
"elif \"PH\" == self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_ph_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex)",
"register = self.OEM_EC_REGISTERS[\"device_led\"] self.write(register, state) if self.debug: print( \"Led status change to: %s\"",
") if \"EC\" == self.moduletype: points = {\"dry\": 0x02, \"single\": 0x03, \"low\": 0x04,",
"self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"] elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"] byte_array = int(round(t * 100)).to_bytes(4,",
"response of calibration confirm register \"\"\" if self.debug: if hex(0x00) == hex(confirm): print(\"Calibration",
"firmware = self.read( self.OEM_EC_REGISTERS[\"device_firmware\"], self.ONE_BYTE_READ, ) if self.debug: print(\"Firmware type is: %s\" %",
"\"\", ) ) # self.set_wakeup_sleep_mode(0x00) # sleep device after read return value def",
"float solution calibration value converted in float. EC waiting for µS e.g. 1.413",
"\"\"\"calibration registers do not use alone because calibration is apply by using set_calibration_apply",
"== self.moduletype: points = {\"dry\": 0x02, \"single\": 0x03, \"low\": 0x04, \"high\": 0x05} register",
"@return string module type, firmware version \"\"\" if \"EC\" == self.moduletype or \"PH\"",
"points = {\"dry\": 0x02, \"single\": 0x03, \"low\": 0x04, \"high\": 0x05} register = self.OEM_EC_REGISTERS[\"device_calibration_request\"]",
"documentations: https://www.atlas-scientific.com/files/EC_oem_datasheet.pdf https://atlas-scientific.com/files/oem_pH_datasheet.pdf \"\"\" import time from GreenPonik_Atlas_Scientific_OEM_i2c.AtlasOEMI2c import _AtlasOEMI2c class _CommonsI2c(_AtlasOEMI2c): \"\"\"",
"/! in float for pH/! \"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_msb\"]",
"apply by using set_calibration_apply /!in float micro siemens µS for EC/! /! in",
"\"dry\", \"single\", \"low\", \"mid\", \"high\" only \"\"\" if point not in (\"dry\", \"single\",",
"\"mid\", \"high\"): raise Exception( 'missing string point argument, \\ can only be \"dry\",",
"= self.OEM_PH_REGISTERS[\"device_calibration_request\"] self.write(register, 0x01) # send 0x01 to clear calibration data time.sleep(self.short_timeout) #",
"\"Led status change to: %s\" % (\"On\" if hex(0x01) == hex(state) else \"OFF\")",
"self.moduletype, value, \"µs\" if \"EC\" == self.moduletype else \"\", ) ) # self.set_wakeup_sleep_mode(0x00)",
"hex(0x01) == hex(mode) else \"sleep\") ) return mode # ----- Setters ----- ########",
"Atlas Scientific i2c by GreenPonik Source code is based on Atlas Scientific documentations:",
") # self.set_wakeup_sleep_mode(0x00) # sleep device after read return value def get_temperature(self): \"\"\"",
"read register to get confirmation conf = self.read(register) self._check_calibration_confirm(conf) return conf def set_calibration_clear(self):",
"_check_calibration_confirm(self, confirm): \"\"\" check the response of calibration confirm register \"\"\" if self.debug:",
"calibration data time.sleep(self.short_timeout) # wait before read register to get confirmation conf =",
"- \"mid\": 2, - \"high\": 3, \"\"\" binary_calib_status = self.PH_BINARY_CALIB_STATUS r = self.read(register)",
"the same for EC and PH OEM circuit :return: int 0x00 = OFF",
"PH OEM circuit :param byte: action => 0x01 = WakeUp or 0x00 =",
"raise Exception( \"only decimal address expected, convert hexa by using \\ AtlasI2c.ADDR_OEM_DECIMAL or",
"%.2f\" % value) print( \"%s sent converted value to bytes: \" % (self.moduletype),",
"change physical i2c address \"\"\" self.address(addr) raise NotImplementedError(\"write workflow to change physical i2c",
"if hex(0x01) == hex(state) else \"OFF\") ) def set_wakeup_sleep_mode(self, action=0x01): \"\"\"change device mode",
"mode register is the same for EC and PH OEM circuit :return: int",
"I2C mode. Atlas Scientific i2c by GreenPonik Source code is based on Atlas",
"100 if self.debug: print(\"%s compensation Temperature: %s°c\" % (self.moduletype, value)) return value def",
"and firmware is: %s\" % ( self.moduletype, info[0], info[1], ) def get_type(self): \"\"\"",
"######## def set_temperature(self, t=25.0): \"\"\"Set the compensation temperature :param t: float temperature value",
"3, \"\"\" binary_calib_status = self.EC_BINARY_CALIB_STATUS elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_confirm\"] \"\"\"",
"Exception( 'missing string point argument, \\ can only be \"dry\", \"single\", \"low\", \"mid\",",
"self.OEM_PH_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"low\": 1, - \"mid\": 2, - \"high\": 3, \"\"\"",
"== self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self.write(register, 0x01) # send 0x01 to clear calibration",
"the response of calibration confirm register \"\"\" if self.debug: if hex(0x00) == hex(confirm):",
"0x01 = ON :rtype: int \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] led_status = self.read(register) if",
"info[1], ) def get_type(self): \"\"\" Read sensor type @return int the sensor type",
"byte_array): \"\"\" convert bytearray response to float result return float converted value \"\"\"",
"def get_temperature(self): \"\"\" Get current compensation temperature @return float temperature value \"\"\" if",
"return device_type def get_firmware(self): \"\"\" Read sensor firmware @return int the firmware revision",
"float temperature value \"\"\" self.set_wakeup_sleep_mode(0x01) # wake device before set temperature time.sleep(self._long_timeout) if",
"\"mid\", \"high\"' ) if \"EC\" == self.moduletype: points = {\"dry\": 0x02, \"single\": 0x03,",
"the same for EC and PH OEM circuit :param byte: action => 0x01",
"firmware revision \"\"\" if \"EC\" == self.moduletype or \"PH\" == self.moduletype: firmware =",
"% value) print( \"%s sent converted value to bytes: \" % (self.moduletype), byte_array,",
"100)).to_bytes(4, \"big\") if self.debug: print(\"Temperature to set: %.2f\" % t) print( \"%s sent",
"Temperature: %s°c\" % (self.moduletype, value)) return value def get_calibration(self): \"\"\" Get current calibrations",
"int: \"\"\" get Active or Hibernate device mode register is the same for",
"= self.read( self.OEM_EC_REGISTERS[\"device_new_reading\"], self.ONE_BYTE_READ, ) return is_new_read def get_read(self): \"\"\" Read sensor value",
"print(\"Byte Array to decode: \", byte_array) print(\"Byte Array decoded to hexa string: %s\"",
"conf = self.read(register) self._check_calibration_confirm(conf) return conf def set_i2c_addr(self, addr): \"\"\"Change the device i2c",
"same for EC and PH OEM circuit :param byte: action => 0x01 =",
":param value: float solution calibration value converted in float. EC waiting for µS",
"and PH OEM circuit :param byte: action => 0x01 = WakeUp or 0x00",
"\"mid\": 2, - \"high\": 3, \"\"\" binary_calib_status = self.PH_BINARY_CALIB_STATUS r = self.read(register) if",
"µS for EC/! /! in float for pH/! \"\"\" if \"EC\" == self.moduletype:",
"if self.debug: print(\"Binary result from OEM\", r) print(\"Who is calibrated? >\", binary_calib_status[r]) return",
"module type, firmware version \"\"\" if \"EC\" == self.moduletype or \"PH\" == self.moduletype:",
"read return value def get_temperature(self): \"\"\" Get current compensation temperature @return float temperature",
"if self.debug: print(\"Device type is: %s\" % device_type) return device_type def get_firmware(self): \"\"\"",
"\"SUCCESS: %s, module type: %s and firmware is: %s\" % ( self.moduletype, info[0],",
"= Hibernate \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] self.write(register, action) if self.debug: print( \"Device is",
"OEM circuit :return: int 0x01 = WakeUp or 0x00 = Hibernate :rtype: int",
"\"EC\" == self.moduletype else \"\", ) ) # self.set_wakeup_sleep_mode(0x00) # sleep device after",
"print( \"%s sent converted temp to bytes: \" % (self.moduletype), byte_array, ) time.sleep(self.short_timeout)",
"== self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"dry\": 0, - \"single\": 1,",
"= self.OEM_PH_REGISTERS[\"device_calibration_msb\"] byte_array = int(round(value * 1000)).to_bytes(4, \"big\") self.write(register, byte_array) if self.debug: print(\"Value",
"OEM circuits \"\"\" def _convert_raw_hex_to_float(self, byte_array): \"\"\" convert bytearray response to float result",
":rtype: int \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] mode = self.read(register) if self.debug: print( \"Device",
"print( \"Device is currently in mode: %s\" % (\"wakeup\" if hex(0x01) == hex(mode)",
"----- ######## def set_temperature(self, t=25.0): \"\"\"Set the compensation temperature :param t: float temperature",
"% (self.moduletype), byte_array, ) def set_calibration_apply(self, value, point=\"\"): \"\"\"apply the calibration :param value:",
":return: int 0x01 = WakeUp or 0x00 = Hibernate :rtype: int \"\"\" register",
"\\ can only be \"dry\", \"single\", \"low\", \"mid\", \"high\"' ) if \"EC\" ==",
"self.write(register, points[point]) # apply point calibration data time.sleep(self.short_timeout) # wait before read register",
"----------- Class to communicate with Atlas Scientific OEM sensors in I2C mode. Atlas",
"if \"EC\" == self.moduletype or \"PH\" == self.moduletype: firmware = self.read( self.OEM_EC_REGISTERS[\"device_firmware\"], self.ONE_BYTE_READ,",
"decode: \", byte_array) print(\"Byte Array decoded to hexa string: %s\" % hexstr) print(\"float",
"hexa string: %s\" % hexstr) print(\"float from hexa: %.3f\" % float_from_hexa) return converted",
"\"\"\" if \"EC\" == self.moduletype or \"PH\" == self.moduletype: firmware = self.read( self.OEM_EC_REGISTERS[\"device_firmware\"],",
"\"\"\" Read sensor firmware @return int the firmware revision \"\"\" if \"EC\" ==",
"== self.moduletype else \"\", ) ) # self.set_wakeup_sleep_mode(0x00) # sleep device after read",
"OFF or 0x01 = ON :rtype: int \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] led_status =",
"string \"dry\", \"single\", \"low\", \"mid\", \"high\" only \"\"\" if point not in (\"dry\",",
"string point argument, \\ can only be \"dry\", \"single\", \"low\", \"mid\", \"high\"' )",
"type, firmware version \"\"\" if \"EC\" == self.moduletype or \"PH\" == self.moduletype: info",
"\"PH\" == self.moduletype: device_type = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.ONE_BYTE_READ, ) if self.debug: print(\"Device type",
"- \"low\": 2, - \"high\": 3, \"\"\" binary_calib_status = self.EC_BINARY_CALIB_STATUS elif \"PH\" ==",
"from hexa: %.3f\" % float_from_hexa) return converted def _check_calibration_confirm(self, confirm): \"\"\" check the",
"2, - \"high\": 3, \"\"\" binary_calib_status = self.PH_BINARY_CALIB_STATUS r = self.read(register) if self.debug:",
"% (self.moduletype, value)) return value def get_calibration(self): \"\"\" Get current calibrations data :return:",
"type @return int the sensor type (1=EC, 4=PH) \"\"\" if \"EC\" == self.moduletype",
") elif \"PH\" == self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) value =",
"set_calibration_apply(self, value, point=\"\"): \"\"\"apply the calibration :param value: float solution calibration value converted",
"\"\"\" get Active or Hibernate device mode register is the same for EC",
"register is the same for EC and PH OEM circuit :return: int 0x00",
"self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) elif \"PH\" == self.moduletype: rawhex =",
"\"\"\" bits - \"low\": 1, - \"mid\": 2, - \"high\": 3, \"\"\" binary_calib_status",
"Hibernate :rtype: int \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] mode = self.read(register) if self.debug: print(",
"\"high\": 3, \"\"\" binary_calib_status = self.PH_BINARY_CALIB_STATUS r = self.read(register) if self.debug: print(\"Binary result",
"after set temperature def _set_calibration_registers(self, value): \"\"\"calibration registers do not use alone because",
"2, - \"high\": 3, \"\"\" binary_calib_status = self.EC_BINARY_CALIB_STATUS elif \"PH\" == self.moduletype: register",
"to: %s\" % (\"On\" if hex(0x01) == hex(state) else \"OFF\") ) def set_wakeup_sleep_mode(self,",
"if addr not in self.ADDR_OEM_HEXA and addr not in self.ADDR_OEM_DECIMAL: raise Exception( \"only",
"float temperature value \"\"\" if \"EC\" == self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ,",
"self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_ec_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 100 elif",
"temperature def _set_calibration_registers(self, value): \"\"\"calibration registers do not use alone because calibration is",
"0x01 = WakeUp or 0x00 = Hibernate :rtype: int \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"]",
") return mode # ----- Setters ----- ######## def set_temperature(self, t=25.0): \"\"\"Set the",
"\"low\": 0x04, \"high\": 0x05} register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype: points =",
"\"\"\"clear calibration data \"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\"",
"value def get_temperature(self): \"\"\" Get current compensation temperature @return float temperature value \"\"\"",
"calibration :param value: float solution calibration value converted in float. EC waiting for",
"float result return float converted value \"\"\" hexstr = byte_array.hex() float_from_hexa = float.fromhex(byte_array.hex())",
"if self.debug: print(\"Value to send: %.2f\" % value) print( \"%s sent converted value",
"compensation Temperature: %s°c\" % (self.moduletype, value)) return value def get_calibration(self): \"\"\" Get current",
"return conf def set_calibration_clear(self): \"\"\"clear calibration data \"\"\" if \"EC\" == self.moduletype: register",
"self.OEM_EC_REGISTERS[\"device_ec_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 100 elif \"PH\" == self.moduletype: rawhex",
"/usr/bin/python3 \"\"\" Description ----------- Class to communicate with Atlas Scientific OEM sensors in",
"same for EC and PH OEM circuit :return: int 0x00 = OFF or",
"device mode to Active or Hibernate register is the same for EC and",
"data :return: string with current points calibrated :rtype: \"\"\" if \"EC\" == self.moduletype:",
"if self.debug: print(\"Led status is currently: %s\" % hex(led_status)) return led_status def get_wakeup_sleep_mode(self)",
"% (\"On\" if hex(0x01) == hex(state) else \"OFF\") ) def set_wakeup_sleep_mode(self, action=0x01): \"\"\"change",
"temp to bytes: \" % (self.moduletype), byte_array, ) time.sleep(self.short_timeout) self.write(register, byte_array) self.set_wakeup_sleep_mode(0x00) #",
"string with current points calibrated :rtype: \"\"\" if \"EC\" == self.moduletype: register =",
"1, - \"mid\": 2, - \"high\": 3, \"\"\" binary_calib_status = self.PH_BINARY_CALIB_STATUS r =",
"return value def get_calibration(self): \"\"\" Get current calibrations data :return: string with current",
"or 0x00 = Hibernate \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] self.write(register, action) if self.debug: print(",
"self.OEM_EC_REGISTERS[\"device_led\"] led_status = self.read(register) if self.debug: print(\"Led status is currently: %s\" % hex(led_status))",
"\"PH\" == self.moduletype: info = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.TWO_BYTE_READ, ) return \"SUCCESS: %s, module",
"float. EC waiting for µS e.g. 1.413 = > 1413.0 :param point: string",
":rtype: int \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] led_status = self.read(register) if self.debug: print(\"Led status",
"to communicate with Atlas Scientific OEM sensors in I2C mode. Atlas Scientific i2c",
"\"PH\" == self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) /",
"% hex(led_status)) return led_status def get_wakeup_sleep_mode(self) -> int: \"\"\" get Active or Hibernate",
"0x03, \"high\": 0x04} register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self._set_calibration_registers(value) time.sleep(self.long_timeout) self.write(register, points[point]) # apply point",
") else: \"\"\" write workflow to change physical i2c address \"\"\" self.address(addr) raise",
"binary_calib_status[r]) return binary_calib_status[r] def get_led(self) -> int: \"\"\" Get led state register is",
"\"\"\" binary_calib_status = self.EC_BINARY_CALIB_STATUS elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits",
"# sleep device after set temperature def _set_calibration_registers(self, value): \"\"\"calibration registers do not",
"self.read( self.OEM_EC_REGISTERS[\"device_firmware\"], self.ONE_BYTE_READ, ) if self.debug: print(\"Firmware type is: %s\" % firmware) return",
"data time.sleep(self.short_timeout) # wait before read register to get confirmation conf = self.read(register)",
"value to bytes: \" % (self.moduletype), byte_array, ) def set_calibration_apply(self, value, point=\"\"): \"\"\"apply",
"hexstr) print(\"float from hexa: %.3f\" % float_from_hexa) return converted def _check_calibration_confirm(self, confirm): \"\"\"",
"print(\"float from hexa: %.3f\" % float_from_hexa) return converted def _check_calibration_confirm(self, confirm): \"\"\" check",
"_convert_raw_hex_to_float(self, byte_array): \"\"\" convert bytearray response to float result return float converted value",
"get_wakeup_sleep_mode(self) -> int: \"\"\" get Active or Hibernate device mode register is the",
"== hex(action) else \"sleep\") ) def set_ack_new_read_available(self): \"\"\"Ack new Read available \"\"\" register",
"circuits \"\"\" def _convert_raw_hex_to_float(self, byte_array): \"\"\" convert bytearray response to float result return",
"self.TWO_BYTE_READ, ) return \"SUCCESS: %s, module type: %s and firmware is: %s\" %",
"Scientific documentations: https://www.atlas-scientific.com/files/EC_oem_datasheet.pdf https://atlas-scientific.com/files/oem_pH_datasheet.pdf \"\"\" import time from GreenPonik_Atlas_Scientific_OEM_i2c.AtlasOEMI2c import _AtlasOEMI2c class _CommonsI2c(_AtlasOEMI2c):",
"\"\"\" if \"EC\" == self.moduletype or \"PH\" == self.moduletype: info = self.read( self.OEM_EC_REGISTERS[\"device_type\"],",
"byte_array = int(round(value * 1000)).to_bytes(4, \"big\") self.write(register, byte_array) if self.debug: print(\"Value to send:",
"value = self._convert_raw_hex_to_float(rawhex) / 100 elif \"PH\" == self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_ph_msb\"],",
"\", byte_array) print(\"Byte Array decoded to hexa string: %s\" % hexstr) print(\"float from",
"addr not in self.ADDR_OEM_HEXA and addr not in self.ADDR_OEM_DECIMAL: raise Exception( \"only decimal",
"Array decoded to hexa string: %s\" % hexstr) print(\"float from hexa: %.3f\" %",
"\"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] self.write(register, state) if self.debug: print( \"Led status change to:",
"= 0x00 self.write(register, ack) if self.debug: print(\"ack new reading available register %s to",
"int(round(value * 100)).to_bytes(4, \"big\") elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_msb\"] byte_array =",
"\"\"\" commons methods for EC and PH OEM circuits \"\"\" def _convert_raw_hex_to_float(self, byte_array):",
"self.OEM_PH_REGISTERS[\"device_ph_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 1000 if self.debug: print( \"%s: %s%s\"",
"t: float temperature value \"\"\" self.set_wakeup_sleep_mode(0x01) # wake device before set temperature time.sleep(self._long_timeout)",
"# sleep device after read return value def get_temperature(self): \"\"\" Get current compensation",
"get_type(self): \"\"\" Read sensor type @return int the sensor type (1=EC, 4=PH) \"\"\"",
"byte_array = int(round(value * 100)).to_bytes(4, \"big\") elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_msb\"]",
"(\"wakeup\" if hex(0x01) == hex(action) else \"sleep\") ) def set_ack_new_read_available(self): \"\"\"Ack new Read",
"def get_device_info(self): \"\"\" Get device information @return string module type, firmware version \"\"\"",
"rawhex = self.read( self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) elif \"PH\" == self.moduletype: rawhex = self.read(",
"\"dry\": 0, - \"single\": 1, - \"low\": 2, - \"high\": 3, \"\"\" binary_calib_status",
"is: %s\" % firmware) return firmware def get_new_read_available(self): \"\"\" New Read is available",
"is currently: %s\" % hex(led_status)) return led_status def get_wakeup_sleep_mode(self) -> int: \"\"\" get",
"mode # ----- Setters ----- ######## def set_temperature(self, t=25.0): \"\"\"Set the compensation temperature",
"byte_array, ) time.sleep(self.short_timeout) self.write(register, byte_array) self.set_wakeup_sleep_mode(0x00) # sleep device after set temperature def",
"# self.set_wakeup_sleep_mode(0x00) # sleep device after read return value def get_temperature(self): \"\"\" Get",
"state => 0x01 = ON or 0x00 = OFF \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"]",
"hex(0x01) == hex(state) else \"OFF\") ) def set_wakeup_sleep_mode(self, action=0x01): \"\"\"change device mode to",
"get_calibration(self): \"\"\" Get current calibrations data :return: string with current points calibrated :rtype:",
"for EC and PH OEM circuit :param byte: action => 0x01 = WakeUp",
") return \"SUCCESS: %s, module type: %s and firmware is: %s\" % (",
"self.OEM_EC_REGISTERS[\"device_new_reading\"], self.ONE_BYTE_READ, ) return is_new_read def get_read(self): \"\"\" Read sensor value @return float",
"== self.moduletype: register = self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"] byte_array = int(round(t * 100)).to_bytes(4, \"big\") if self.debug:",
"use alone because calibration is apply by using set_calibration_apply /!in float micro siemens",
"self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"dry\": 0, - \"single\": 1, -",
"value @return float the sensor value \"\"\" # self.set_wakeup_sleep_mode(0x01) # wake device before",
"_AtlasOEMI2c class _CommonsI2c(_AtlasOEMI2c): \"\"\" commons methods for EC and PH OEM circuits \"\"\"",
"value) print( \"%s sent converted value to bytes: \" % (self.moduletype), byte_array, )",
"to get confirmation conf = self.read(register) self._check_calibration_confirm(conf) return conf def set_calibration_clear(self): \"\"\"clear calibration",
"== self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_ph_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 1000",
"int \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] mode = self.read(register) if self.debug: print( \"Device is",
"set_calibration_clear(self): \"\"\"clear calibration data \"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif",
"register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self.write(register, 0x01) #",
"time.sleep(self.short_timeout) # wait before read register to get confirmation conf = self.read(register) self._check_calibration_confirm(conf)",
") time.sleep(self.short_timeout) self.write(register, byte_array) self.set_wakeup_sleep_mode(0x00) # sleep device after set temperature def _set_calibration_registers(self,",
"\"EC\" == self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_ec_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) /",
"self.EC_BINARY_CALIB_STATUS elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"low\": 1,",
"\"dry\", \"single\", \"low\", \"mid\", \"high\"' ) if \"EC\" == self.moduletype: points = {\"dry\":",
"hexa: %.3f\" % float_from_hexa) return converted def _check_calibration_confirm(self, confirm): \"\"\" check the response",
"GreenPonik_Atlas_Scientific_OEM_i2c.AtlasOEMI2c import _AtlasOEMI2c class _CommonsI2c(_AtlasOEMI2c): \"\"\" commons methods for EC and PH OEM",
"not in self.ADDR_OEM_HEXA and addr not in self.ADDR_OEM_DECIMAL: raise Exception( \"only decimal address",
"conf def set_i2c_addr(self, addr): \"\"\"Change the device i2c address :param addr: int =",
"confirm): \"\"\" check the response of calibration confirm register \"\"\" if self.debug: if",
"point calibration data time.sleep(self.short_timeout) # wait before read register to get confirmation conf",
"self.debug: print(\"Temperature to set: %.2f\" % t) print( \"%s sent converted temp to",
"= byte_array.hex() float_from_hexa = float.fromhex(byte_array.hex()) converted = float_from_hexa if self.debug: print(\"Byte Array to",
"\"\"\"Set the compensation temperature :param t: float temperature value \"\"\" self.set_wakeup_sleep_mode(0x01) # wake",
"@return int 1 if new read available, 0 if not \"\"\" is_new_read =",
"self.moduletype: info = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.TWO_BYTE_READ, ) return \"SUCCESS: %s, module type: %s",
"self.moduletype: firmware = self.read( self.OEM_EC_REGISTERS[\"device_firmware\"], self.ONE_BYTE_READ, ) if self.debug: print(\"Firmware type is: %s\"",
"self.debug: print( \"%s: %s%s\" % ( self.moduletype, value, \"µs\" if \"EC\" == self.moduletype",
"self.write(register, byte_array) self.set_wakeup_sleep_mode(0x00) # sleep device after set temperature def _set_calibration_registers(self, value): \"\"\"calibration",
"= self.OEM_EC_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"dry\": 0, - \"single\": 1, - \"low\": 2,",
"current compensation temperature @return float temperature value \"\"\" if \"EC\" == self.moduletype: rawhex",
"Description ----------- Class to communicate with Atlas Scientific OEM sensors in I2C mode.",
"set temperature time.sleep(self._long_timeout) if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"] elif \"PH\" ==",
"%s%s\" % ( self.moduletype, value, \"µs\" if \"EC\" == self.moduletype else \"\", )",
"Read sensor value @return float the sensor value \"\"\" # self.set_wakeup_sleep_mode(0x01) # wake",
"i2c address :param addr: int = new i2c add \"\"\" if addr not",
"%s\" % (\"wakeup\" if hex(0x01) == hex(action) else \"sleep\") ) def set_ack_new_read_available(self): \"\"\"Ack",
"\"\"\" Get current calibrations data :return: string with current points calibrated :rtype: \"\"\"",
"\"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"low\": 1, - \"mid\":",
"ON :rtype: int \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] led_status = self.read(register) if self.debug: print(\"Led",
"in (\"dry\", \"single\", \"low\", \"mid\", \"high\"): raise Exception( 'missing string point argument, \\",
"elif \"PH\" == self.moduletype: points = {\"low\": 0x02, \"mid\": 0x03, \"high\": 0x04} register",
"float_from_hexa if self.debug: print(\"Byte Array to decode: \", byte_array) print(\"Byte Array decoded to",
"/ 100 elif \"PH\" == self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_ph_msb\"], self.FOUR_BYTE_READ, ) value",
"mode to Active or Hibernate register is the same for EC and PH",
"\"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] self.write(register, action) if self.debug: print( \"Device is now: %s\"",
"\"high\": 0x04} register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self._set_calibration_registers(value) time.sleep(self.long_timeout) self.write(register, points[point]) # apply point calibration",
"== self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_msb\"] # ec calibration wait for µSiemens byte_array =",
"add \"\"\" if addr not in self.ADDR_OEM_HEXA and addr not in self.ADDR_OEM_DECIMAL: raise",
"-> int: \"\"\" Get led state register is the same for EC and",
"\"\"\" # self.set_wakeup_sleep_mode(0x01) # wake device before read time.sleep(self._long_timeout) if \"EC\" == self.moduletype:",
"for µS e.g. 1.413 = > 1413.0 :param point: string \"dry\", \"single\", \"low\",",
"point argument, \\ can only be \"dry\", \"single\", \"low\", \"mid\", \"high\"' ) if",
"currently: %s\" % hex(led_status)) return led_status def get_wakeup_sleep_mode(self) -> int: \"\"\" get Active",
"hexstr = byte_array.hex() float_from_hexa = float.fromhex(byte_array.hex()) converted = float_from_hexa if self.debug: print(\"Byte Array",
"\"%s sent converted temp to bytes: \" % (self.moduletype), byte_array, ) time.sleep(self.short_timeout) self.write(register,",
"calibrated :rtype: \"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits -",
"Get device information @return string module type, firmware version \"\"\" if \"EC\" ==",
"= self.EC_BINARY_CALIB_STATUS elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"low\":",
"int = new i2c add \"\"\" if addr not in self.ADDR_OEM_HEXA and addr",
"# self.set_wakeup_sleep_mode(0x01) # wake device before read time.sleep(self._long_timeout) if \"EC\" == self.moduletype: rawhex",
"= self.OEM_EC_REGISTERS[\"device_led\"] self.write(register, state) if self.debug: print( \"Led status change to: %s\" %",
"\"OFF\") ) def set_wakeup_sleep_mode(self, action=0x01): \"\"\"change device mode to Active or Hibernate register",
"mode = self.read(register) if self.debug: print( \"Device is currently in mode: %s\" %",
"{\"low\": 0x02, \"mid\": 0x03, \"high\": 0x04} register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self._set_calibration_registers(value) time.sleep(self.long_timeout) self.write(register, points[point])",
"\"high\": 3, \"\"\" binary_calib_status = self.EC_BINARY_CALIB_STATUS elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_confirm\"]",
"register to get confirmation conf = self.read(register) self._check_calibration_confirm(conf) return conf def set_i2c_addr(self, addr):",
"= OFF \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] self.write(register, state) if self.debug: print( \"Led status",
"_CommonsI2c(_AtlasOEMI2c): \"\"\" commons methods for EC and PH OEM circuits \"\"\" def _convert_raw_hex_to_float(self,",
"== self.moduletype: firmware = self.read( self.OEM_EC_REGISTERS[\"device_firmware\"], self.ONE_BYTE_READ, ) if self.debug: print(\"Firmware type is:",
"self.OEM_PH_REGISTERS[\"device_calibration_request\"] self.write(register, 0x01) # send 0x01 to clear calibration data time.sleep(self.short_timeout) # wait",
"Source code is based on Atlas Scientific documentations: https://www.atlas-scientific.com/files/EC_oem_datasheet.pdf https://atlas-scientific.com/files/oem_pH_datasheet.pdf \"\"\" import time",
"register to get confirmation conf = self.read(register) self._check_calibration_confirm(conf) return conf def set_calibration_clear(self): \"\"\"clear",
"= self.read(register) self._check_calibration_confirm(conf) return conf def set_calibration_clear(self): \"\"\"clear calibration data \"\"\" if \"EC\"",
"self._check_calibration_confirm(conf) return conf def set_i2c_addr(self, addr): \"\"\"Change the device i2c address :param addr:",
"\"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype: register",
"if self.debug: print( \"Device is currently in mode: %s\" % (\"wakeup\" if hex(0x01)",
"( self.moduletype, info[0], info[1], ) def get_type(self): \"\"\" Read sensor type @return int",
"confirm register \"\"\" if self.debug: if hex(0x00) == hex(confirm): print(\"Calibration applied\") else: raise",
"\" % (self.moduletype), byte_array, ) time.sleep(self.short_timeout) self.write(register, byte_array) self.set_wakeup_sleep_mode(0x00) # sleep device after",
"https://www.atlas-scientific.com/files/EC_oem_datasheet.pdf https://atlas-scientific.com/files/oem_pH_datasheet.pdf \"\"\" import time from GreenPonik_Atlas_Scientific_OEM_i2c.AtlasOEMI2c import _AtlasOEMI2c class _CommonsI2c(_AtlasOEMI2c): \"\"\" commons",
"if hex(0x00) == hex(confirm): print(\"Calibration applied\") else: raise Exception(\"Cannot confirm the operation was",
"\"EC\" == self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) elif \"PH\" == self.moduletype:",
"self.debug: print(\"%s compensation Temperature: %s°c\" % (self.moduletype, value)) return value def get_calibration(self): \"\"\"",
">\", binary_calib_status[r]) return binary_calib_status[r] def get_led(self) -> int: \"\"\" Get led state register",
"to bytes: \" % (self.moduletype), byte_array, ) def set_calibration_apply(self, value, point=\"\"): \"\"\"apply the",
"\"EC\" == self.moduletype or \"PH\" == self.moduletype: firmware = self.read( self.OEM_EC_REGISTERS[\"device_firmware\"], self.ONE_BYTE_READ, )",
"point not in (\"dry\", \"single\", \"low\", \"mid\", \"high\"): raise Exception( 'missing string point",
"= WakeUp or 0x00 = Hibernate :rtype: int \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] mode",
"response to float result return float converted value \"\"\" hexstr = byte_array.hex() float_from_hexa",
"to send: %.2f\" % value) print( \"%s sent converted value to bytes: \"",
"self.read(register) self._check_calibration_confirm(conf) return conf def set_i2c_addr(self, addr): \"\"\"Change the device i2c address :param",
"return conf def set_i2c_addr(self, addr): \"\"\"Change the device i2c address :param addr: int",
"\"\"\" if \"EC\" == self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) elif \"PH\"",
"else: \"\"\" write workflow to change physical i2c address \"\"\" self.address(addr) raise NotImplementedError(\"write",
"def _check_calibration_confirm(self, confirm): \"\"\" check the response of calibration confirm register \"\"\" if",
"\"\"\" binary_calib_status = self.PH_BINARY_CALIB_STATUS r = self.read(register) if self.debug: print(\"Binary result from OEM\",",
") def set_ack_new_read_available(self): \"\"\"Ack new Read available \"\"\" register = self.OEM_EC_REGISTERS[\"device_new_reading\"] ack =",
"int 0x01 = WakeUp or 0x00 = Hibernate :rtype: int \"\"\" register =",
"action => 0x01 = WakeUp or 0x00 = Hibernate \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"]",
"is the same for EC and PH OEM circuit :return: int 0x00 =",
"\"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"] byte_array = int(round(t * 100)).to_bytes(4, \"big\") if",
"to hexa string: %s\" % hexstr) print(\"float from hexa: %.3f\" % float_from_hexa) return",
"int the firmware revision \"\"\" if \"EC\" == self.moduletype or \"PH\" == self.moduletype:",
"\"big\") if self.debug: print(\"Temperature to set: %.2f\" % t) print( \"%s sent converted",
"from OEM\", r) print(\"Who is calibrated? >\", binary_calib_status[r]) return binary_calib_status[r] def get_led(self) ->",
"self.write(register, 0x01) # send 0x01 to clear calibration data time.sleep(self.short_timeout) # wait before",
"hex(confirm): print(\"Calibration applied\") else: raise Exception(\"Cannot confirm the operation was correctly executed\") #",
"print( \"%s: %s%s\" % ( self.moduletype, value, \"µs\" if \"EC\" == self.moduletype else",
"self._convert_raw_hex_to_float(rawhex) / 100 elif \"PH\" == self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_ph_msb\"], self.FOUR_BYTE_READ, )",
"status is currently: %s\" % hex(led_status)) return led_status def get_wakeup_sleep_mode(self) -> int: \"\"\"",
") def set_wakeup_sleep_mode(self, action=0x01): \"\"\"change device mode to Active or Hibernate register is",
"self.debug: print( \"Led status change to: %s\" % (\"On\" if hex(0x01) == hex(state)",
"0x01 = WakeUp or 0x00 = Hibernate \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] self.write(register, action)",
"device_type = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.ONE_BYTE_READ, ) if self.debug: print(\"Device type is: %s\" %",
"register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self._set_calibration_registers(value) time.sleep(self.long_timeout) self.write(register, points[point]) # apply point calibration data time.sleep(self.short_timeout)",
"raise NotImplementedError(\"write workflow to change physical i2c address\") def set_led(self, state=0x01): \"\"\"Change Led",
"operation was correctly executed\") # ----- Getters ----- ######## def get_device_info(self): \"\"\" Get",
"sent converted value to bytes: \" % (self.moduletype), byte_array, ) def set_calibration_apply(self, value,",
"Hibernate register is the same for EC and PH OEM circuit :param byte:",
"EC and PH OEM circuit :return: int 0x01 = WakeUp or 0x00 =",
"µSiemens byte_array = int(round(value * 100)).to_bytes(4, \"big\") elif \"PH\" == self.moduletype: register =",
"send: %.2f\" % value) print( \"%s sent converted value to bytes: \" %",
"register is the same for EC and PH OEM circuit :param byte: action",
"\"high\": 0x05} register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype: points = {\"low\": 0x02,",
"def _set_calibration_registers(self, value): \"\"\"calibration registers do not use alone because calibration is apply",
"temperature @return float temperature value \"\"\" if \"EC\" == self.moduletype: rawhex = self.read(",
"self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.ONE_BYTE_READ, ) if self.debug: print(\"Device type is: %s\" % device_type) return",
"type is: %s\" % firmware) return firmware def get_new_read_available(self): \"\"\" New Read is",
"register = self.OEM_EC_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"dry\": 0, - \"single\": 1, - \"low\":",
"register = self.OEM_PH_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"low\": 1, - \"mid\": 2, - \"high\":",
"\"\"\" write workflow to change physical i2c address \"\"\" self.address(addr) raise NotImplementedError(\"write workflow",
"print(\"Led status is currently: %s\" % hex(led_status)) return led_status def get_wakeup_sleep_mode(self) -> int:",
"=> 0x01 = ON or 0x00 = OFF \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] self.write(register,",
"set: %.2f\" % t) print( \"%s sent converted temp to bytes: \" %",
"get_led(self) -> int: \"\"\" Get led state register is the same for EC",
"float for pH/! \"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_msb\"] # ec",
"% device_type) return device_type def get_firmware(self): \"\"\" Read sensor firmware @return int the",
"= self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self.write(register, 0x01) # send",
"confirmation conf = self.read(register) self._check_calibration_confirm(conf) return conf def set_i2c_addr(self, addr): \"\"\"Change the device",
"before read time.sleep(self._long_timeout) if \"EC\" == self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_ec_msb\"], self.FOUR_BYTE_READ, )",
"= > 1413.0 :param point: string \"dry\", \"single\", \"low\", \"mid\", \"high\" only \"\"\"",
"self._convert_raw_hex_to_float(rawhex) / 1000 if self.debug: print( \"%s: %s%s\" % ( self.moduletype, value, \"µs\"",
"addr): \"\"\"Change the device i2c address :param addr: int = new i2c add",
"is currently in mode: %s\" % (\"wakeup\" if hex(0x01) == hex(mode) else \"sleep\")",
"1 if new read available, 0 if not \"\"\" is_new_read = self.read( self.OEM_EC_REGISTERS[\"device_new_reading\"],",
"self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 100 if self.debug: print(\"%s compensation Temperature:",
"byte_array) print(\"Byte Array decoded to hexa string: %s\" % hexstr) print(\"float from hexa:",
"0x00 = OFF \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] self.write(register, state) if self.debug: print( \"Led",
"self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_ph_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 1000 if",
"address expected, convert hexa by using \\ AtlasI2c.ADDR_OEM_DECIMAL or AtlasI2c.ADDR_EZO_DECIMAL\" ) else: \"\"\"",
"\" % (self.moduletype), byte_array, ) def set_calibration_apply(self, value, point=\"\"): \"\"\"apply the calibration :param",
"applied\") else: raise Exception(\"Cannot confirm the operation was correctly executed\") # ----- Getters",
"self.set_wakeup_sleep_mode(0x00) # sleep device after set temperature def _set_calibration_registers(self, value): \"\"\"calibration registers do",
"wake device before read time.sleep(self._long_timeout) if \"EC\" == self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_ec_msb\"],",
"Array to decode: \", byte_array) print(\"Byte Array decoded to hexa string: %s\" %",
"\"single\": 1, - \"low\": 2, - \"high\": 3, \"\"\" binary_calib_status = self.EC_BINARY_CALIB_STATUS elif",
"self.debug: print(\"Device type is: %s\" % device_type) return device_type def get_firmware(self): \"\"\" Read",
"print(\"Device type is: %s\" % device_type) return device_type def get_firmware(self): \"\"\" Read sensor",
"firmware @return int the firmware revision \"\"\" if \"EC\" == self.moduletype or \"PH\"",
"result return float converted value \"\"\" hexstr = byte_array.hex() float_from_hexa = float.fromhex(byte_array.hex()) converted",
"= self.OEM_PH_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"low\": 1, - \"mid\": 2, - \"high\": 3,",
"current calibrations data :return: string with current points calibrated :rtype: \"\"\" if \"EC\"",
"float converted value \"\"\" hexstr = byte_array.hex() float_from_hexa = float.fromhex(byte_array.hex()) converted = float_from_hexa",
"(self.moduletype, value)) return value def get_calibration(self): \"\"\" Get current calibrations data :return: string",
"self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.TWO_BYTE_READ, ) return \"SUCCESS: %s, module type: %s and firmware is:",
"for EC and PH OEM circuit :return: int 0x00 = OFF or 0x01",
"status change to: %s\" % (\"On\" if hex(0x01) == hex(state) else \"OFF\") )",
"Read sensor type @return int the sensor type (1=EC, 4=PH) \"\"\" if \"EC\"",
"address\") def set_led(self, state=0x01): \"\"\"Change Led state :param state: byte state => 0x01",
"ec calibration wait for µSiemens byte_array = int(round(value * 100)).to_bytes(4, \"big\") elif \"PH\"",
"return \"SUCCESS: %s, module type: %s and firmware is: %s\" % ( self.moduletype,",
"the calibration :param value: float solution calibration value converted in float. EC waiting",
"action=0x01): \"\"\"change device mode to Active or Hibernate register is the same for",
"self.ADDR_OEM_HEXA and addr not in self.ADDR_OEM_DECIMAL: raise Exception( \"only decimal address expected, convert",
"firmware version \"\"\" if \"EC\" == self.moduletype or \"PH\" == self.moduletype: info =",
"\"\"\" Read sensor value @return float the sensor value \"\"\" # self.set_wakeup_sleep_mode(0x01) #",
"for EC/! /! in float for pH/! \"\"\" if \"EC\" == self.moduletype: register",
"converted value to bytes: \" % (self.moduletype), byte_array, ) def set_calibration_apply(self, value, point=\"\"):",
"if self.debug: print( \"Device is now: %s\" % (\"wakeup\" if hex(0x01) == hex(action)",
"if \"EC\" == self.moduletype else \"\", ) ) # self.set_wakeup_sleep_mode(0x00) # sleep device",
"self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 100 elif \"PH\" == self.moduletype: rawhex =",
"# ----- Getters ----- ######## def get_device_info(self): \"\"\" Get device information @return string",
"\"single\", \"low\", \"mid\", \"high\" only \"\"\" if point not in (\"dry\", \"single\", \"low\",",
"\"single\": 0x03, \"low\": 0x04, \"high\": 0x05} register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype:",
"Get current compensation temperature @return float temperature value \"\"\" if \"EC\" == self.moduletype:",
"\"%s sent converted value to bytes: \" % (self.moduletype), byte_array, ) def set_calibration_apply(self,",
") value = self._convert_raw_hex_to_float(rawhex) / 1000 if self.debug: print( \"%s: %s%s\" % (",
"for EC and PH OEM circuits \"\"\" def _convert_raw_hex_to_float(self, byte_array): \"\"\" convert bytearray",
"bits - \"low\": 1, - \"mid\": 2, - \"high\": 3, \"\"\" binary_calib_status =",
"points = {\"low\": 0x02, \"mid\": 0x03, \"high\": 0x04} register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self._set_calibration_registers(value) time.sleep(self.long_timeout)",
"EC waiting for µS e.g. 1.413 = > 1413.0 :param point: string \"dry\",",
"self.read( self.OEM_EC_REGISTERS[\"device_ec_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 100 elif \"PH\" == self.moduletype:",
"ack) if self.debug: print(\"ack new reading available register %s to %s\" % (register,",
"= self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype: points = {\"low\": 0x02, \"mid\": 0x03, \"high\":",
"AtlasI2c.ADDR_EZO_DECIMAL\" ) else: \"\"\" write workflow to change physical i2c address \"\"\" self.address(addr)",
"device_type) return device_type def get_firmware(self): \"\"\" Read sensor firmware @return int the firmware",
"\"big\") elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_msb\"] byte_array = int(round(value * 1000)).to_bytes(4,",
"int(round(t * 100)).to_bytes(4, \"big\") if self.debug: print(\"Temperature to set: %.2f\" % t) print(",
"\"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_msb\"] # ec calibration wait for",
"% ( self.moduletype, value, \"µs\" if \"EC\" == self.moduletype else \"\", ) )",
"version \"\"\" if \"EC\" == self.moduletype or \"PH\" == self.moduletype: info = self.read(",
"rawhex = self.read( self.OEM_PH_REGISTERS[\"device_ph_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 1000 if self.debug:",
":param t: float temperature value \"\"\" self.set_wakeup_sleep_mode(0x01) # wake device before set temperature",
"self.moduletype else \"\", ) ) # self.set_wakeup_sleep_mode(0x00) # sleep device after read return",
"correctly executed\") # ----- Getters ----- ######## def get_device_info(self): \"\"\" Get device information",
"self.OEM_EC_REGISTERS[\"device_sleep\"] self.write(register, action) if self.debug: print( \"Device is now: %s\" % (\"wakeup\" if",
"\"mid\": 0x03, \"high\": 0x04} register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self._set_calibration_registers(value) time.sleep(self.long_timeout) self.write(register, points[point]) # apply",
"available, 0 if not \"\"\" is_new_read = self.read( self.OEM_EC_REGISTERS[\"device_new_reading\"], self.ONE_BYTE_READ, ) return is_new_read",
"%.2f\" % t) print( \"%s sent converted temp to bytes: \" % (self.moduletype),",
"if \"EC\" == self.moduletype or \"PH\" == self.moduletype: device_type = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.ONE_BYTE_READ,",
"before set temperature time.sleep(self._long_timeout) if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"] elif \"PH\"",
"\"\"\" hexstr = byte_array.hex() float_from_hexa = float.fromhex(byte_array.hex()) converted = float_from_hexa if self.debug: print(\"Byte",
"float_from_hexa = float.fromhex(byte_array.hex()) converted = float_from_hexa if self.debug: print(\"Byte Array to decode: \",",
"now: %s\" % (\"wakeup\" if hex(0x01) == hex(action) else \"sleep\") ) def set_ack_new_read_available(self):",
"== self.moduletype: points = {\"low\": 0x02, \"mid\": 0x03, \"high\": 0x04} register = self.OEM_PH_REGISTERS[\"device_calibration_request\"]",
"\"\"\" register = self.OEM_EC_REGISTERS[\"device_new_reading\"] ack = 0x00 self.write(register, ack) if self.debug: print(\"ack new",
"get confirmation conf = self.read(register) self._check_calibration_confirm(conf) return conf def set_calibration_clear(self): \"\"\"clear calibration data",
"is available @return int 1 if new read available, 0 if not \"\"\"",
"t=25.0): \"\"\"Set the compensation temperature :param t: float temperature value \"\"\" self.set_wakeup_sleep_mode(0x01) #",
"NotImplementedError(\"write workflow to change physical i2c address\") def set_led(self, state=0x01): \"\"\"Change Led state",
"point: string \"dry\", \"single\", \"low\", \"mid\", \"high\" only \"\"\" if point not in",
"int 0x00 = OFF or 0x01 = ON :rtype: int \"\"\" register =",
"because calibration is apply by using set_calibration_apply /!in float micro siemens µS for",
"self.moduletype or \"PH\" == self.moduletype: info = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.TWO_BYTE_READ, ) return \"SUCCESS:",
"is apply by using set_calibration_apply /!in float micro siemens µS for EC/! /!",
"0x05} register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype: points = {\"low\": 0x02, \"mid\":",
"self.OEM_EC_REGISTERS[\"device_new_reading\"] ack = 0x00 self.write(register, ack) if self.debug: print(\"ack new reading available register",
"read time.sleep(self._long_timeout) if \"EC\" == self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_ec_msb\"], self.FOUR_BYTE_READ, ) value",
"Exception(\"Cannot confirm the operation was correctly executed\") # ----- Getters ----- ######## def",
"result from OEM\", r) print(\"Who is calibrated? >\", binary_calib_status[r]) return binary_calib_status[r] def get_led(self)",
"hex(action) else \"sleep\") ) def set_ack_new_read_available(self): \"\"\"Ack new Read available \"\"\" register =",
"/ 100 if self.debug: print(\"%s compensation Temperature: %s°c\" % (self.moduletype, value)) return value",
"circuit :return: int 0x00 = OFF or 0x01 = ON :rtype: int \"\"\"",
"after read return value def get_temperature(self): \"\"\" Get current compensation temperature @return float",
"state=0x01): \"\"\"Change Led state :param state: byte state => 0x01 = ON or",
") value = self._convert_raw_hex_to_float(rawhex) / 100 elif \"PH\" == self.moduletype: rawhex = self.read(",
"\"high\" only \"\"\" if point not in (\"dry\", \"single\", \"low\", \"mid\", \"high\"): raise",
"self.read( self.OEM_EC_REGISTERS[\"device_new_reading\"], self.ONE_BYTE_READ, ) return is_new_read def get_read(self): \"\"\" Read sensor value @return",
"device after read return value def get_temperature(self): \"\"\" Get current compensation temperature @return",
"self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"low\": 1, - \"mid\": 2, -",
"Get led state register is the same for EC and PH OEM circuit",
"self.OEM_PH_REGISTERS[\"device_calibration_request\"] self._set_calibration_registers(value) time.sleep(self.long_timeout) self.write(register, points[point]) # apply point calibration data time.sleep(self.short_timeout) # wait",
"\"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_msb\"] # ec calibration wait for µSiemens byte_array",
"self.OEM_EC_REGISTERS[\"device_type\"], self.ONE_BYTE_READ, ) if self.debug: print(\"Device type is: %s\" % device_type) return device_type",
"self.read(register) if self.debug: print(\"Led status is currently: %s\" % hex(led_status)) return led_status def",
"% hexstr) print(\"float from hexa: %.3f\" % float_from_hexa) return converted def _check_calibration_confirm(self, confirm):",
"current points calibrated :rtype: \"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_confirm\"] \"\"\"",
"byte_array) if self.debug: print(\"Value to send: %.2f\" % value) print( \"%s sent converted",
"\"\"\" check the response of calibration confirm register \"\"\" if self.debug: if hex(0x00)",
"is based on Atlas Scientific documentations: https://www.atlas-scientific.com/files/EC_oem_datasheet.pdf https://atlas-scientific.com/files/oem_pH_datasheet.pdf \"\"\" import time from GreenPonik_Atlas_Scientific_OEM_i2c.AtlasOEMI2c",
"type: %s and firmware is: %s\" % ( self.moduletype, info[0], info[1], ) def",
"set_wakeup_sleep_mode(self, action=0x01): \"\"\"change device mode to Active or Hibernate register is the same",
"\"%s: %s%s\" % ( self.moduletype, value, \"µs\" if \"EC\" == self.moduletype else \"\",",
"solution calibration value converted in float. EC waiting for µS e.g. 1.413 =",
"calibration data \"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" ==",
"sensor value \"\"\" # self.set_wakeup_sleep_mode(0x01) # wake device before read time.sleep(self._long_timeout) if \"EC\"",
"self.debug: print(\"Value to send: %.2f\" % value) print( \"%s sent converted value to",
"be \"dry\", \"single\", \"low\", \"mid\", \"high\"' ) if \"EC\" == self.moduletype: points =",
"self.debug: print(\"Byte Array to decode: \", byte_array) print(\"Byte Array decoded to hexa string:",
"\"PH\" == self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_ph_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) /",
"byte_array.hex() float_from_hexa = float.fromhex(byte_array.hex()) converted = float_from_hexa if self.debug: print(\"Byte Array to decode:",
"\"\"\" self.address(addr) raise NotImplementedError(\"write workflow to change physical i2c address\") def set_led(self, state=0x01):",
"def set_i2c_addr(self, addr): \"\"\"Change the device i2c address :param addr: int = new",
"byte_array) self.set_wakeup_sleep_mode(0x00) # sleep device after set temperature def _set_calibration_registers(self, value): \"\"\"calibration registers",
"self.set_wakeup_sleep_mode(0x00) # sleep device after read return value def get_temperature(self): \"\"\" Get current",
"executed\") # ----- Getters ----- ######## def get_device_info(self): \"\"\" Get device information @return",
"import time from GreenPonik_Atlas_Scientific_OEM_i2c.AtlasOEMI2c import _AtlasOEMI2c class _CommonsI2c(_AtlasOEMI2c): \"\"\" commons methods for EC",
"def get_firmware(self): \"\"\" Read sensor firmware @return int the firmware revision \"\"\" if",
"int \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] led_status = self.read(register) if self.debug: print(\"Led status is",
"is the same for EC and PH OEM circuit :param byte: action =>",
"(self.moduletype), byte_array, ) time.sleep(self.short_timeout) self.write(register, byte_array) self.set_wakeup_sleep_mode(0x00) # sleep device after set temperature",
"self.write(register, ack) if self.debug: print(\"ack new reading available register %s to %s\" %",
"value = self._convert_raw_hex_to_float(rawhex) / 1000 if self.debug: print( \"%s: %s%s\" % ( self.moduletype,",
"wait for µSiemens byte_array = int(round(value * 100)).to_bytes(4, \"big\") elif \"PH\" == self.moduletype:",
"0x03, \"low\": 0x04, \"high\": 0x05} register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype: points",
"register = self.OEM_EC_REGISTERS[\"device_calibration_msb\"] # ec calibration wait for µSiemens byte_array = int(round(value *",
"\"EC\" == self.moduletype or \"PH\" == self.moduletype: info = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.TWO_BYTE_READ, )",
"def get_new_read_available(self): \"\"\" New Read is available @return int 1 if new read",
"r = self.read(register) if self.debug: print(\"Binary result from OEM\", r) print(\"Who is calibrated?",
"# apply point calibration data time.sleep(self.short_timeout) # wait before read register to get",
"address \"\"\" self.address(addr) raise NotImplementedError(\"write workflow to change physical i2c address\") def set_led(self,",
"converted def _check_calibration_confirm(self, confirm): \"\"\" check the response of calibration confirm register \"\"\"",
"= self.OEM_EC_REGISTERS[\"device_sleep\"] self.write(register, action) if self.debug: print( \"Device is now: %s\" % (\"wakeup\"",
"%s\" % (\"On\" if hex(0x01) == hex(state) else \"OFF\") ) def set_wakeup_sleep_mode(self, action=0x01):",
"temperature value \"\"\" self.set_wakeup_sleep_mode(0x01) # wake device before set temperature time.sleep(self._long_timeout) if \"EC\"",
"{\"dry\": 0x02, \"single\": 0x03, \"low\": 0x04, \"high\": 0x05} register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\"",
"addr: int = new i2c add \"\"\" if addr not in self.ADDR_OEM_HEXA and",
"= ON or 0x00 = OFF \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] self.write(register, state) if",
"- \"high\": 3, \"\"\" binary_calib_status = self.PH_BINARY_CALIB_STATUS r = self.read(register) if self.debug: print(\"Binary",
"Read is available @return int 1 if new read available, 0 if not",
"= self.read(register) self._check_calibration_confirm(conf) return conf def set_i2c_addr(self, addr): \"\"\"Change the device i2c address",
"to decode: \", byte_array) print(\"Byte Array decoded to hexa string: %s\" % hexstr)",
":return: string with current points calibrated :rtype: \"\"\" if \"EC\" == self.moduletype: register",
"= int(round(value * 100)).to_bytes(4, \"big\") elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_msb\"] byte_array",
"%s\" % hexstr) print(\"float from hexa: %.3f\" % float_from_hexa) return converted def _check_calibration_confirm(self,",
"self.set_wakeup_sleep_mode(0x01) # wake device before set temperature time.sleep(self._long_timeout) if \"EC\" == self.moduletype: register",
"time.sleep(self.long_timeout) self.write(register, points[point]) # apply point calibration data time.sleep(self.short_timeout) # wait before read",
"converted = float_from_hexa if self.debug: print(\"Byte Array to decode: \", byte_array) print(\"Byte Array",
"1, - \"low\": 2, - \"high\": 3, \"\"\" binary_calib_status = self.EC_BINARY_CALIB_STATUS elif \"PH\"",
"and addr not in self.ADDR_OEM_DECIMAL: raise Exception( \"only decimal address expected, convert hexa",
"not use alone because calibration is apply by using set_calibration_apply /!in float micro",
"converted temp to bytes: \" % (self.moduletype), byte_array, ) time.sleep(self.short_timeout) self.write(register, byte_array) self.set_wakeup_sleep_mode(0x00)",
"0x01) # send 0x01 to clear calibration data time.sleep(self.short_timeout) # wait before read",
"self.moduletype: register = self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"] elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"] byte_array =",
"# send 0x01 to clear calibration data time.sleep(self.short_timeout) # wait before read register",
"\"\"\" import time from GreenPonik_Atlas_Scientific_OEM_i2c.AtlasOEMI2c import _AtlasOEMI2c class _CommonsI2c(_AtlasOEMI2c): \"\"\" commons methods for",
"self.FOUR_BYTE_READ, ) elif \"PH\" == self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) value",
"bits - \"dry\": 0, - \"single\": 1, - \"low\": 2, - \"high\": 3,",
"value \"\"\" hexstr = byte_array.hex() float_from_hexa = float.fromhex(byte_array.hex()) converted = float_from_hexa if self.debug:",
"circuit :return: int 0x01 = WakeUp or 0x00 = Hibernate :rtype: int \"\"\"",
":return: int 0x00 = OFF or 0x01 = ON :rtype: int \"\"\" register",
"set_temperature(self, t=25.0): \"\"\"Set the compensation temperature :param t: float temperature value \"\"\" self.set_wakeup_sleep_mode(0x01)",
"in self.ADDR_OEM_HEXA and addr not in self.ADDR_OEM_DECIMAL: raise Exception( \"only decimal address expected,",
"hex(mode) else \"sleep\") ) return mode # ----- Setters ----- ######## def set_temperature(self,",
"time.sleep(self._long_timeout) if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"] elif \"PH\" == self.moduletype: register",
"1000)).to_bytes(4, \"big\") self.write(register, byte_array) if self.debug: print(\"Value to send: %.2f\" % value) print(",
"in float. EC waiting for µS e.g. 1.413 = > 1413.0 :param point:",
"sensor value @return float the sensor value \"\"\" # self.set_wakeup_sleep_mode(0x01) # wake device",
"if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype: register =",
"value): \"\"\"calibration registers do not use alone because calibration is apply by using",
"\"Device is now: %s\" % (\"wakeup\" if hex(0x01) == hex(action) else \"sleep\") )",
"register = self.OEM_EC_REGISTERS[\"device_sleep\"] mode = self.read(register) if self.debug: print( \"Device is currently in",
"self.OEM_EC_REGISTERS[\"device_led\"] self.write(register, state) if self.debug: print( \"Led status change to: %s\" % (\"On\"",
"\"\"\" def _convert_raw_hex_to_float(self, byte_array): \"\"\" convert bytearray response to float result return float",
"\"\"\" self.set_wakeup_sleep_mode(0x01) # wake device before set temperature time.sleep(self._long_timeout) if \"EC\" == self.moduletype:",
"register = self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"] byte_array = int(round(t * 100)).to_bytes(4, \"big\") if self.debug: print(\"Temperature to",
"self.read(register) if self.debug: print(\"Binary result from OEM\", r) print(\"Who is calibrated? >\", binary_calib_status[r])",
"Atlas Scientific documentations: https://www.atlas-scientific.com/files/EC_oem_datasheet.pdf https://atlas-scientific.com/files/oem_pH_datasheet.pdf \"\"\" import time from GreenPonik_Atlas_Scientific_OEM_i2c.AtlasOEMI2c import _AtlasOEMI2c class",
"rawhex = self.read( self.OEM_EC_REGISTERS[\"device_ec_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 100 elif \"PH\"",
"get_device_info(self): \"\"\" Get device information @return string module type, firmware version \"\"\" if",
"self.debug: print( \"Device is now: %s\" % (\"wakeup\" if hex(0x01) == hex(action) else",
"%s, module type: %s and firmware is: %s\" % ( self.moduletype, info[0], info[1],",
"% float_from_hexa) return converted def _check_calibration_confirm(self, confirm): \"\"\" check the response of calibration",
"% (\"wakeup\" if hex(0x01) == hex(action) else \"sleep\") ) def set_ack_new_read_available(self): \"\"\"Ack new",
"self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_msb\"] byte_array = int(round(value * 1000)).to_bytes(4, \"big\") self.write(register, byte_array) if",
"=> 0x01 = WakeUp or 0x00 = Hibernate \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] self.write(register,",
"byte: action => 0x01 = WakeUp or 0x00 = Hibernate \"\"\" register =",
"workflow to change physical i2c address \"\"\" self.address(addr) raise NotImplementedError(\"write workflow to change",
"available \"\"\" register = self.OEM_EC_REGISTERS[\"device_new_reading\"] ack = 0x00 self.write(register, ack) if self.debug: print(\"ack",
"= self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.ONE_BYTE_READ, ) if self.debug: print(\"Device type is: %s\" % device_type)",
"int 1 if new read available, 0 if not \"\"\" is_new_read = self.read(",
"device mode register is the same for EC and PH OEM circuit :return:",
"data \"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype:",
"was correctly executed\") # ----- Getters ----- ######## def get_device_info(self): \"\"\" Get device",
"= self.read(register) if self.debug: print(\"Led status is currently: %s\" % hex(led_status)) return led_status",
"= int(round(value * 1000)).to_bytes(4, \"big\") self.write(register, byte_array) if self.debug: print(\"Value to send: %.2f\"",
"the compensation temperature :param t: float temperature value \"\"\" self.set_wakeup_sleep_mode(0x01) # wake device",
"alone because calibration is apply by using set_calibration_apply /!in float micro siemens µS",
"print(\"Calibration applied\") else: raise Exception(\"Cannot confirm the operation was correctly executed\") # -----",
"circuit :param byte: action => 0x01 = WakeUp or 0x00 = Hibernate \"\"\"",
"Atlas Scientific OEM sensors in I2C mode. Atlas Scientific i2c by GreenPonik Source",
"\"\"\" if \"EC\" == self.moduletype or \"PH\" == self.moduletype: device_type = self.read( self.OEM_EC_REGISTERS[\"device_type\"],",
"= self.OEM_EC_REGISTERS[\"device_sleep\"] mode = self.read(register) if self.debug: print( \"Device is currently in mode:",
"\"\"\" Get device information @return string module type, firmware version \"\"\" if \"EC\"",
"available @return int 1 if new read available, 0 if not \"\"\" is_new_read",
"time.sleep(self.short_timeout) self.write(register, byte_array) self.set_wakeup_sleep_mode(0x00) # sleep device after set temperature def _set_calibration_registers(self, value):",
"firmware is: %s\" % ( self.moduletype, info[0], info[1], ) def get_type(self): \"\"\" Read",
"\"low\", \"mid\", \"high\"' ) if \"EC\" == self.moduletype: points = {\"dry\": 0x02, \"single\":",
"def set_led(self, state=0x01): \"\"\"Change Led state :param state: byte state => 0x01 =",
"clear calibration data time.sleep(self.short_timeout) # wait before read register to get confirmation conf",
"elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"] byte_array = int(round(t * 100)).to_bytes(4, \"big\")",
"waiting for µS e.g. 1.413 = > 1413.0 :param point: string \"dry\", \"single\",",
"temperature time.sleep(self._long_timeout) if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"] elif \"PH\" == self.moduletype:",
"@return float temperature value \"\"\" if \"EC\" == self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"],",
"value \"\"\" if \"EC\" == self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) elif",
"if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"dry\": 0, -",
"= Hibernate :rtype: int \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] mode = self.read(register) if self.debug:",
"== self.moduletype: register = self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"] elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"] byte_array",
"calibration wait for µSiemens byte_array = int(round(value * 100)).to_bytes(4, \"big\") elif \"PH\" ==",
"get confirmation conf = self.read(register) self._check_calibration_confirm(conf) return conf def set_i2c_addr(self, addr): \"\"\"Change the",
"of calibration confirm register \"\"\" if self.debug: if hex(0x00) == hex(confirm): print(\"Calibration applied\")",
":param state: byte state => 0x01 = ON or 0x00 = OFF \"\"\"",
"or 0x00 = OFF \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] self.write(register, state) if self.debug: print(",
"get_read(self): \"\"\" Read sensor value @return float the sensor value \"\"\" # self.set_wakeup_sleep_mode(0x01)",
"0x00 self.write(register, ack) if self.debug: print(\"ack new reading available register %s to %s\"",
"int the sensor type (1=EC, 4=PH) \"\"\" if \"EC\" == self.moduletype or \"PH\"",
"- \"low\": 1, - \"mid\": 2, - \"high\": 3, \"\"\" binary_calib_status = self.PH_BINARY_CALIB_STATUS",
"self.OEM_PH_REGISTERS[\"device_calibration_msb\"] byte_array = int(round(value * 1000)).to_bytes(4, \"big\") self.write(register, byte_array) if self.debug: print(\"Value to",
"######## def get_device_info(self): \"\"\" Get device information @return string module type, firmware version",
"check the response of calibration confirm register \"\"\" if self.debug: if hex(0x00) ==",
"Setters ----- ######## def set_temperature(self, t=25.0): \"\"\"Set the compensation temperature :param t: float",
"@return float the sensor value \"\"\" # self.set_wakeup_sleep_mode(0x01) # wake device before read",
"hex(0x01) == hex(action) else \"sleep\") ) def set_ack_new_read_available(self): \"\"\"Ack new Read available \"\"\"",
"\"\"\"Ack new Read available \"\"\" register = self.OEM_EC_REGISTERS[\"device_new_reading\"] ack = 0x00 self.write(register, ack)",
"@return int the sensor type (1=EC, 4=PH) \"\"\" if \"EC\" == self.moduletype or",
"self.write(register, state) if self.debug: print( \"Led status change to: %s\" % (\"On\" if",
"set_ack_new_read_available(self): \"\"\"Ack new Read available \"\"\" register = self.OEM_EC_REGISTERS[\"device_new_reading\"] ack = 0x00 self.write(register,",
"PH OEM circuits \"\"\" def _convert_raw_hex_to_float(self, byte_array): \"\"\" convert bytearray response to float",
"= float.fromhex(byte_array.hex()) converted = float_from_hexa if self.debug: print(\"Byte Array to decode: \", byte_array)",
"# wake device before read time.sleep(self._long_timeout) if \"EC\" == self.moduletype: rawhex = self.read(",
"self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 100 if",
"\"sleep\") ) return mode # ----- Setters ----- ######## def set_temperature(self, t=25.0): \"\"\"Set",
"= ON :rtype: int \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] led_status = self.read(register) if self.debug:",
"= int(round(t * 100)).to_bytes(4, \"big\") if self.debug: print(\"Temperature to set: %.2f\" % t)",
"\"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_request\"]",
"self.moduletype: points = {\"dry\": 0x02, \"single\": 0x03, \"low\": 0x04, \"high\": 0x05} register =",
"0x00 = Hibernate \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] self.write(register, action) if self.debug: print( \"Device",
"the sensor value \"\"\" # self.set_wakeup_sleep_mode(0x01) # wake device before read time.sleep(self._long_timeout) if",
"led_status def get_wakeup_sleep_mode(self) -> int: \"\"\" get Active or Hibernate device mode register",
"set_i2c_addr(self, addr): \"\"\"Change the device i2c address :param addr: int = new i2c",
"revision \"\"\" if \"EC\" == self.moduletype or \"PH\" == self.moduletype: firmware = self.read(",
"'missing string point argument, \\ can only be \"dry\", \"single\", \"low\", \"mid\", \"high\"'",
"elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_msb\"] byte_array = int(round(value * 1000)).to_bytes(4, \"big\")",
"_set_calibration_registers(self, value): \"\"\"calibration registers do not use alone because calibration is apply by",
"AtlasI2c.ADDR_OEM_DECIMAL or AtlasI2c.ADDR_EZO_DECIMAL\" ) else: \"\"\" write workflow to change physical i2c address",
"register = self.OEM_EC_REGISTERS[\"device_sleep\"] self.write(register, action) if self.debug: print( \"Device is now: %s\" %",
"address :param addr: int = new i2c add \"\"\" if addr not in",
"compensation temperature @return float temperature value \"\"\" if \"EC\" == self.moduletype: rawhex =",
"register = self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"] elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"] byte_array = int(round(t",
"self.moduletype: register = self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"] byte_array = int(round(t * 100)).to_bytes(4, \"big\") if self.debug: print(\"Temperature",
"% (\"wakeup\" if hex(0x01) == hex(mode) else \"sleep\") ) return mode # -----",
"or 0x01 = ON :rtype: int \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] led_status = self.read(register)",
"expected, convert hexa by using \\ AtlasI2c.ADDR_OEM_DECIMAL or AtlasI2c.ADDR_EZO_DECIMAL\" ) else: \"\"\" write",
"%s\" % hex(led_status)) return led_status def get_wakeup_sleep_mode(self) -> int: \"\"\" get Active or",
"print(\"Byte Array decoded to hexa string: %s\" % hexstr) print(\"float from hexa: %.3f\"",
"i2c by GreenPonik Source code is based on Atlas Scientific documentations: https://www.atlas-scientific.com/files/EC_oem_datasheet.pdf https://atlas-scientific.com/files/oem_pH_datasheet.pdf",
"1.413 = > 1413.0 :param point: string \"dry\", \"single\", \"low\", \"mid\", \"high\" only",
"read register to get confirmation conf = self.read(register) self._check_calibration_confirm(conf) return conf def set_i2c_addr(self,",
"physical i2c address \"\"\" self.address(addr) raise NotImplementedError(\"write workflow to change physical i2c address\")",
"raise Exception( 'missing string point argument, \\ can only be \"dry\", \"single\", \"low\",",
"state) if self.debug: print( \"Led status change to: %s\" % (\"On\" if hex(0x01)",
"get_new_read_available(self): \"\"\" New Read is available @return int 1 if new read available,",
"to change physical i2c address\") def set_led(self, state=0x01): \"\"\"Change Led state :param state:",
"----- Setters ----- ######## def set_temperature(self, t=25.0): \"\"\"Set the compensation temperature :param t:",
"value, point=\"\"): \"\"\"apply the calibration :param value: float solution calibration value converted in",
"register = self.OEM_EC_REGISTERS[\"device_led\"] led_status = self.read(register) if self.debug: print(\"Led status is currently: %s\"",
"\"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"dry\": 0,",
"https://atlas-scientific.com/files/oem_pH_datasheet.pdf \"\"\" import time from GreenPonik_Atlas_Scientific_OEM_i2c.AtlasOEMI2c import _AtlasOEMI2c class _CommonsI2c(_AtlasOEMI2c): \"\"\" commons methods",
"get_firmware(self): \"\"\" Read sensor firmware @return int the firmware revision \"\"\" if \"EC\"",
"elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"low\": 1, -",
"self.debug: print(\"Binary result from OEM\", r) print(\"Who is calibrated? >\", binary_calib_status[r]) return binary_calib_status[r]",
"convert hexa by using \\ AtlasI2c.ADDR_OEM_DECIMAL or AtlasI2c.ADDR_EZO_DECIMAL\" ) else: \"\"\" write workflow",
"\"\"\"Change Led state :param state: byte state => 0x01 = ON or 0x00",
"self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self.write(register, 0x01)",
"def get_wakeup_sleep_mode(self) -> int: \"\"\" get Active or Hibernate device mode register is",
"register \"\"\" if self.debug: if hex(0x00) == hex(confirm): print(\"Calibration applied\") else: raise Exception(\"Cannot",
"value)) return value def get_calibration(self): \"\"\" Get current calibrations data :return: string with",
"temperature value \"\"\" if \"EC\" == self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, )",
"state register is the same for EC and PH OEM circuit :return: int",
"if point not in (\"dry\", \"single\", \"low\", \"mid\", \"high\"): raise Exception( 'missing string",
"or \"PH\" == self.moduletype: device_type = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.ONE_BYTE_READ, ) if self.debug: print(\"Device",
"self.read( self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) elif \"PH\" == self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ,",
"sleep device after read return value def get_temperature(self): \"\"\" Get current compensation temperature",
"# wait before read register to get confirmation conf = self.read(register) self._check_calibration_confirm(conf) return",
"self.ONE_BYTE_READ, ) if self.debug: print(\"Device type is: %s\" % device_type) return device_type def",
"mode: %s\" % (\"wakeup\" if hex(0x01) == hex(mode) else \"sleep\") ) return mode",
"(self.moduletype), byte_array, ) def set_calibration_apply(self, value, point=\"\"): \"\"\"apply the calibration :param value: float",
"self.debug: if hex(0x00) == hex(confirm): print(\"Calibration applied\") else: raise Exception(\"Cannot confirm the operation",
"send 0x01 to clear calibration data time.sleep(self.short_timeout) # wait before read register to",
"EC and PH OEM circuit :return: int 0x00 = OFF or 0x01 =",
"== self.moduletype or \"PH\" == self.moduletype: info = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.TWO_BYTE_READ, ) return",
"100 elif \"PH\" == self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_ph_msb\"], self.FOUR_BYTE_READ, ) value =",
"\"only decimal address expected, convert hexa by using \\ AtlasI2c.ADDR_OEM_DECIMAL or AtlasI2c.ADDR_EZO_DECIMAL\" )",
"self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"] byte_array = int(round(t * 100)).to_bytes(4, \"big\") if self.debug: print(\"Temperature to set: %.2f\"",
"is now: %s\" % (\"wakeup\" if hex(0x01) == hex(action) else \"sleep\") ) def",
"print(\"%s compensation Temperature: %s°c\" % (self.moduletype, value)) return value def get_calibration(self): \"\"\" Get",
"if self.debug: print( \"%s: %s%s\" % ( self.moduletype, value, \"µs\" if \"EC\" ==",
"\"low\", \"mid\", \"high\"): raise Exception( 'missing string point argument, \\ can only be",
"value, \"µs\" if \"EC\" == self.moduletype else \"\", ) ) # self.set_wakeup_sleep_mode(0x00) #",
"byte_array, ) def set_calibration_apply(self, value, point=\"\"): \"\"\"apply the calibration :param value: float solution",
"self.ONE_BYTE_READ, ) return is_new_read def get_read(self): \"\"\" Read sensor value @return float the",
"= self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.TWO_BYTE_READ, ) return \"SUCCESS: %s, module type: %s and firmware",
"binary_calib_status = self.PH_BINARY_CALIB_STATUS r = self.read(register) if self.debug: print(\"Binary result from OEM\", r)",
"%s\" % (\"wakeup\" if hex(0x01) == hex(mode) else \"sleep\") ) return mode #",
"self.OEM_EC_REGISTERS[\"device_sleep\"] mode = self.read(register) if self.debug: print( \"Device is currently in mode: %s\"",
") def set_calibration_apply(self, value, point=\"\"): \"\"\"apply the calibration :param value: float solution calibration",
"converted in float. EC waiting for µS e.g. 1.413 = > 1413.0 :param",
"confirm the operation was correctly executed\") # ----- Getters ----- ######## def get_device_info(self):",
"self.write(register, action) if self.debug: print( \"Device is now: %s\" % (\"wakeup\" if hex(0x01)",
"- \"dry\": 0, - \"single\": 1, - \"low\": 2, - \"high\": 3, \"\"\"",
"sensor type (1=EC, 4=PH) \"\"\" if \"EC\" == self.moduletype or \"PH\" == self.moduletype:",
"value converted in float. EC waiting for µS e.g. 1.413 = > 1413.0",
"1413.0 :param point: string \"dry\", \"single\", \"low\", \"mid\", \"high\" only \"\"\" if point",
"/!in float micro siemens µS for EC/! /! in float for pH/! \"\"\"",
"change physical i2c address\") def set_led(self, state=0x01): \"\"\"Change Led state :param state: byte",
"OFF \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] self.write(register, state) if self.debug: print( \"Led status change",
"#! /usr/bin/python3 \"\"\" Description ----------- Class to communicate with Atlas Scientific OEM sensors",
"if self.debug: print(\"ack new reading available register %s to %s\" % (register, ack))",
"\"big\") self.write(register, byte_array) if self.debug: print(\"Value to send: %.2f\" % value) print( \"%s",
"value def get_calibration(self): \"\"\" Get current calibrations data :return: string with current points",
"0x04, \"high\": 0x05} register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" == self.moduletype: points = {\"low\":",
"device before set temperature time.sleep(self._long_timeout) if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"] elif",
"print(\"Value to send: %.2f\" % value) print( \"%s sent converted value to bytes:",
"else \"sleep\") ) def set_ack_new_read_available(self): \"\"\"Ack new Read available \"\"\" register = self.OEM_EC_REGISTERS[\"device_new_reading\"]",
"= self.read( self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) elif \"PH\" == self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"],",
"print(\"Who is calibrated? >\", binary_calib_status[r]) return binary_calib_status[r] def get_led(self) -> int: \"\"\" Get",
"print(\"Binary result from OEM\", r) print(\"Who is calibrated? >\", binary_calib_status[r]) return binary_calib_status[r] def",
"def set_temperature(self, t=25.0): \"\"\"Set the compensation temperature :param t: float temperature value \"\"\"",
"device after set temperature def _set_calibration_registers(self, value): \"\"\"calibration registers do not use alone",
"if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"] elif \"PH\" == self.moduletype: register =",
"in mode: %s\" % (\"wakeup\" if hex(0x01) == hex(mode) else \"sleep\") ) return",
":param byte: action => 0x01 = WakeUp or 0x00 = Hibernate \"\"\" register",
"do not use alone because calibration is apply by using set_calibration_apply /!in float",
"return value def get_temperature(self): \"\"\" Get current compensation temperature @return float temperature value",
"\"high\"): raise Exception( 'missing string point argument, \\ can only be \"dry\", \"single\",",
"(\"On\" if hex(0x01) == hex(state) else \"OFF\") ) def set_wakeup_sleep_mode(self, action=0x01): \"\"\"change device",
"\"\"\"Change the device i2c address :param addr: int = new i2c add \"\"\"",
"µS e.g. 1.413 = > 1413.0 :param point: string \"dry\", \"single\", \"low\", \"mid\",",
"code is based on Atlas Scientific documentations: https://www.atlas-scientific.com/files/EC_oem_datasheet.pdf https://atlas-scientific.com/files/oem_pH_datasheet.pdf \"\"\" import time from",
"decimal address expected, convert hexa by using \\ AtlasI2c.ADDR_OEM_DECIMAL or AtlasI2c.ADDR_EZO_DECIMAL\" ) else:",
"using \\ AtlasI2c.ADDR_OEM_DECIMAL or AtlasI2c.ADDR_EZO_DECIMAL\" ) else: \"\"\" write workflow to change physical",
"hex(led_status)) return led_status def get_wakeup_sleep_mode(self) -> int: \"\"\" get Active or Hibernate device",
"wake device before set temperature time.sleep(self._long_timeout) if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"]",
"3, \"\"\" binary_calib_status = self.PH_BINARY_CALIB_STATUS r = self.read(register) if self.debug: print(\"Binary result from",
"if self.debug: print(\"%s compensation Temperature: %s°c\" % (self.moduletype, value)) return value def get_calibration(self):",
"EC and PH OEM circuits \"\"\" def _convert_raw_hex_to_float(self, byte_array): \"\"\" convert bytearray response",
"convert bytearray response to float result return float converted value \"\"\" hexstr =",
"bytes: \" % (self.moduletype), byte_array, ) def set_calibration_apply(self, value, point=\"\"): \"\"\"apply the calibration",
"== self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_ec_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 100",
"0 if not \"\"\" is_new_read = self.read( self.OEM_EC_REGISTERS[\"device_new_reading\"], self.ONE_BYTE_READ, ) return is_new_read def",
"float.fromhex(byte_array.hex()) converted = float_from_hexa if self.debug: print(\"Byte Array to decode: \", byte_array) print(\"Byte",
"workflow to change physical i2c address\") def set_led(self, state=0x01): \"\"\"Change Led state :param",
"== hex(confirm): print(\"Calibration applied\") else: raise Exception(\"Cannot confirm the operation was correctly executed\")",
") return is_new_read def get_read(self): \"\"\" Read sensor value @return float the sensor",
"to bytes: \" % (self.moduletype), byte_array, ) time.sleep(self.short_timeout) self.write(register, byte_array) self.set_wakeup_sleep_mode(0x00) # sleep",
"0x02, \"single\": 0x03, \"low\": 0x04, \"high\": 0x05} register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif \"PH\" ==",
"0x02, \"mid\": 0x03, \"high\": 0x04} register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self._set_calibration_registers(value) time.sleep(self.long_timeout) self.write(register, points[point]) #",
"(\"wakeup\" if hex(0x01) == hex(mode) else \"sleep\") ) return mode # ----- Setters",
"\"Device is currently in mode: %s\" % (\"wakeup\" if hex(0x01) == hex(mode) else",
"0x00 = Hibernate :rtype: int \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] mode = self.read(register) if",
"led state register is the same for EC and PH OEM circuit :return:",
") if self.debug: print(\"Firmware type is: %s\" % firmware) return firmware def get_new_read_available(self):",
"self.moduletype: register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self.write(register, 0x01) # send 0x01 to clear calibration data",
"Class to communicate with Atlas Scientific OEM sensors in I2C mode. Atlas Scientific",
"= self.read(register) if self.debug: print(\"Binary result from OEM\", r) print(\"Who is calibrated? >\",",
"\"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"dry\": 0, - \"single\":",
"print(\"Temperature to set: %.2f\" % t) print( \"%s sent converted temp to bytes:",
") if self.debug: print(\"Device type is: %s\" % device_type) return device_type def get_firmware(self):",
"self.moduletype: points = {\"low\": 0x02, \"mid\": 0x03, \"high\": 0x04} register = self.OEM_PH_REGISTERS[\"device_calibration_request\"] self._set_calibration_registers(value)",
"mode. Atlas Scientific i2c by GreenPonik Source code is based on Atlas Scientific",
"t) print( \"%s sent converted temp to bytes: \" % (self.moduletype), byte_array, )",
"\"µs\" if \"EC\" == self.moduletype else \"\", ) ) # self.set_wakeup_sleep_mode(0x00) # sleep",
"and PH OEM circuit :return: int 0x01 = WakeUp or 0x00 = Hibernate",
"if \"EC\" == self.moduletype: points = {\"dry\": 0x02, \"single\": 0x03, \"low\": 0x04, \"high\":",
"time.sleep(self._long_timeout) if \"EC\" == self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_ec_msb\"], self.FOUR_BYTE_READ, ) value =",
"\"\"\"change device mode to Active or Hibernate register is the same for EC",
"self.OEM_EC_REGISTERS[\"device_firmware\"], self.ONE_BYTE_READ, ) if self.debug: print(\"Firmware type is: %s\" % firmware) return firmware",
") ) # self.set_wakeup_sleep_mode(0x00) # sleep device after read return value def get_temperature(self):",
"by using \\ AtlasI2c.ADDR_OEM_DECIMAL or AtlasI2c.ADDR_EZO_DECIMAL\" ) else: \"\"\" write workflow to change",
"read available, 0 if not \"\"\" is_new_read = self.read( self.OEM_EC_REGISTERS[\"device_new_reading\"], self.ONE_BYTE_READ, ) return",
"self.set_wakeup_sleep_mode(0x01) # wake device before read time.sleep(self._long_timeout) if \"EC\" == self.moduletype: rawhex =",
"sent converted temp to bytes: \" % (self.moduletype), byte_array, ) time.sleep(self.short_timeout) self.write(register, byte_array)",
"module type: %s and firmware is: %s\" % ( self.moduletype, info[0], info[1], )",
"firmware) return firmware def get_new_read_available(self): \"\"\" New Read is available @return int 1",
"if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_msb\"] # ec calibration wait for µSiemens",
"== self.moduletype or \"PH\" == self.moduletype: device_type = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.ONE_BYTE_READ, ) if",
"= self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"] byte_array = int(round(t * 100)).to_bytes(4, \"big\") if self.debug: print(\"Temperature to set:",
"* 1000)).to_bytes(4, \"big\") self.write(register, byte_array) if self.debug: print(\"Value to send: %.2f\" % value)",
"from GreenPonik_Atlas_Scientific_OEM_i2c.AtlasOEMI2c import _AtlasOEMI2c class _CommonsI2c(_AtlasOEMI2c): \"\"\" commons methods for EC and PH",
"(\"dry\", \"single\", \"low\", \"mid\", \"high\"): raise Exception( 'missing string point argument, \\ can",
"int: \"\"\" Get led state register is the same for EC and PH",
"* 100)).to_bytes(4, \"big\") if self.debug: print(\"Temperature to set: %.2f\" % t) print( \"%s",
") value = self._convert_raw_hex_to_float(rawhex) / 100 if self.debug: print(\"%s compensation Temperature: %s°c\" %",
"%s\" % ( self.moduletype, info[0], info[1], ) def get_type(self): \"\"\" Read sensor type",
"EC/! /! in float for pH/! \"\"\" if \"EC\" == self.moduletype: register =",
":param addr: int = new i2c add \"\"\" if addr not in self.ADDR_OEM_HEXA",
"register is the same for EC and PH OEM circuit :return: int 0x01",
"for EC and PH OEM circuit :return: int 0x01 = WakeUp or 0x00",
"register = self.OEM_PH_REGISTERS[\"device_calibration_msb\"] byte_array = int(round(value * 1000)).to_bytes(4, \"big\") self.write(register, byte_array) if self.debug:",
"only be \"dry\", \"single\", \"low\", \"mid\", \"high\"' ) if \"EC\" == self.moduletype: points",
"device i2c address :param addr: int = new i2c add \"\"\" if addr",
"hex(state) else \"OFF\") ) def set_wakeup_sleep_mode(self, action=0x01): \"\"\"change device mode to Active or",
"firmware def get_new_read_available(self): \"\"\" New Read is available @return int 1 if new",
"/ 1000 if self.debug: print( \"%s: %s%s\" % ( self.moduletype, value, \"µs\" if",
"\"\"\" Description ----------- Class to communicate with Atlas Scientific OEM sensors in I2C",
"return mode # ----- Setters ----- ######## def set_temperature(self, t=25.0): \"\"\"Set the compensation",
"\"low\", \"mid\", \"high\" only \"\"\" if point not in (\"dry\", \"single\", \"low\", \"mid\",",
"= {\"dry\": 0x02, \"single\": 0x03, \"low\": 0x04, \"high\": 0x05} register = self.OEM_EC_REGISTERS[\"device_calibration_request\"] elif",
"self.read( self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 100 if self.debug: print(\"%s compensation",
"\"\"\" Get led state register is the same for EC and PH OEM",
"points[point]) # apply point calibration data time.sleep(self.short_timeout) # wait before read register to",
"not in (\"dry\", \"single\", \"low\", \"mid\", \"high\"): raise Exception( 'missing string point argument,",
"with Atlas Scientific OEM sensors in I2C mode. Atlas Scientific i2c by GreenPonik",
"value = self._convert_raw_hex_to_float(rawhex) / 100 if self.debug: print(\"%s compensation Temperature: %s°c\" % (self.moduletype,",
"= self.read( self.OEM_EC_REGISTERS[\"device_firmware\"], self.ONE_BYTE_READ, ) if self.debug: print(\"Firmware type is: %s\" % firmware)",
"is: %s\" % ( self.moduletype, info[0], info[1], ) def get_type(self): \"\"\" Read sensor",
"micro siemens µS for EC/! /! in float for pH/! \"\"\" if \"EC\"",
"or 0x00 = Hibernate :rtype: int \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] mode = self.read(register)",
"wait before read register to get confirmation conf = self.read(register) self._check_calibration_confirm(conf) return conf",
"and PH OEM circuit :return: int 0x00 = OFF or 0x01 = ON",
"write workflow to change physical i2c address \"\"\" self.address(addr) raise NotImplementedError(\"write workflow to",
"communicate with Atlas Scientific OEM sensors in I2C mode. Atlas Scientific i2c by",
"class _CommonsI2c(_AtlasOEMI2c): \"\"\" commons methods for EC and PH OEM circuits \"\"\" def",
"point=\"\"): \"\"\"apply the calibration :param value: float solution calibration value converted in float.",
"= self.read(register) if self.debug: print( \"Device is currently in mode: %s\" % (\"wakeup\"",
"registers do not use alone because calibration is apply by using set_calibration_apply /!in",
"sensor type @return int the sensor type (1=EC, 4=PH) \"\"\" if \"EC\" ==",
"self.moduletype: device_type = self.read( self.OEM_EC_REGISTERS[\"device_type\"], self.ONE_BYTE_READ, ) if self.debug: print(\"Device type is: %s\"",
"@return int the firmware revision \"\"\" if \"EC\" == self.moduletype or \"PH\" ==",
"float micro siemens µS for EC/! /! in float for pH/! \"\"\" if",
"= OFF or 0x01 = ON :rtype: int \"\"\" register = self.OEM_EC_REGISTERS[\"device_led\"] led_status",
"return float converted value \"\"\" hexstr = byte_array.hex() float_from_hexa = float.fromhex(byte_array.hex()) converted =",
"\"PH\" == self.moduletype: firmware = self.read( self.OEM_EC_REGISTERS[\"device_firmware\"], self.ONE_BYTE_READ, ) if self.debug: print(\"Firmware type",
"can only be \"dry\", \"single\", \"low\", \"mid\", \"high\"' ) if \"EC\" == self.moduletype:",
"self.address(addr) raise NotImplementedError(\"write workflow to change physical i2c address\") def set_led(self, state=0x01): \"\"\"Change",
":rtype: \"\"\" if \"EC\" == self.moduletype: register = self.OEM_EC_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"dry\":",
"print( \"Led status change to: %s\" % (\"On\" if hex(0x01) == hex(state) else",
"\"\"\" New Read is available @return int 1 if new read available, 0",
"if \"EC\" == self.moduletype: rawhex = self.read( self.OEM_EC_REGISTERS[\"device_ec_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex)",
"physical i2c address\") def set_led(self, state=0x01): \"\"\"Change Led state :param state: byte state",
"%s°c\" % (self.moduletype, value)) return value def get_calibration(self): \"\"\" Get current calibrations data",
"\"\"\" if self.debug: if hex(0x00) == hex(confirm): print(\"Calibration applied\") else: raise Exception(\"Cannot confirm",
"= self.read( self.OEM_PH_REGISTERS[\"device_ph_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 1000 if self.debug: print(",
"device_type def get_firmware(self): \"\"\" Read sensor firmware @return int the firmware revision \"\"\"",
"is_new_read = self.read( self.OEM_EC_REGISTERS[\"device_new_reading\"], self.ONE_BYTE_READ, ) return is_new_read def get_read(self): \"\"\" Read sensor",
"Get current calibrations data :return: string with current points calibrated :rtype: \"\"\" if",
"PH OEM circuit :return: int 0x00 = OFF or 0x01 = ON :rtype:",
"> 1413.0 :param point: string \"dry\", \"single\", \"low\", \"mid\", \"high\" only \"\"\" if",
"PH OEM circuit :return: int 0x01 = WakeUp or 0x00 = Hibernate :rtype:",
"\"PH\" == self.moduletype: points = {\"low\": 0x02, \"mid\": 0x03, \"high\": 0x04} register =",
"is: %s\" % device_type) return device_type def get_firmware(self): \"\"\" Read sensor firmware @return",
"information @return string module type, firmware version \"\"\" if \"EC\" == self.moduletype or",
"self.ADDR_OEM_DECIMAL: raise Exception( \"only decimal address expected, convert hexa by using \\ AtlasI2c.ADDR_OEM_DECIMAL",
"if self.debug: print(\"Firmware type is: %s\" % firmware) return firmware def get_new_read_available(self): \"\"\"",
"= self._convert_raw_hex_to_float(rawhex) / 1000 if self.debug: print( \"%s: %s%s\" % ( self.moduletype, value,",
"siemens µS for EC/! /! in float for pH/! \"\"\" if \"EC\" ==",
"# ec calibration wait for µSiemens byte_array = int(round(value * 100)).to_bytes(4, \"big\") elif",
"\"\"\" if point not in (\"dry\", \"single\", \"low\", \"mid\", \"high\"): raise Exception( 'missing",
"== self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) value = self._convert_raw_hex_to_float(rawhex) / 100",
"def set_calibration_apply(self, value, point=\"\"): \"\"\"apply the calibration :param value: float solution calibration value",
"value: float solution calibration value converted in float. EC waiting for µS e.g.",
"self.OEM_EC_REGISTERS[\"device_calibration_confirm\"] \"\"\" bits - \"dry\": 0, - \"single\": 1, - \"low\": 2, -",
"== hex(state) else \"OFF\") ) def set_wakeup_sleep_mode(self, action=0x01): \"\"\"change device mode to Active",
"self.OEM_EC_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, ) elif \"PH\" == self.moduletype: rawhex = self.read( self.OEM_PH_REGISTERS[\"device_temperature_comp_msb\"], self.FOUR_BYTE_READ, )",
"if self.debug: print( \"Led status change to: %s\" % (\"On\" if hex(0x01) ==",
"value \"\"\" # self.set_wakeup_sleep_mode(0x01) # wake device before read time.sleep(self._long_timeout) if \"EC\" ==",
"= WakeUp or 0x00 = Hibernate \"\"\" register = self.OEM_EC_REGISTERS[\"device_sleep\"] self.write(register, action) if"
] |
[
"main(request, environ).getResult() # except Exception as ex: # error = {\"error\": str(ex.args[0])} #",
"{\"status\": 200, \"value\": error, \"type\": \"application/json\"} self.response = main(request, environ).getResult() def result(self): if",
"make anything. self.response = \"\"\"<h1>Petition doesn't have <u>Environ</u> or <u>Location</u></h1>\"\"\" elif environ !=",
"for piece in a.timetuple()[:3]: logtime += str(piece)+'-' logtime = logtime[:-1]+\" \" for piece",
"str(piece)+'-' logtime = logtime[:-1]+\" \" for piece in a.timetuple()[3:]: logtime += str(piece)+':' logtime",
"str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'r') if len(log.readlines()) > 500: self.cleanLogs(self.environ['DOCUMENT_ROOT']+'logs')",
"doesn't have <u>Environ</u> or <u>Location</u></h1>\"\"\" elif environ != None: self.environ = environ from",
"str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() return str(logData) def cleanLogs(self, location): logfiles = os.listdir(location) if len(logfiles)",
"None if environ == None and location == None: #If the environ and",
"os class core: def __init__(self, environ = None, location = None): self.response =",
"= os.listdir(location) if len(logfiles) == 9: os.remove(logfiles[-1]) logfiles = logfiles[:-1] cont = 1",
"cleanLogs(self, location): logfiles = os.listdir(location) if len(logfiles) == 9: os.remove(logfiles[-1]) logfiles = logfiles[:-1]",
"None: #If the environ and the location are None, no make anything. self.response",
"+= str(piece)+':' logtime = logtime[:-3] if len(logdir) < 1: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w')",
"= buildRq() from tools.main import main request = buildReq.extrctEnv(environ, environ['DOCUMENT_ROOT']) # try: #",
"if len(log.readlines()) > 500: self.cleanLogs(self.environ['DOCUMENT_ROOT']+'logs') log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log',",
"for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() return str(logData) def cleanLogs(self, location): logfiles =",
"self.response = {\"status\": 200, \"value\": error, \"type\": \"application/json\"} self.response = main(request, environ).getResult() def",
"= open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'a') for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n')",
"logtime = '' for piece in a.timetuple()[:3]: logtime += str(piece)+'-' logtime = logtime[:-1]+\"",
"= None, location = None): self.response = None if environ == None and",
"'a') for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() return str(logData) def cleanLogs(self, location): logfiles",
"for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'r') if len(log.readlines())",
"'' for piece in a.timetuple()[:3]: logtime += str(piece)+'-' logtime = logtime[:-1]+\" \" for",
"self.response = \"\"\"<h1>Petition doesn't have <u>Environ</u> or <u>Location</u></h1>\"\"\" elif environ != None: self.environ",
"if len(logdir) < 1: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n')",
"{\"error\": str(ex.args[0])} # self.response = {\"status\": 200, \"value\": error, \"type\": \"application/json\"} self.response =",
"logtime += str(piece)+'-' logtime = logtime[:-1]+\" \" for piece in a.timetuple()[3:]: logtime +=",
"500: self.cleanLogs(self.environ['DOCUMENT_ROOT']+'logs') log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'a') for piece",
"\"value\": error, \"type\": \"application/json\"} self.response = main(request, environ).getResult() def result(self): if self.response !=",
"the core...\"] def logs(self, logData): logdir = os.listdir(self.environ['DOCUMENT_ROOT']+'logs/') a = datetime.now() logtime =",
"if len(logfiles) == 9: os.remove(logfiles[-1]) logfiles = logfiles[:-1] cont = 1 for log",
"self.environ = environ from tools.Utilities import buildRq buildReq = buildRq() from tools.main import",
"def result(self): if self.response != None: return self.response else: return [\"plain\", \"Problem with",
"environ).getResult() # except Exception as ex: # error = {\"error\": str(ex.args[0])} # self.response",
"buildRq() from tools.main import main request = buildReq.extrctEnv(environ, environ['DOCUMENT_ROOT']) # try: # self.response",
"are None, no make anything. self.response = \"\"\"<h1>Petition doesn't have <u>Environ</u> or <u>Location</u></h1>\"\"\"",
"log.write('['+logtime+']'+str(piece)+'\\n') log.close() return str(logData) def cleanLogs(self, location): logfiles = os.listdir(location) if len(logfiles) ==",
"environ = None, location = None): self.response = None if environ == None",
"location == None: #If the environ and the location are None, no make",
"environ from tools.Utilities import buildRq buildReq = buildRq() from tools.main import main request",
"datetime import datetime import os class core: def __init__(self, environ = None, location",
"!= None: return self.response else: return [\"plain\", \"Problem with the communication with the",
"None): self.response = None if environ == None and location == None: #If",
"a.timetuple()[3:]: logtime += str(piece)+':' logtime = logtime[:-3] if len(logdir) < 1: log =",
"log.write('['+logtime+']'+str(piece)+'\\n') log.close() else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'r') if len(log.readlines()) > 500: self.cleanLogs(self.environ['DOCUMENT_ROOT']+'logs') log",
"a.timetuple()[:3]: logtime += str(piece)+'-' logtime = logtime[:-1]+\" \" for piece in a.timetuple()[3:]: logtime",
"== None and location == None: #If the environ and the location are",
"= environ from tools.Utilities import buildRq buildReq = buildRq() from tools.main import main",
"None: return self.response else: return [\"plain\", \"Problem with the communication with the core...\"]",
"= {\"status\": 200, \"value\": error, \"type\": \"application/json\"} self.response = main(request, environ).getResult() def result(self):",
"def logs(self, logData): logdir = os.listdir(self.environ['DOCUMENT_ROOT']+'logs/') a = datetime.now() logtime = '' for",
"\"\"\"<h1>Petition doesn't have <u>Environ</u> or <u>Location</u></h1>\"\"\" elif environ != None: self.environ = environ",
"= logtime[:-3] if len(logdir) < 1: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') for piece in",
"= {\"error\": str(ex.args[0])} # self.response = {\"status\": 200, \"value\": error, \"type\": \"application/json\"} self.response",
"if self.response != None: return self.response else: return [\"plain\", \"Problem with the communication",
"else: return [\"plain\", \"Problem with the communication with the core...\"] def logs(self, logData):",
"self.response = None if environ == None and location == None: #If the",
"location): logfiles = os.listdir(location) if len(logfiles) == 9: os.remove(logfiles[-1]) logfiles = logfiles[:-1] cont",
"logtime[:-1]+\" \" for piece in a.timetuple()[3:]: logtime += str(piece)+':' logtime = logtime[:-3] if",
"datetime.now() logtime = '' for piece in a.timetuple()[:3]: logtime += str(piece)+'-' logtime =",
"from tools.main import main request = buildReq.extrctEnv(environ, environ['DOCUMENT_ROOT']) # try: # self.response =",
"log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'r') if len(log.readlines()) > 500: self.cleanLogs(self.environ['DOCUMENT_ROOT']+'logs') log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w')",
"in a.timetuple()[:3]: logtime += str(piece)+'-' logtime = logtime[:-1]+\" \" for piece in a.timetuple()[3:]:",
"logfiles = logfiles[:-1] cont = 1 for log in logfiles: os.rename(self.environ['DOCUMENT_ROOT']+'logs/'+log, self.environ['DOCUMENT_ROOT']+'logs/error_'+str(cont)+'.log') else:",
"None, no make anything. self.response = \"\"\"<h1>Petition doesn't have <u>Environ</u> or <u>Location</u></h1>\"\"\" elif",
"log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'a') for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() return str(logData) def",
"import main request = buildReq.extrctEnv(environ, environ['DOCUMENT_ROOT']) # try: # self.response = main(request, environ).getResult()",
"# self.response = main(request, environ).getResult() # except Exception as ex: # error =",
"in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'r') if len(log.readlines()) > 500:",
"= os.listdir(self.environ['DOCUMENT_ROOT']+'logs/') a = datetime.now() logtime = '' for piece in a.timetuple()[:3]: logtime",
"as ex: # error = {\"error\": str(ex.args[0])} # self.response = {\"status\": 200, \"value\":",
"log.close() return str(logData) def cleanLogs(self, location): logfiles = os.listdir(location) if len(logfiles) == 9:",
"piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'r') if len(log.readlines()) >",
"= open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log',",
"\" for piece in a.timetuple()[3:]: logtime += str(piece)+':' logtime = logtime[:-3] if len(logdir)",
"environ and the location are None, no make anything. self.response = \"\"\"<h1>Petition doesn't",
"__init__(self, environ = None, location = None): self.response = None if environ ==",
"open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'r')",
"#If the environ and the location are None, no make anything. self.response =",
"core...\"] def logs(self, logData): logdir = os.listdir(self.environ['DOCUMENT_ROOT']+'logs/') a = datetime.now() logtime = ''",
"else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'r') if len(log.readlines()) > 500: self.cleanLogs(self.environ['DOCUMENT_ROOT']+'logs') log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log',",
"= open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'r') if len(log.readlines()) > 500: self.cleanLogs(self.environ['DOCUMENT_ROOT']+'logs') log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') else:",
"the location are None, no make anything. self.response = \"\"\"<h1>Petition doesn't have <u>Environ</u>",
"logfiles = os.listdir(location) if len(logfiles) == 9: os.remove(logfiles[-1]) logfiles = logfiles[:-1] cont =",
"logfiles: os.rename(self.environ['DOCUMENT_ROOT']+'logs/'+log, self.environ['DOCUMENT_ROOT']+'logs/error_'+str(cont)+'.log') else: cont = 1 for log in logfiles: os.rename(self.environ['DOCUMENT_ROOT']+'logs/'+log, self.environ['DOCUMENT_ROOT']+'logs/error_'+str(cont)+'.log')",
"= None): self.response = None if environ == None and location == None:",
"buildReq.extrctEnv(environ, environ['DOCUMENT_ROOT']) # try: # self.response = main(request, environ).getResult() # except Exception as",
"# except Exception as ex: # error = {\"error\": str(ex.args[0])} # self.response =",
"have <u>Environ</u> or <u>Location</u></h1>\"\"\" elif environ != None: self.environ = environ from tools.Utilities",
"logtime[:-3] if len(logdir) < 1: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') for piece in str(logData).split('\\n'):",
"len(logdir) < 1: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close()",
"<u>Environ</u> or <u>Location</u></h1>\"\"\" elif environ != None: self.environ = environ from tools.Utilities import",
"and the location are None, no make anything. self.response = \"\"\"<h1>Petition doesn't have",
"logtime = logtime[:-1]+\" \" for piece in a.timetuple()[3:]: logtime += str(piece)+':' logtime =",
"tools.Utilities import buildRq buildReq = buildRq() from tools.main import main request = buildReq.extrctEnv(environ,",
"= main(request, environ).getResult() def result(self): if self.response != None: return self.response else: return",
"piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() return str(logData) def cleanLogs(self, location): logfiles = os.listdir(location)",
"import os class core: def __init__(self, environ = None, location = None): self.response",
"from datetime import datetime import os class core: def __init__(self, environ = None,",
"buildRq buildReq = buildRq() from tools.main import main request = buildReq.extrctEnv(environ, environ['DOCUMENT_ROOT']) #",
"str(ex.args[0])} # self.response = {\"status\": 200, \"value\": error, \"type\": \"application/json\"} self.response = main(request,",
"# try: # self.response = main(request, environ).getResult() # except Exception as ex: #",
"== None: #If the environ and the location are None, no make anything.",
"for log in logfiles: os.rename(self.environ['DOCUMENT_ROOT']+'logs/'+log, self.environ['DOCUMENT_ROOT']+'logs/error_'+str(cont)+'.log') else: cont = 1 for log in",
"= main(request, environ).getResult() # except Exception as ex: # error = {\"error\": str(ex.args[0])}",
"in a.timetuple()[3:]: logtime += str(piece)+':' logtime = logtime[:-3] if len(logdir) < 1: log",
"= 1 for log in logfiles: os.rename(self.environ['DOCUMENT_ROOT']+'logs/'+log, self.environ['DOCUMENT_ROOT']+'logs/error_'+str(cont)+'.log') else: cont = 1 for",
"main(request, environ).getResult() def result(self): if self.response != None: return self.response else: return [\"plain\",",
"9: os.remove(logfiles[-1]) logfiles = logfiles[:-1] cont = 1 for log in logfiles: os.rename(self.environ['DOCUMENT_ROOT']+'logs/'+log,",
"return [\"plain\", \"Problem with the communication with the core...\"] def logs(self, logData): logdir",
"datetime import os class core: def __init__(self, environ = None, location = None):",
"# error = {\"error\": str(ex.args[0])} # self.response = {\"status\": 200, \"value\": error, \"type\":",
"cont = 1 for log in logfiles: os.rename(self.environ['DOCUMENT_ROOT']+'logs/'+log, self.environ['DOCUMENT_ROOT']+'logs/error_'+str(cont)+'.log') else: cont = 1",
"None: self.environ = environ from tools.Utilities import buildRq buildReq = buildRq() from tools.main",
"piece in a.timetuple()[:3]: logtime += str(piece)+'-' logtime = logtime[:-1]+\" \" for piece in",
"def cleanLogs(self, location): logfiles = os.listdir(location) if len(logfiles) == 9: os.remove(logfiles[-1]) logfiles =",
"environ).getResult() def result(self): if self.response != None: return self.response else: return [\"plain\", \"Problem",
"a = datetime.now() logtime = '' for piece in a.timetuple()[:3]: logtime += str(piece)+'-'",
"logfiles[:-1] cont = 1 for log in logfiles: os.rename(self.environ['DOCUMENT_ROOT']+'logs/'+log, self.environ['DOCUMENT_ROOT']+'logs/error_'+str(cont)+'.log') else: cont =",
"None, location = None): self.response = None if environ == None and location",
"logdir = os.listdir(self.environ['DOCUMENT_ROOT']+'logs/') a = datetime.now() logtime = '' for piece in a.timetuple()[:3]:",
"except Exception as ex: # error = {\"error\": str(ex.args[0])} # self.response = {\"status\":",
"self.response = main(request, environ).getResult() def result(self): if self.response != None: return self.response else:",
"return str(logData) def cleanLogs(self, location): logfiles = os.listdir(location) if len(logfiles) == 9: os.remove(logfiles[-1])",
"or <u>Location</u></h1>\"\"\" elif environ != None: self.environ = environ from tools.Utilities import buildRq",
"\"Problem with the communication with the core...\"] def logs(self, logData): logdir = os.listdir(self.environ['DOCUMENT_ROOT']+'logs/')",
"log in logfiles: os.rename(self.environ['DOCUMENT_ROOT']+'logs/'+log, self.environ['DOCUMENT_ROOT']+'logs/error_'+str(cont)+'.log') else: cont = 1 for log in logfiles:",
"error, \"type\": \"application/json\"} self.response = main(request, environ).getResult() def result(self): if self.response != None:",
"None and location == None: #If the environ and the location are None,",
"the communication with the core...\"] def logs(self, logData): logdir = os.listdir(self.environ['DOCUMENT_ROOT']+'logs/') a =",
"from tools.Utilities import buildRq buildReq = buildRq() from tools.main import main request =",
"str(piece)+':' logtime = logtime[:-3] if len(logdir) < 1: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') for",
"self.response != None: return self.response else: return [\"plain\", \"Problem with the communication with",
"with the core...\"] def logs(self, logData): logdir = os.listdir(self.environ['DOCUMENT_ROOT']+'logs/') a = datetime.now() logtime",
"os.listdir(location) if len(logfiles) == 9: os.remove(logfiles[-1]) logfiles = logfiles[:-1] cont = 1 for",
"location = None): self.response = None if environ == None and location ==",
"tools.main import main request = buildReq.extrctEnv(environ, environ['DOCUMENT_ROOT']) # try: # self.response = main(request,",
"# self.response = {\"status\": 200, \"value\": error, \"type\": \"application/json\"} self.response = main(request, environ).getResult()",
"in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() return str(logData) def cleanLogs(self, location): logfiles = os.listdir(location) if",
"logData): logdir = os.listdir(self.environ['DOCUMENT_ROOT']+'logs/') a = datetime.now() logtime = '' for piece in",
"environ == None and location == None: #If the environ and the location",
"import datetime import os class core: def __init__(self, environ = None, location =",
"if environ == None and location == None: #If the environ and the",
"\"application/json\"} self.response = main(request, environ).getResult() def result(self): if self.response != None: return self.response",
"= datetime.now() logtime = '' for piece in a.timetuple()[:3]: logtime += str(piece)+'-' logtime",
"logtime = logtime[:-3] if len(logdir) < 1: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') for piece",
"main request = buildReq.extrctEnv(environ, environ['DOCUMENT_ROOT']) # try: # self.response = main(request, environ).getResult() #",
"open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'a') for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() return str(logData) def cleanLogs(self, location):",
"error = {\"error\": str(ex.args[0])} # self.response = {\"status\": 200, \"value\": error, \"type\": \"application/json\"}",
"self.response else: return [\"plain\", \"Problem with the communication with the core...\"] def logs(self,",
"= buildReq.extrctEnv(environ, environ['DOCUMENT_ROOT']) # try: # self.response = main(request, environ).getResult() # except Exception",
"logs(self, logData): logdir = os.listdir(self.environ['DOCUMENT_ROOT']+'logs/') a = datetime.now() logtime = '' for piece",
"def __init__(self, environ = None, location = None): self.response = None if environ",
"self.response = main(request, environ).getResult() # except Exception as ex: # error = {\"error\":",
"with the communication with the core...\"] def logs(self, logData): logdir = os.listdir(self.environ['DOCUMENT_ROOT']+'logs/') a",
"1: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() else: log",
"class core: def __init__(self, environ = None, location = None): self.response = None",
"return self.response else: return [\"plain\", \"Problem with the communication with the core...\"] def",
"environ['DOCUMENT_ROOT']) # try: # self.response = main(request, environ).getResult() # except Exception as ex:",
"[\"plain\", \"Problem with the communication with the core...\"] def logs(self, logData): logdir =",
"len(log.readlines()) > 500: self.cleanLogs(self.environ['DOCUMENT_ROOT']+'logs') log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'a')",
"os.remove(logfiles[-1]) logfiles = logfiles[:-1] cont = 1 for log in logfiles: os.rename(self.environ['DOCUMENT_ROOT']+'logs/'+log, self.environ['DOCUMENT_ROOT']+'logs/error_'+str(cont)+'.log')",
"> 500: self.cleanLogs(self.environ['DOCUMENT_ROOT']+'logs') log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'a') for",
"log.close() else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'r') if len(log.readlines()) > 500: self.cleanLogs(self.environ['DOCUMENT_ROOT']+'logs') log =",
"open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'r') if len(log.readlines()) > 500: self.cleanLogs(self.environ['DOCUMENT_ROOT']+'logs') log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') else: log",
"in logfiles: os.rename(self.environ['DOCUMENT_ROOT']+'logs/'+log, self.environ['DOCUMENT_ROOT']+'logs/error_'+str(cont)+'.log') else: cont = 1 for log in logfiles: os.rename(self.environ['DOCUMENT_ROOT']+'logs/'+log,",
"len(logfiles) == 9: os.remove(logfiles[-1]) logfiles = logfiles[:-1] cont = 1 for log in",
"== 9: os.remove(logfiles[-1]) logfiles = logfiles[:-1] cont = 1 for log in logfiles:",
"logtime += str(piece)+':' logtime = logtime[:-3] if len(logdir) < 1: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log',",
"<u>Location</u></h1>\"\"\" elif environ != None: self.environ = environ from tools.Utilities import buildRq buildReq",
"piece in a.timetuple()[3:]: logtime += str(piece)+':' logtime = logtime[:-3] if len(logdir) < 1:",
"!= None: self.environ = environ from tools.Utilities import buildRq buildReq = buildRq() from",
"= \"\"\"<h1>Petition doesn't have <u>Environ</u> or <u>Location</u></h1>\"\"\" elif environ != None: self.environ =",
"anything. self.response = \"\"\"<h1>Petition doesn't have <u>Environ</u> or <u>Location</u></h1>\"\"\" elif environ != None:",
"log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'a') for piece in str(logData).split('\\n'):",
"'w') for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'r') if",
"= logfiles[:-1] cont = 1 for log in logfiles: os.rename(self.environ['DOCUMENT_ROOT']+'logs/'+log, self.environ['DOCUMENT_ROOT']+'logs/error_'+str(cont)+'.log') else: cont",
"buildReq = buildRq() from tools.main import main request = buildReq.extrctEnv(environ, environ['DOCUMENT_ROOT']) # try:",
"1 for log in logfiles: os.rename(self.environ['DOCUMENT_ROOT']+'logs/'+log, self.environ['DOCUMENT_ROOT']+'logs/error_'+str(cont)+'.log') else: cont = 1 for log",
"import buildRq buildReq = buildRq() from tools.main import main request = buildReq.extrctEnv(environ, environ['DOCUMENT_ROOT'])",
"< 1: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() else:",
"else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'a') for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() return str(logData)",
"core: def __init__(self, environ = None, location = None): self.response = None if",
"os.listdir(self.environ['DOCUMENT_ROOT']+'logs/') a = datetime.now() logtime = '' for piece in a.timetuple()[:3]: logtime +=",
"self.cleanLogs(self.environ['DOCUMENT_ROOT']+'logs') log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'a') for piece in",
"= logtime[:-1]+\" \" for piece in a.timetuple()[3:]: logtime += str(piece)+':' logtime = logtime[:-3]",
"and location == None: #If the environ and the location are None, no",
"\"type\": \"application/json\"} self.response = main(request, environ).getResult() def result(self): if self.response != None: return",
"+= str(piece)+'-' logtime = logtime[:-1]+\" \" for piece in a.timetuple()[3:]: logtime += str(piece)+':'",
"200, \"value\": error, \"type\": \"application/json\"} self.response = main(request, environ).getResult() def result(self): if self.response",
"Exception as ex: # error = {\"error\": str(ex.args[0])} # self.response = {\"status\": 200,",
"'r') if len(log.readlines()) > 500: self.cleanLogs(self.environ['DOCUMENT_ROOT']+'logs') log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') else: log =",
"no make anything. self.response = \"\"\"<h1>Petition doesn't have <u>Environ</u> or <u>Location</u></h1>\"\"\" elif environ",
"str(logData) def cleanLogs(self, location): logfiles = os.listdir(location) if len(logfiles) == 9: os.remove(logfiles[-1]) logfiles",
"try: # self.response = main(request, environ).getResult() # except Exception as ex: # error",
"elif environ != None: self.environ = environ from tools.Utilities import buildRq buildReq =",
"request = buildReq.extrctEnv(environ, environ['DOCUMENT_ROOT']) # try: # self.response = main(request, environ).getResult() # except",
"communication with the core...\"] def logs(self, logData): logdir = os.listdir(self.environ['DOCUMENT_ROOT']+'logs/') a = datetime.now()",
"the environ and the location are None, no make anything. self.response = \"\"\"<h1>Petition",
"for piece in a.timetuple()[3:]: logtime += str(piece)+':' logtime = logtime[:-3] if len(logdir) <",
"'w') else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'a') for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() return",
"= open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'a') for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() return str(logData) def cleanLogs(self,",
"ex: # error = {\"error\": str(ex.args[0])} # self.response = {\"status\": 200, \"value\": error,",
"location are None, no make anything. self.response = \"\"\"<h1>Petition doesn't have <u>Environ</u> or",
"open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') else: log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'a') for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close()",
"log = open(self.environ['DOCUMENT_ROOT']+'logs/error.log', 'w') for piece in str(logData).split('\\n'): log.write('['+logtime+']'+str(piece)+'\\n') log.close() else: log =",
"= '' for piece in a.timetuple()[:3]: logtime += str(piece)+'-' logtime = logtime[:-1]+\" \"",
"result(self): if self.response != None: return self.response else: return [\"plain\", \"Problem with the",
"= None if environ == None and location == None: #If the environ",
"environ != None: self.environ = environ from tools.Utilities import buildRq buildReq = buildRq()"
] |
[
"shell. \"\"\" from twisted.python.versions import Version from twisted.python.deprecate import deprecatedModuleAttribute deprecatedModuleAttribute( Version(\"Twisted\", 11,",
"details. \"\"\" Subpackage containing the modules that implement the command line tools. Note",
"from twisted.python.deprecate import deprecatedModuleAttribute deprecatedModuleAttribute( Version(\"Twisted\", 11, 1, 0), \"Seek unzipping software outside",
"from twisted.python.versions import Version from twisted.python.deprecate import deprecatedModuleAttribute deprecatedModuleAttribute( Version(\"Twisted\", 11, 1, 0),",
"a shell. \"\"\" from twisted.python.versions import Version from twisted.python.deprecate import deprecatedModuleAttribute deprecatedModuleAttribute( Version(\"Twisted\",",
"intended to be invoked directly from a shell. \"\"\" from twisted.python.versions import Version",
"that implement the command line tools. Note that these are imported by top-level",
"Version from twisted.python.deprecate import deprecatedModuleAttribute deprecatedModuleAttribute( Version(\"Twisted\", 11, 1, 0), \"Seek unzipping software",
"from a shell. \"\"\" from twisted.python.versions import Version from twisted.python.deprecate import deprecatedModuleAttribute deprecatedModuleAttribute(",
"0), \"Seek unzipping software outside of Twisted.\", __name__, \"tkunzip\") deprecatedModuleAttribute( Version(\"Twisted\", 12, 1,",
"software outside of Twisted.\", __name__, \"tkunzip\") deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"tapconvert has",
"\"\"\" from twisted.python.versions import Version from twisted.python.deprecate import deprecatedModuleAttribute deprecatedModuleAttribute( Version(\"Twisted\", 11, 1,",
"\"\"\" Subpackage containing the modules that implement the command line tools. Note that",
"for details. \"\"\" Subpackage containing the modules that implement the command line tools.",
"See LICENSE for details. \"\"\" Subpackage containing the modules that implement the command",
"Subpackage containing the modules that implement the command line tools. Note that these",
"(c) Twisted Matrix Laboratories. # See LICENSE for details. \"\"\" Subpackage containing the",
"\"Seek unzipping software outside of Twisted.\", __name__, \"tkunzip\") deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0),",
"import deprecatedModuleAttribute deprecatedModuleAttribute( Version(\"Twisted\", 11, 1, 0), \"Seek unzipping software outside of Twisted.\",",
"twisted.python.deprecate import deprecatedModuleAttribute deprecatedModuleAttribute( Version(\"Twisted\", 11, 1, 0), \"Seek unzipping software outside of",
"Matrix Laboratories. # See LICENSE for details. \"\"\" Subpackage containing the modules that",
"which are intended to be invoked directly from a shell. \"\"\" from twisted.python.versions",
"import Version from twisted.python.deprecate import deprecatedModuleAttribute deprecatedModuleAttribute( Version(\"Twisted\", 11, 1, 0), \"Seek unzipping",
"are imported by top-level scripts which are intended to be invoked directly from",
"invoked directly from a shell. \"\"\" from twisted.python.versions import Version from twisted.python.deprecate import",
"Version(\"Twisted\", 12, 1, 0), \"tapconvert has been deprecated.\", __name__, \"tapconvert\") del Version, deprecatedModuleAttribute",
"Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. \"\"\" Subpackage containing",
"deprecatedModuleAttribute deprecatedModuleAttribute( Version(\"Twisted\", 11, 1, 0), \"Seek unzipping software outside of Twisted.\", __name__,",
"be invoked directly from a shell. \"\"\" from twisted.python.versions import Version from twisted.python.deprecate",
"scripts which are intended to be invoked directly from a shell. \"\"\" from",
"# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. \"\"\" Subpackage",
"top-level scripts which are intended to be invoked directly from a shell. \"\"\"",
"<filename>IMU/VTK-6.2.0/ThirdParty/Twisted/twisted/scripts/__init__.py # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. \"\"\"",
"implement the command line tools. Note that these are imported by top-level scripts",
"deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"tapconvert has been deprecated.\", __name__, \"tapconvert\") del Version,",
"containing the modules that implement the command line tools. Note that these are",
"tools. Note that these are imported by top-level scripts which are intended to",
"unzipping software outside of Twisted.\", __name__, \"tkunzip\") deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"tapconvert",
"Note that these are imported by top-level scripts which are intended to be",
"__name__, \"tkunzip\") deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"tapconvert has been deprecated.\", __name__, \"tapconvert\")",
"11, 1, 0), \"Seek unzipping software outside of Twisted.\", __name__, \"tkunzip\") deprecatedModuleAttribute( Version(\"Twisted\",",
"twisted.python.versions import Version from twisted.python.deprecate import deprecatedModuleAttribute deprecatedModuleAttribute( Version(\"Twisted\", 11, 1, 0), \"Seek",
"of Twisted.\", __name__, \"tkunzip\") deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"tapconvert has been deprecated.\",",
"1, 0), \"Seek unzipping software outside of Twisted.\", __name__, \"tkunzip\") deprecatedModuleAttribute( Version(\"Twisted\", 12,",
"Twisted.\", __name__, \"tkunzip\") deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"tapconvert has been deprecated.\", __name__,",
"modules that implement the command line tools. Note that these are imported by",
"outside of Twisted.\", __name__, \"tkunzip\") deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"tapconvert has been",
"Twisted Matrix Laboratories. # See LICENSE for details. \"\"\" Subpackage containing the modules",
"to be invoked directly from a shell. \"\"\" from twisted.python.versions import Version from",
"the modules that implement the command line tools. Note that these are imported",
"by top-level scripts which are intended to be invoked directly from a shell.",
"command line tools. Note that these are imported by top-level scripts which are",
"LICENSE for details. \"\"\" Subpackage containing the modules that implement the command line",
"the command line tools. Note that these are imported by top-level scripts which",
"\"tkunzip\") deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"tapconvert has been deprecated.\", __name__, \"tapconvert\") del",
"line tools. Note that these are imported by top-level scripts which are intended",
"Laboratories. # See LICENSE for details. \"\"\" Subpackage containing the modules that implement",
"directly from a shell. \"\"\" from twisted.python.versions import Version from twisted.python.deprecate import deprecatedModuleAttribute",
"that these are imported by top-level scripts which are intended to be invoked",
"deprecatedModuleAttribute( Version(\"Twisted\", 11, 1, 0), \"Seek unzipping software outside of Twisted.\", __name__, \"tkunzip\")",
"Version(\"Twisted\", 11, 1, 0), \"Seek unzipping software outside of Twisted.\", __name__, \"tkunzip\") deprecatedModuleAttribute(",
"are intended to be invoked directly from a shell. \"\"\" from twisted.python.versions import",
"# See LICENSE for details. \"\"\" Subpackage containing the modules that implement the",
"imported by top-level scripts which are intended to be invoked directly from a",
"these are imported by top-level scripts which are intended to be invoked directly"
] |
[
"item[1]) ) except Exception as e: print(e) return Response('The Roads database is offline',",
"item in conf.db_select(sql): items.append( (item[0], item[1]) ) except Exception as e: print(e) return",
"mapping points = [] for coords in coords_list: points.append(tuple([coords[1], coords[0]])) ave_lat = sum(p[0]",
"def show_map(): ''' Function to render a map around the specified line '''",
"information' folium.PolyLine(points, color=\"red\", weight=2.5, opacity=1, popup = name, tooltip=tooltip).add_to(folium_map) return folium_map.get_root().render() @routes.route('/rds/<string:roads_id>') def",
"as text)) LIKE '%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%' '''.format(search_string=search_string.strip().upper()) sql += '''ORDER BY",
"register_template=None, per_page=per_page, search_query=search_string, search_enabled=True ).render() @routes.route('/map') def show_map(): ''' Function to render a",
"@routes.route('/rds/') def roads(): # Search specific items using keywords search_string = request.values.get('search') try:",
"else 1 per_page = int(request.values.get('per_page')) \\ if request.values.get('per_page') is not None else DEFAULT_ITEMS_PER_PAGE",
"= (page - 1) * per_page # get the id and name for",
"# Search specific items using keywords search_string = request.values.get('search') try: # get the",
"mimetype='text/plain', status=500) return ContainerRenderer(request=request, instance_uri=request.url, label='Roads Register', comment='A register of Roads', parent_container_uri='http://linked.data.gov.au/def/placenames/PlaceName', parent_container_label='QLD_Roads',",
"items.append( (item[0], item[1]) ) except Exception as e: print(e) return Response('The Roads database",
"OR UPPER(\"name\") LIKE '%{search_string}%'; '''.format(search_string=search_string.strip().upper()) no_of_items = conf.db_select(sql)[0][0] page = int(request.values.get('page')) if request.values.get('page')",
"offline', mimetype='text/plain', status=500) return ContainerRenderer(request=request, instance_uri=request.url, label='Roads Register', comment='A register of Roads', parent_container_uri='http://linked.data.gov.au/def/placenames/PlaceName',",
"get the id and name for each record in the database sql =",
"items using keywords search_string = request.values.get('search') try: # get the register length from",
"more information' folium.PolyLine(points, color=\"red\", weight=2.5, opacity=1, popup = name, tooltip=tooltip).add_to(folium_map) return folium_map.get_root().render() @routes.route('/rds/<string:roads_id>')",
"no_of_items = conf.db_select(sql)[0][0] page = int(request.values.get('page')) if request.values.get('page') is not None else 1",
"comment='A register of Roads', parent_container_uri='http://linked.data.gov.au/def/placenames/PlaceName', parent_container_label='QLD_Roads', members=items, members_total_count=no_of_items, profiles=None, default_profile_token=None, super_register=None, page_size_max=1000, register_template=None,",
"coords_list = ast.literal_eval(request.values.get('coords'))[0] # swap x & y for mapping points = []",
"zoom_start=15) tooltip = 'Click for more information' folium.PolyLine(points, color=\"red\", weight=2.5, opacity=1, popup =",
"create a new map object folium_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=15) tooltip = 'Click",
"& y for mapping points = [] for coords in coords_list: points.append(tuple([coords[1], coords[0]]))",
"* per_page # get the id and name for each record in the",
"(item[0], item[1]) ) except Exception as e: print(e) return Response('The Roads database is",
"y for mapping points = [] for coords in coords_list: points.append(tuple([coords[1], coords[0]])) ave_lat",
"= Blueprint('controller', __name__) DEFAULT_ITEMS_PER_PAGE=50 @routes.route('/', strict_slashes=True) def home(): return render_template('home.html') @routes.route('/rds/') def roads():",
"x & y for mapping points = [] for coords in coords_list: points.append(tuple([coords[1],",
"ContainerRenderer import conf import ast import folium print(__name__) routes = Blueprint('controller', __name__) DEFAULT_ITEMS_PER_PAGE=50",
"database sql = '''SELECT \"id\", \"name\" FROM \"transportroads\"''' if search_string: sql += '''WHERE",
"len(points) # create a new map object folium_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=15) tooltip",
"UPPER(cast(\"id\" as text)) LIKE '%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%'; '''.format(search_string=search_string.strip().upper()) no_of_items = conf.db_select(sql)[0][0]",
"return render_template('home.html') @routes.route('/rds/') def roads(): # Search specific items using keywords search_string =",
"return ContainerRenderer(request=request, instance_uri=request.url, label='Roads Register', comment='A register of Roads', parent_container_uri='http://linked.data.gov.au/def/placenames/PlaceName', parent_container_label='QLD_Roads', members=items, members_total_count=no_of_items,",
"points) / len(points) # create a new map object folium_map = folium.Map(location=[ave_lat, ave_lon],",
"search_string = request.values.get('search') try: # get the register length from the online DB",
"import folium print(__name__) routes = Blueprint('controller', __name__) DEFAULT_ITEMS_PER_PAGE=50 @routes.route('/', strict_slashes=True) def home(): return",
"import Roads from pyldapi import ContainerRenderer import conf import ast import folium print(__name__)",
"line ''' name = request.values.get('name') coords_list = ast.literal_eval(request.values.get('coords'))[0] # swap x & y",
"Function to render a map around the specified line ''' name = request.values.get('name')",
"@routes.route('/', strict_slashes=True) def home(): return render_template('home.html') @routes.route('/rds/') def roads(): # Search specific items",
"'''WHERE UPPER(cast(\"id\" as text)) LIKE '%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%' '''.format(search_string=search_string.strip().upper()) sql +=",
"per_page=per_page, search_query=search_string, search_enabled=True ).render() @routes.route('/map') def show_map(): ''' Function to render a map",
"id and name for each record in the database sql = '''SELECT \"id\",",
"per_page = int(request.values.get('per_page')) \\ if request.values.get('per_page') is not None else DEFAULT_ITEMS_PER_PAGE offset =",
"+= '''WHERE UPPER(cast(\"id\" as text)) LIKE '%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%'; '''.format(search_string=search_string.strip().upper()) no_of_items",
"= [] for item in conf.db_select(sql): items.append( (item[0], item[1]) ) except Exception as",
"'%{search_string}%' '''.format(search_string=search_string.strip().upper()) sql += '''ORDER BY \"name\" OFFSET {} LIMIT {}'''.format(offset, per_page) items",
"conf.db_select(sql)[0][0] page = int(request.values.get('page')) if request.values.get('page') is not None else 1 per_page =",
"conf.db_select(sql): items.append( (item[0], item[1]) ) except Exception as e: print(e) return Response('The Roads",
"search_enabled=True ).render() @routes.route('/map') def show_map(): ''' Function to render a map around the",
"color=\"red\", weight=2.5, opacity=1, popup = name, tooltip=tooltip).add_to(folium_map) return folium_map.get_root().render() @routes.route('/rds/<string:roads_id>') def road(roads_id): roads",
"'SELECT COUNT(*) FROM \"transportroads\"' if search_string: sql += '''WHERE UPPER(cast(\"id\" as text)) LIKE",
"points = [] for coords in coords_list: points.append(tuple([coords[1], coords[0]])) ave_lat = sum(p[0] for",
"= conf.db_select(sql)[0][0] page = int(request.values.get('page')) if request.values.get('page') is not None else 1 per_page",
"import ast import folium print(__name__) routes = Blueprint('controller', __name__) DEFAULT_ITEMS_PER_PAGE=50 @routes.route('/', strict_slashes=True) def",
"home(): return render_template('home.html') @routes.route('/rds/') def roads(): # Search specific items using keywords search_string",
"UPPER(\"name\") LIKE '%{search_string}%'; '''.format(search_string=search_string.strip().upper()) no_of_items = conf.db_select(sql)[0][0] page = int(request.values.get('page')) if request.values.get('page') is",
"for each record in the database sql = '''SELECT \"id\", \"name\" FROM \"transportroads\"'''",
"search_query=search_string, search_enabled=True ).render() @routes.route('/map') def show_map(): ''' Function to render a map around",
"int(request.values.get('per_page')) \\ if request.values.get('per_page') is not None else DEFAULT_ITEMS_PER_PAGE offset = (page -",
"status=500) return ContainerRenderer(request=request, instance_uri=request.url, label='Roads Register', comment='A register of Roads', parent_container_uri='http://linked.data.gov.au/def/placenames/PlaceName', parent_container_label='QLD_Roads', members=items,",
"LIKE '%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%'; '''.format(search_string=search_string.strip().upper()) no_of_items = conf.db_select(sql)[0][0] page = int(request.values.get('page'))",
"for p in points) / len(points) ave_lon = sum(p[1] for p in points)",
"import Blueprint, request, Response, render_template from model.roads import Roads from pyldapi import ContainerRenderer",
"import ContainerRenderer import conf import ast import folium print(__name__) routes = Blueprint('controller', __name__)",
"is not None else 1 per_page = int(request.values.get('per_page')) \\ if request.values.get('per_page') is not",
"DB sql = 'SELECT COUNT(*) FROM \"transportroads\"' if search_string: sql += '''WHERE UPPER(cast(\"id\"",
"per_page # get the id and name for each record in the database",
"None else 1 per_page = int(request.values.get('per_page')) \\ if request.values.get('per_page') is not None else",
"try: # get the register length from the online DB sql = 'SELECT",
"per_page) items = [] for item in conf.db_select(sql): items.append( (item[0], item[1]) ) except",
"for coords in coords_list: points.append(tuple([coords[1], coords[0]])) ave_lat = sum(p[0] for p in points)",
"text)) LIKE '%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%' '''.format(search_string=search_string.strip().upper()) sql += '''ORDER BY \"name\"",
"online DB sql = 'SELECT COUNT(*) FROM \"transportroads\"' if search_string: sql += '''WHERE",
"Roads from pyldapi import ContainerRenderer import conf import ast import folium print(__name__) routes",
"except Exception as e: print(e) return Response('The Roads database is offline', mimetype='text/plain', status=500)",
"= int(request.values.get('per_page')) \\ if request.values.get('per_page') is not None else DEFAULT_ITEMS_PER_PAGE offset = (page",
"def roads(): # Search specific items using keywords search_string = request.values.get('search') try: #",
"offset = (page - 1) * per_page # get the id and name",
"'%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%' '''.format(search_string=search_string.strip().upper()) sql += '''ORDER BY \"name\" OFFSET {}",
"routes = Blueprint('controller', __name__) DEFAULT_ITEMS_PER_PAGE=50 @routes.route('/', strict_slashes=True) def home(): return render_template('home.html') @routes.route('/rds/') def",
"- 1) * per_page # get the id and name for each record",
"request.values.get('per_page') is not None else DEFAULT_ITEMS_PER_PAGE offset = (page - 1) * per_page",
"each record in the database sql = '''SELECT \"id\", \"name\" FROM \"transportroads\"''' if",
"= int(request.values.get('page')) if request.values.get('page') is not None else 1 per_page = int(request.values.get('per_page')) \\",
"tooltip = 'Click for more information' folium.PolyLine(points, color=\"red\", weight=2.5, opacity=1, popup = name,",
"p in points) / len(points) ave_lon = sum(p[1] for p in points) /",
"1) * per_page # get the id and name for each record in",
"record in the database sql = '''SELECT \"id\", \"name\" FROM \"transportroads\"''' if search_string:",
"is not None else DEFAULT_ITEMS_PER_PAGE offset = (page - 1) * per_page #",
"render a map around the specified line ''' name = request.values.get('name') coords_list =",
"roads(): # Search specific items using keywords search_string = request.values.get('search') try: # get",
"strict_slashes=True) def home(): return render_template('home.html') @routes.route('/rds/') def roads(): # Search specific items using",
"for more information' folium.PolyLine(points, color=\"red\", weight=2.5, opacity=1, popup = name, tooltip=tooltip).add_to(folium_map) return folium_map.get_root().render()",
"'''ORDER BY \"name\" OFFSET {} LIMIT {}'''.format(offset, per_page) items = [] for item",
"= request.values.get('search') try: # get the register length from the online DB sql",
"coords[0]])) ave_lat = sum(p[0] for p in points) / len(points) ave_lon = sum(p[1]",
"LIKE '%{search_string}%' '''.format(search_string=search_string.strip().upper()) sql += '''ORDER BY \"name\" OFFSET {} LIMIT {}'''.format(offset, per_page)",
"if request.values.get('page') is not None else 1 per_page = int(request.values.get('per_page')) \\ if request.values.get('per_page')",
"= sum(p[1] for p in points) / len(points) # create a new map",
"if request.values.get('per_page') is not None else DEFAULT_ITEMS_PER_PAGE offset = (page - 1) *",
"in coords_list: points.append(tuple([coords[1], coords[0]])) ave_lat = sum(p[0] for p in points) / len(points)",
"popup = name, tooltip=tooltip).add_to(folium_map) return folium_map.get_root().render() @routes.route('/rds/<string:roads_id>') def road(roads_id): roads = Roads(request, request.base_url)",
"ContainerRenderer(request=request, instance_uri=request.url, label='Roads Register', comment='A register of Roads', parent_container_uri='http://linked.data.gov.au/def/placenames/PlaceName', parent_container_label='QLD_Roads', members=items, members_total_count=no_of_items, profiles=None,",
"points.append(tuple([coords[1], coords[0]])) ave_lat = sum(p[0] for p in points) / len(points) ave_lon =",
"and name for each record in the database sql = '''SELECT \"id\", \"name\"",
"OFFSET {} LIMIT {}'''.format(offset, per_page) items = [] for item in conf.db_select(sql): items.append(",
"search_string: sql += '''WHERE UPPER(cast(\"id\" as text)) LIKE '%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%'",
"search_string: sql += '''WHERE UPPER(cast(\"id\" as text)) LIKE '%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%';",
"Blueprint('controller', __name__) DEFAULT_ITEMS_PER_PAGE=50 @routes.route('/', strict_slashes=True) def home(): return render_template('home.html') @routes.route('/rds/') def roads(): #",
"BY \"name\" OFFSET {} LIMIT {}'''.format(offset, per_page) items = [] for item in",
"ave_lat = sum(p[0] for p in points) / len(points) ave_lon = sum(p[1] for",
"in conf.db_select(sql): items.append( (item[0], item[1]) ) except Exception as e: print(e) return Response('The",
"Blueprint, request, Response, render_template from model.roads import Roads from pyldapi import ContainerRenderer import",
"= request.values.get('name') coords_list = ast.literal_eval(request.values.get('coords'))[0] # swap x & y for mapping points",
"show_map(): ''' Function to render a map around the specified line ''' name",
"''' Function to render a map around the specified line ''' name =",
"len(points) ave_lon = sum(p[1] for p in points) / len(points) # create a",
"request.values.get('search') try: # get the register length from the online DB sql =",
"sql += '''ORDER BY \"name\" OFFSET {} LIMIT {}'''.format(offset, per_page) items = []",
"= folium.Map(location=[ave_lat, ave_lon], zoom_start=15) tooltip = 'Click for more information' folium.PolyLine(points, color=\"red\", weight=2.5,",
"Roads', parent_container_uri='http://linked.data.gov.au/def/placenames/PlaceName', parent_container_label='QLD_Roads', members=items, members_total_count=no_of_items, profiles=None, default_profile_token=None, super_register=None, page_size_max=1000, register_template=None, per_page=per_page, search_query=search_string, search_enabled=True",
"parent_container_uri='http://linked.data.gov.au/def/placenames/PlaceName', parent_container_label='QLD_Roads', members=items, members_total_count=no_of_items, profiles=None, default_profile_token=None, super_register=None, page_size_max=1000, register_template=None, per_page=per_page, search_query=search_string, search_enabled=True ).render()",
"render_template from model.roads import Roads from pyldapi import ContainerRenderer import conf import ast",
"{}'''.format(offset, per_page) items = [] for item in conf.db_select(sql): items.append( (item[0], item[1]) )",
"page_size_max=1000, register_template=None, per_page=per_page, search_query=search_string, search_enabled=True ).render() @routes.route('/map') def show_map(): ''' Function to render",
"from model.roads import Roads from pyldapi import ContainerRenderer import conf import ast import",
"None else DEFAULT_ITEMS_PER_PAGE offset = (page - 1) * per_page # get the",
"sql += '''WHERE UPPER(cast(\"id\" as text)) LIKE '%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%' '''.format(search_string=search_string.strip().upper())",
"{} LIMIT {}'''.format(offset, per_page) items = [] for item in conf.db_select(sql): items.append( (item[0],",
"sql += '''WHERE UPPER(cast(\"id\" as text)) LIKE '%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%'; '''.format(search_string=search_string.strip().upper())",
") except Exception as e: print(e) return Response('The Roads database is offline', mimetype='text/plain',",
"as text)) LIKE '%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%'; '''.format(search_string=search_string.strip().upper()) no_of_items = conf.db_select(sql)[0][0] page",
"Search specific items using keywords search_string = request.values.get('search') try: # get the register",
"+= '''ORDER BY \"name\" OFFSET {} LIMIT {}'''.format(offset, per_page) items = [] for",
"Response('The Roads database is offline', mimetype='text/plain', status=500) return ContainerRenderer(request=request, instance_uri=request.url, label='Roads Register', comment='A",
"int(request.values.get('page')) if request.values.get('page') is not None else 1 per_page = int(request.values.get('per_page')) \\ if",
"1 per_page = int(request.values.get('per_page')) \\ if request.values.get('per_page') is not None else DEFAULT_ITEMS_PER_PAGE offset",
"+= '''WHERE UPPER(cast(\"id\" as text)) LIKE '%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%' '''.format(search_string=search_string.strip().upper()) sql",
"is offline', mimetype='text/plain', status=500) return ContainerRenderer(request=request, instance_uri=request.url, label='Roads Register', comment='A register of Roads',",
"in points) / len(points) # create a new map object folium_map = folium.Map(location=[ave_lat,",
"LIKE '%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%' '''.format(search_string=search_string.strip().upper()) sql += '''ORDER BY \"name\" OFFSET",
"the database sql = '''SELECT \"id\", \"name\" FROM \"transportroads\"''' if search_string: sql +=",
"ast import folium print(__name__) routes = Blueprint('controller', __name__) DEFAULT_ITEMS_PER_PAGE=50 @routes.route('/', strict_slashes=True) def home():",
"from pyldapi import ContainerRenderer import conf import ast import folium print(__name__) routes =",
"LIMIT {}'''.format(offset, per_page) items = [] for item in conf.db_select(sql): items.append( (item[0], item[1])",
"map object folium_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=15) tooltip = 'Click for more information'",
"e: print(e) return Response('The Roads database is offline', mimetype='text/plain', status=500) return ContainerRenderer(request=request, instance_uri=request.url,",
"__name__) DEFAULT_ITEMS_PER_PAGE=50 @routes.route('/', strict_slashes=True) def home(): return render_template('home.html') @routes.route('/rds/') def roads(): # Search",
"print(__name__) routes = Blueprint('controller', __name__) DEFAULT_ITEMS_PER_PAGE=50 @routes.route('/', strict_slashes=True) def home(): return render_template('home.html') @routes.route('/rds/')",
"/ len(points) # create a new map object folium_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=15)",
"# swap x & y for mapping points = [] for coords in",
"@routes.route('/map') def show_map(): ''' Function to render a map around the specified line",
"not None else DEFAULT_ITEMS_PER_PAGE offset = (page - 1) * per_page # get",
"UPPER(cast(\"id\" as text)) LIKE '%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%' '''.format(search_string=search_string.strip().upper()) sql += '''ORDER",
"instance_uri=request.url, label='Roads Register', comment='A register of Roads', parent_container_uri='http://linked.data.gov.au/def/placenames/PlaceName', parent_container_label='QLD_Roads', members=items, members_total_count=no_of_items, profiles=None, default_profile_token=None,",
"a new map object folium_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=15) tooltip = 'Click for",
"LIKE '%{search_string}%'; '''.format(search_string=search_string.strip().upper()) no_of_items = conf.db_select(sql)[0][0] page = int(request.values.get('page')) if request.values.get('page') is not",
"in the database sql = '''SELECT \"id\", \"name\" FROM \"transportroads\"''' if search_string: sql",
"the specified line ''' name = request.values.get('name') coords_list = ast.literal_eval(request.values.get('coords'))[0] # swap x",
"Register', comment='A register of Roads', parent_container_uri='http://linked.data.gov.au/def/placenames/PlaceName', parent_container_label='QLD_Roads', members=items, members_total_count=no_of_items, profiles=None, default_profile_token=None, super_register=None, page_size_max=1000,",
"= [] for coords in coords_list: points.append(tuple([coords[1], coords[0]])) ave_lat = sum(p[0] for p",
"for mapping points = [] for coords in coords_list: points.append(tuple([coords[1], coords[0]])) ave_lat =",
"map around the specified line ''' name = request.values.get('name') coords_list = ast.literal_eval(request.values.get('coords'))[0] #",
"# get the id and name for each record in the database sql",
"coords in coords_list: points.append(tuple([coords[1], coords[0]])) ave_lat = sum(p[0] for p in points) /",
"object folium_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=15) tooltip = 'Click for more information' folium.PolyLine(points,",
"weight=2.5, opacity=1, popup = name, tooltip=tooltip).add_to(folium_map) return folium_map.get_root().render() @routes.route('/rds/<string:roads_id>') def road(roads_id): roads =",
"ave_lon = sum(p[1] for p in points) / len(points) # create a new",
"folium.PolyLine(points, color=\"red\", weight=2.5, opacity=1, popup = name, tooltip=tooltip).add_to(folium_map) return folium_map.get_root().render() @routes.route('/rds/<string:roads_id>') def road(roads_id):",
"COUNT(*) FROM \"transportroads\"' if search_string: sql += '''WHERE UPPER(cast(\"id\" as text)) LIKE '%{search_string}%'",
"\"name\" FROM \"transportroads\"''' if search_string: sql += '''WHERE UPPER(cast(\"id\" as text)) LIKE '%{search_string}%'",
"folium print(__name__) routes = Blueprint('controller', __name__) DEFAULT_ITEMS_PER_PAGE=50 @routes.route('/', strict_slashes=True) def home(): return render_template('home.html')",
"swap x & y for mapping points = [] for coords in coords_list:",
"'%{search_string}%'; '''.format(search_string=search_string.strip().upper()) no_of_items = conf.db_select(sql)[0][0] page = int(request.values.get('page')) if request.values.get('page') is not None",
"the id and name for each record in the database sql = '''SELECT",
"not None else 1 per_page = int(request.values.get('per_page')) \\ if request.values.get('per_page') is not None",
"\"transportroads\"' if search_string: sql += '''WHERE UPPER(cast(\"id\" as text)) LIKE '%{search_string}%' OR UPPER(\"name\")",
"database is offline', mimetype='text/plain', status=500) return ContainerRenderer(request=request, instance_uri=request.url, label='Roads Register', comment='A register of",
"of Roads', parent_container_uri='http://linked.data.gov.au/def/placenames/PlaceName', parent_container_label='QLD_Roads', members=items, members_total_count=no_of_items, profiles=None, default_profile_token=None, super_register=None, page_size_max=1000, register_template=None, per_page=per_page, search_query=search_string,",
"parent_container_label='QLD_Roads', members=items, members_total_count=no_of_items, profiles=None, default_profile_token=None, super_register=None, page_size_max=1000, register_template=None, per_page=per_page, search_query=search_string, search_enabled=True ).render() @routes.route('/map')",
"page = int(request.values.get('page')) if request.values.get('page') is not None else 1 per_page = int(request.values.get('per_page'))",
"text)) LIKE '%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%'; '''.format(search_string=search_string.strip().upper()) no_of_items = conf.db_select(sql)[0][0] page =",
"name for each record in the database sql = '''SELECT \"id\", \"name\" FROM",
"coords_list: points.append(tuple([coords[1], coords[0]])) ave_lat = sum(p[0] for p in points) / len(points) ave_lon",
"= 'Click for more information' folium.PolyLine(points, color=\"red\", weight=2.5, opacity=1, popup = name, tooltip=tooltip).add_to(folium_map)",
"FROM \"transportroads\"''' if search_string: sql += '''WHERE UPPER(cast(\"id\" as text)) LIKE '%{search_string}%' OR",
"from flask import Blueprint, request, Response, render_template from model.roads import Roads from pyldapi",
"OR UPPER(\"name\") LIKE '%{search_string}%' '''.format(search_string=search_string.strip().upper()) sql += '''ORDER BY \"name\" OFFSET {} LIMIT",
"Response, render_template from model.roads import Roads from pyldapi import ContainerRenderer import conf import",
"ast.literal_eval(request.values.get('coords'))[0] # swap x & y for mapping points = [] for coords",
"= 'SELECT COUNT(*) FROM \"transportroads\"' if search_string: sql += '''WHERE UPPER(cast(\"id\" as text))",
"super_register=None, page_size_max=1000, register_template=None, per_page=per_page, search_query=search_string, search_enabled=True ).render() @routes.route('/map') def show_map(): ''' Function to",
"= ast.literal_eval(request.values.get('coords'))[0] # swap x & y for mapping points = [] for",
"members=items, members_total_count=no_of_items, profiles=None, default_profile_token=None, super_register=None, page_size_max=1000, register_template=None, per_page=per_page, search_query=search_string, search_enabled=True ).render() @routes.route('/map') def",
"\\ if request.values.get('per_page') is not None else DEFAULT_ITEMS_PER_PAGE offset = (page - 1)",
"around the specified line ''' name = request.values.get('name') coords_list = ast.literal_eval(request.values.get('coords'))[0] # swap",
"'Click for more information' folium.PolyLine(points, color=\"red\", weight=2.5, opacity=1, popup = name, tooltip=tooltip).add_to(folium_map) return",
"render_template('home.html') @routes.route('/rds/') def roads(): # Search specific items using keywords search_string = request.values.get('search')",
"'''.format(search_string=search_string.strip().upper()) no_of_items = conf.db_select(sql)[0][0] page = int(request.values.get('page')) if request.values.get('page') is not None else",
"import conf import ast import folium print(__name__) routes = Blueprint('controller', __name__) DEFAULT_ITEMS_PER_PAGE=50 @routes.route('/',",
"model.roads import Roads from pyldapi import ContainerRenderer import conf import ast import folium",
"conf import ast import folium print(__name__) routes = Blueprint('controller', __name__) DEFAULT_ITEMS_PER_PAGE=50 @routes.route('/', strict_slashes=True)",
"request, Response, render_template from model.roads import Roads from pyldapi import ContainerRenderer import conf",
"a map around the specified line ''' name = request.values.get('name') coords_list = ast.literal_eval(request.values.get('coords'))[0]",
"# get the register length from the online DB sql = 'SELECT COUNT(*)",
"points) / len(points) ave_lon = sum(p[1] for p in points) / len(points) #",
"def home(): return render_template('home.html') @routes.route('/rds/') def roads(): # Search specific items using keywords",
"register of Roads', parent_container_uri='http://linked.data.gov.au/def/placenames/PlaceName', parent_container_label='QLD_Roads', members=items, members_total_count=no_of_items, profiles=None, default_profile_token=None, super_register=None, page_size_max=1000, register_template=None, per_page=per_page,",
"ave_lon], zoom_start=15) tooltip = 'Click for more information' folium.PolyLine(points, color=\"red\", weight=2.5, opacity=1, popup",
"sum(p[0] for p in points) / len(points) ave_lon = sum(p[1] for p in",
"name, tooltip=tooltip).add_to(folium_map) return folium_map.get_root().render() @routes.route('/rds/<string:roads_id>') def road(roads_id): roads = Roads(request, request.base_url) return roads.render()",
"/ len(points) ave_lon = sum(p[1] for p in points) / len(points) # create",
"(page - 1) * per_page # get the id and name for each",
"else DEFAULT_ITEMS_PER_PAGE offset = (page - 1) * per_page # get the id",
"sql = '''SELECT \"id\", \"name\" FROM \"transportroads\"''' if search_string: sql += '''WHERE UPPER(cast(\"id\"",
"for item in conf.db_select(sql): items.append( (item[0], item[1]) ) except Exception as e: print(e)",
"sum(p[1] for p in points) / len(points) # create a new map object",
"return Response('The Roads database is offline', mimetype='text/plain', status=500) return ContainerRenderer(request=request, instance_uri=request.url, label='Roads Register',",
"sql = 'SELECT COUNT(*) FROM \"transportroads\"' if search_string: sql += '''WHERE UPPER(cast(\"id\" as",
").render() @routes.route('/map') def show_map(): ''' Function to render a map around the specified",
"the online DB sql = 'SELECT COUNT(*) FROM \"transportroads\"' if search_string: sql +=",
"FROM \"transportroads\"' if search_string: sql += '''WHERE UPPER(cast(\"id\" as text)) LIKE '%{search_string}%' OR",
"'''SELECT \"id\", \"name\" FROM \"transportroads\"''' if search_string: sql += '''WHERE UPPER(cast(\"id\" as text))",
"# create a new map object folium_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=15) tooltip =",
"''' name = request.values.get('name') coords_list = ast.literal_eval(request.values.get('coords'))[0] # swap x & y for",
"new map object folium_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=15) tooltip = 'Click for more",
"'%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%'; '''.format(search_string=search_string.strip().upper()) no_of_items = conf.db_select(sql)[0][0] page = int(request.values.get('page')) if",
"print(e) return Response('The Roads database is offline', mimetype='text/plain', status=500) return ContainerRenderer(request=request, instance_uri=request.url, label='Roads",
"= name, tooltip=tooltip).add_to(folium_map) return folium_map.get_root().render() @routes.route('/rds/<string:roads_id>') def road(roads_id): roads = Roads(request, request.base_url) return",
"length from the online DB sql = 'SELECT COUNT(*) FROM \"transportroads\"' if search_string:",
"as e: print(e) return Response('The Roads database is offline', mimetype='text/plain', status=500) return ContainerRenderer(request=request,",
"to render a map around the specified line ''' name = request.values.get('name') coords_list",
"folium_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=15) tooltip = 'Click for more information' folium.PolyLine(points, color=\"red\",",
"flask import Blueprint, request, Response, render_template from model.roads import Roads from pyldapi import",
"register length from the online DB sql = 'SELECT COUNT(*) FROM \"transportroads\"' if",
"= '''SELECT \"id\", \"name\" FROM \"transportroads\"''' if search_string: sql += '''WHERE UPPER(cast(\"id\" as",
"get the register length from the online DB sql = 'SELECT COUNT(*) FROM",
"'''WHERE UPPER(cast(\"id\" as text)) LIKE '%{search_string}%' OR UPPER(\"name\") LIKE '%{search_string}%'; '''.format(search_string=search_string.strip().upper()) no_of_items =",
"UPPER(\"name\") LIKE '%{search_string}%' '''.format(search_string=search_string.strip().upper()) sql += '''ORDER BY \"name\" OFFSET {} LIMIT {}'''.format(offset,",
"[] for item in conf.db_select(sql): items.append( (item[0], item[1]) ) except Exception as e:",
"\"name\" OFFSET {} LIMIT {}'''.format(offset, per_page) items = [] for item in conf.db_select(sql):",
"label='Roads Register', comment='A register of Roads', parent_container_uri='http://linked.data.gov.au/def/placenames/PlaceName', parent_container_label='QLD_Roads', members=items, members_total_count=no_of_items, profiles=None, default_profile_token=None, super_register=None,",
"for p in points) / len(points) # create a new map object folium_map",
"Roads database is offline', mimetype='text/plain', status=500) return ContainerRenderer(request=request, instance_uri=request.url, label='Roads Register', comment='A register",
"name = request.values.get('name') coords_list = ast.literal_eval(request.values.get('coords'))[0] # swap x & y for mapping",
"pyldapi import ContainerRenderer import conf import ast import folium print(__name__) routes = Blueprint('controller',",
"profiles=None, default_profile_token=None, super_register=None, page_size_max=1000, register_template=None, per_page=per_page, search_query=search_string, search_enabled=True ).render() @routes.route('/map') def show_map(): '''",
"keywords search_string = request.values.get('search') try: # get the register length from the online",
"if search_string: sql += '''WHERE UPPER(cast(\"id\" as text)) LIKE '%{search_string}%' OR UPPER(\"name\") LIKE",
"request.values.get('page') is not None else 1 per_page = int(request.values.get('per_page')) \\ if request.values.get('per_page') is",
"items = [] for item in conf.db_select(sql): items.append( (item[0], item[1]) ) except Exception",
"specified line ''' name = request.values.get('name') coords_list = ast.literal_eval(request.values.get('coords'))[0] # swap x &",
"'''.format(search_string=search_string.strip().upper()) sql += '''ORDER BY \"name\" OFFSET {} LIMIT {}'''.format(offset, per_page) items =",
"\"transportroads\"''' if search_string: sql += '''WHERE UPPER(cast(\"id\" as text)) LIKE '%{search_string}%' OR UPPER(\"name\")",
"folium.Map(location=[ave_lat, ave_lon], zoom_start=15) tooltip = 'Click for more information' folium.PolyLine(points, color=\"red\", weight=2.5, opacity=1,",
"from the online DB sql = 'SELECT COUNT(*) FROM \"transportroads\"' if search_string: sql",
"in points) / len(points) ave_lon = sum(p[1] for p in points) / len(points)",
"DEFAULT_ITEMS_PER_PAGE offset = (page - 1) * per_page # get the id and",
"= sum(p[0] for p in points) / len(points) ave_lon = sum(p[1] for p",
"DEFAULT_ITEMS_PER_PAGE=50 @routes.route('/', strict_slashes=True) def home(): return render_template('home.html') @routes.route('/rds/') def roads(): # Search specific",
"the register length from the online DB sql = 'SELECT COUNT(*) FROM \"transportroads\"'",
"[] for coords in coords_list: points.append(tuple([coords[1], coords[0]])) ave_lat = sum(p[0] for p in",
"p in points) / len(points) # create a new map object folium_map =",
"\"id\", \"name\" FROM \"transportroads\"''' if search_string: sql += '''WHERE UPPER(cast(\"id\" as text)) LIKE",
"Exception as e: print(e) return Response('The Roads database is offline', mimetype='text/plain', status=500) return",
"request.values.get('name') coords_list = ast.literal_eval(request.values.get('coords'))[0] # swap x & y for mapping points =",
"opacity=1, popup = name, tooltip=tooltip).add_to(folium_map) return folium_map.get_root().render() @routes.route('/rds/<string:roads_id>') def road(roads_id): roads = Roads(request,",
"specific items using keywords search_string = request.values.get('search') try: # get the register length",
"members_total_count=no_of_items, profiles=None, default_profile_token=None, super_register=None, page_size_max=1000, register_template=None, per_page=per_page, search_query=search_string, search_enabled=True ).render() @routes.route('/map') def show_map():",
"using keywords search_string = request.values.get('search') try: # get the register length from the",
"default_profile_token=None, super_register=None, page_size_max=1000, register_template=None, per_page=per_page, search_query=search_string, search_enabled=True ).render() @routes.route('/map') def show_map(): ''' Function"
] |
[
"Team - Sheldon, Martin, Brian, Sarah, Veronica. \"\"\" from django.urls import re_path from",
"re_path from .consumers import ChatConsumer # Assign pattern to activate selected websocket websocket_urlpatterns",
"import ChatConsumer # Assign pattern to activate selected websocket websocket_urlpatterns = [ re_path(r'^ws/chat/(?P<room_name>[^/]+)/$',",
"Sheldon, Martin, Brian, Sarah, Veronica. \"\"\" from django.urls import re_path from .consumers import",
"Backend/Server Team - Sheldon, Martin, Brian, Sarah, Veronica. \"\"\" from django.urls import re_path",
"import re_path from .consumers import ChatConsumer # Assign pattern to activate selected websocket",
"Veronica. \"\"\" from django.urls import re_path from .consumers import ChatConsumer # Assign pattern",
"# Assign pattern to activate selected websocket websocket_urlpatterns = [ re_path(r'^ws/chat/(?P<room_name>[^/]+)/$', ChatConsumer), ]",
"Prepared by Backend/Server Team - Sheldon, Martin, Brian, Sarah, Veronica. \"\"\" from django.urls",
"from .consumers import ChatConsumer # Assign pattern to activate selected websocket websocket_urlpatterns =",
"Martin, Brian, Sarah, Veronica. \"\"\" from django.urls import re_path from .consumers import ChatConsumer",
"from django.urls import re_path from .consumers import ChatConsumer # Assign pattern to activate",
".consumers import ChatConsumer # Assign pattern to activate selected websocket websocket_urlpatterns = [",
"\"\"\" from django.urls import re_path from .consumers import ChatConsumer # Assign pattern to",
"django.urls import re_path from .consumers import ChatConsumer # Assign pattern to activate selected",
"- Sheldon, Martin, Brian, Sarah, Veronica. \"\"\" from django.urls import re_path from .consumers",
"by Backend/Server Team - Sheldon, Martin, Brian, Sarah, Veronica. \"\"\" from django.urls import",
"ChatConsumer # Assign pattern to activate selected websocket websocket_urlpatterns = [ re_path(r'^ws/chat/(?P<room_name>[^/]+)/$', ChatConsumer),",
"\"\"\" Prepared by Backend/Server Team - Sheldon, Martin, Brian, Sarah, Veronica. \"\"\" from",
"Sarah, Veronica. \"\"\" from django.urls import re_path from .consumers import ChatConsumer # Assign",
"Brian, Sarah, Veronica. \"\"\" from django.urls import re_path from .consumers import ChatConsumer #"
] |
[
"main(): logging.basicConfig(level=logging.DEBUG) args = get_args() instance_info = ebs.get_instance_info(args.instance_id) resource_state = ResourceState(args, instance_info) resource_state.survey()",
"'created' else: logger.info('Did not find any available volumes. Searching for a ' 'suitable",
"self.state = 'created' else: logger.info('Did not find any available volumes. Searching for a",
"raise ValueError('Value must be positive: {}'.format(n)) return n def key_tag_pair(s): if isinstance(s, bytes):",
"snapshot: snapshot_id = snapshot['SnapshotId'] logger.info( 'Found volume %s in AZ %s, will attempt",
"a volume available in a different AZ than the \" \"current one, instead",
"self.state = 'attached' self.volume_id = random.choice(volumes)['VolumeId'] return if self.args.move_to_current_az: logger.info('Did not find any",
"volume from scratch.') self.state = 'created' else: logger.info('Did not find any available volumes.",
"kms_key_id=self.args.encrypt_kms_key_id, src_snapshot_id=self.snapshot_id) self.volume_id = new_volume['VolumeId'] if not self.attached_device: self.attached_device = ebs.attach_volume( volume_id=self.volume_id, instance_info=self.instance_info,",
"'--snapshot-search-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag used to identify snapshots to create new",
"s = str(s, 'utf-8') elif not isinstance(s, str): raise TypeError('Input must be a",
"attempt to move ' 'it to current AZ %s. Using snapshot %s.', old_volume_id,",
"AND condition.') argp.add_argument( '--attach-device', metavar='PATH|auto', required=True, help='Name of device to use when attaching",
"AZ') other_az_volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=False) for old_volume in other_az_volumes: old_volume_id =",
"snapshot and snapshot['SnapshotId'] def converge(self): if not self.volume_id: availability_zone = \\ self.instance_info['Placement']['AvailabilityZone'] logger.info('About",
"self.state, 'src_snapshot_id': self.snapshot_id} def main(): logging.basicConfig(level=logging.DEBUG) args = get_args() instance_info = ebs.get_instance_info(args.instance_id) resource_state",
"AWS EBS volumes from snapshots') argp.add_argument( '--instance-id', metavar='ID', required=True, help='Instance ID to attach",
"a volume, such as ' '\"/dev/sdb\". Can be set to \"auto\" to use",
"else: logger.info('Creating volume from snapshot %s', self.snapshot_id) new_volume = ebs.create_volume( id_tags=self.args.volume_id_tag, extra_tags=self.args.volume_extra_tag, availability_zone=availability_zone,",
"# pragma: no cover argp = argparse.ArgumentParser( 'ebs-snatcher', description='Automatically provision AWS EBS volumes",
"raise TypeError('Input must be a string') try: key, value = s.split('=', 1) except",
"instance_info) resource_state.survey() resource_state.converge() print(json.dumps(resource_state.to_json())) return 0 if __name__ == '__main__': main() # pragma:",
"available volumes in current AZ. ' 'Searching for available volumes to move in",
"create volumes, but which are ' 'not used for identification') argp.add_argument( '--encrypt-kms-key-id', metavar='KEY-ID',",
"identification') argp.add_argument( '--encrypt-kms-key-id', metavar='KEY-ID', default=None, help='Enable encryption and use the given KMS key",
"type=key_tag_pair, required=True, action='append', help='Tag used to identify desired volumes. Will be used to",
"argp.add_argument( '--snapshot-search-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag used to identify snapshots to create",
"tags will be ' 'combined as an AND condition.') argp.add_argument( '--attach-device', metavar='PATH|auto', required=True,",
"', '.join(map(lambda v: v['VolumeId'], volumes))) self.state = 'attached' self.volume_id = random.choice(volumes)['VolumeId'] return if",
"%s', ', '.join(map(lambda v: v['VolumeId'], volumes))) self.state = 'attached' self.volume_id = random.choice(volumes)['VolumeId'] return",
"return key, value class ResourceState(object): def __init__(self, args, instance_info): self.args = args self.instance_info",
"str, bytes import argparse import json import logging import random from . import",
"attaching a volume, such as ' '\"/dev/sdb\". Can be set to \"auto\" to",
"= \\ ebs.find_system_block_device(self.volume_id, self.attached_device) if self.old_volume_id: ebs.delete_volume(volume_id=self.old_volume_id) def to_json(self): return {'volume_id': self.volume_id, 'attached_device':",
"AZ %s. Using snapshot %s.', old_volume_id, old_az, new_az, snapshot_id) self.state = 'created' self.snapshot_id",
"builtins import str, bytes import argparse import json import logging import random from",
"'created' self.snapshot_id = snapshot and snapshot['SnapshotId'] def converge(self): if not self.volume_id: availability_zone =",
"given specifications in current ' 'AZ: %s', ', '.join(map(lambda v: v['VolumeId'], volumes))) self.state",
"with given specifications in current ' 'AZ: %s', ', '.join(map(lambda v: v['VolumeId'], volumes)))",
"such as ' '\"/dev/sdb\". Can be set to \"auto\" to use a safe",
"for a ' 'suitable snapshot instead') snapshot = ebs.find_existing_snapshot( search_tags=self.args.snapshot_search_tag) self.state = 'created'",
"%s', volume_id) self.state = 'present' self.volume_id = volume_id self.attached_device = attached_device return logger.debug('Looking",
"AZ') volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=True) if volumes: logger.info( 'Found available volumes",
"type to ' 'match.') argp.add_argument( '--move-to-current-az', action='store_true', default=False, help=\"If there is a volume",
"'and applied to new volumes. Can be provided multiple times, in ' 'which",
"%s', availability_zone) if not self.snapshot_id: logger.info('Creating volume from scratch') else: logger.info('Creating volume from",
"AZ ' 'move. Creating new volume from scratch.') self.state = 'created' else: logger.info('Did",
"availability_zone) if not self.snapshot_id: logger.info('Creating volume from scratch') else: logger.info('Creating volume from snapshot",
"= 'attached' self.volume_id = random.choice(volumes)['VolumeId'] return if self.args.move_to_current_az: logger.info('Did not find any available",
"= get_args() instance_info = ebs.get_instance_info(args.instance_id) resource_state = ResourceState(args, instance_info) resource_state.survey() resource_state.converge() print(json.dumps(resource_state.to_json())) return",
"be set to \"auto\" to use a safe default. ' 'Device names found",
"argp.add_argument( '--volume-type', metavar='TYPE', choices=ebs.VOLUME_TYPES, default='gp2', help='Volume type to use for newly created volumes')",
"the current AZ, by cloning it and \" \"deleting the original.\") return argp.parse_args()",
"sure to choose an appropriate volume type to ' 'match.') argp.add_argument( '--move-to-current-az', action='store_true',",
"'--instance-id', metavar='ID', required=True, help='Instance ID to attach volumes to') argp.add_argument( '--volume-id-tag', metavar='KEY=VALUE', type=key_tag_pair,",
"to the current AZ, by cloning it and \" \"deleting the original.\") return",
"ebs.attach_volume( volume_id=self.volume_id, instance_info=self.instance_info, device_name=self.args.attach_device) self.attached_device = \\ ebs.find_system_block_device(self.volume_id, self.attached_device) if self.old_volume_id: ebs.delete_volume(volume_id=self.old_volume_id) def",
"= attached_device return logger.debug('Looking up existing available volumes in AZ') volumes = \\",
"argp.add_argument( '--volume-id-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag used to identify desired volumes. Will",
"help='Volume type to use for newly created volumes') argp.add_argument( '--volume-iops', metavar='COUNT', type=positive_int, default=None,",
"instance_info=self.instance_info, device_name=self.args.attach_device) self.attached_device = \\ ebs.find_system_block_device(self.volume_id, self.attached_device) if self.old_volume_id: ebs.delete_volume(volume_id=self.old_volume_id) def to_json(self): return",
"' 'succeeds') argp.add_argument( '--volume-extra-tag', metavar='KEY=VALUE', type=key_tag_pair, action='append', help='Extra tags to be applied to",
"\\ ebs.find_system_block_device(self.volume_id, self.attached_device) if self.old_volume_id: ebs.delete_volume(volume_id=self.old_volume_id) def to_json(self): return {'volume_id': self.volume_id, 'attached_device': self.attached_device,",
"to identify snapshots to create new volumes from.' 'Can be provided multiple times,",
"as ' '\"/dev/sdb\". Can be set to \"auto\" to use a safe default.",
"volume already attached to instance: %s', volume_id) self.state = 'present' self.volume_id = volume_id",
"device to use when attaching a volume, such as ' '\"/dev/sdb\". Can be",
"if not self.snapshot_id: logger.info('Creating volume from scratch') else: logger.info('Creating volume from snapshot %s',",
"logger.info('Did not find any available volumes in other AZ ' 'move. Creating new",
"1) except ValueError: raise ValueError('Missing tag value: {}'.format(s)) return key, value class ResourceState(object):",
"argp.parse_args() def positive_int(s): n = int(s) if n <= 0: raise ValueError('Value must",
"metavar='TYPE', choices=ebs.VOLUME_TYPES, default='gp2', help='Volume type to use for newly created volumes') argp.add_argument( '--volume-iops',",
"assign to newly created volumes, in GBs.') argp.add_argument( '--snapshot-search-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append',",
"in GBs.') argp.add_argument( '--snapshot-search-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag used to identify snapshots",
"to use when attaching a volume, such as ' '\"/dev/sdb\". Can be set",
"= None self.volume_id = None self.old_volume_id = None self.snapshot_id = None self.attached_device =",
"return if self.args.move_to_current_az: logger.info('Did not find any available volumes in current AZ. '",
"s.split('=', 1) except ValueError: raise ValueError('Missing tag value: {}'.format(s)) return key, value class",
"provided multiple times, in which case tags will be ' 'combined as an",
"'Found volume already attached to instance: %s', volume_id) self.state = 'present' self.volume_id =",
"' 'which case tags will be combined as an AND condition.') argp.add_argument( '--volume-size',",
"the \" \"current one, instead of skipping it and looking for snapshots \"",
"alphabetical order will be tried until attachment ' 'succeeds') argp.add_argument( '--volume-extra-tag', metavar='KEY=VALUE', type=key_tag_pair,",
"value: {}'.format(s)) return key, value class ResourceState(object): def __init__(self, args, instance_info): self.args =",
"' 'and applied to new volumes. Can be provided multiple times, in '",
"from . import ebs logger = logging.getLogger('ebs-snatcher.main') def get_args(): # pragma: no cover",
"not find any available volumes. Searching for a ' 'suitable snapshot instead') snapshot",
"snapshot['SnapshotId'] def converge(self): if not self.volume_id: availability_zone = \\ self.instance_info['Placement']['AvailabilityZone'] logger.info('About to create",
"'Searching for available volumes to move in other AZ') other_az_volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag,",
"'not used for identification') argp.add_argument( '--encrypt-kms-key-id', metavar='KEY-ID', default=None, help='Enable encryption and use the",
"self.instance_info, current_az=False) for old_volume in other_az_volumes: old_volume_id = old_volume['VolumeId'] old_az = old_volume['AvailabilityZone'] new_az",
"= args self.instance_info = instance_info self.state = None self.volume_id = None self.old_volume_id =",
"logger.info( 'Found volume %s in AZ %s, will attempt to move ' 'it",
"must be a string') try: key, value = s.split('=', 1) except ValueError: raise",
"created ' 'volumes. Make sure to choose an appropriate volume type to '",
"= logging.getLogger('ebs-snatcher.main') def get_args(): # pragma: no cover argp = argparse.ArgumentParser( 'ebs-snatcher', description='Automatically",
"current_az=True) if volumes: logger.info( 'Found available volumes with given specifications in current '",
"'created' self.snapshot_id = snapshot_id self.old_volume_id = old_volume_id break else: logger.info('Did not find any",
"no cover argp = argparse.ArgumentParser( 'ebs-snatcher', description='Automatically provision AWS EBS volumes from snapshots')",
"logger.info('About to create volume in AZ %s', availability_zone) if not self.snapshot_id: logger.info('Creating volume",
"will be tried until attachment ' 'succeeds') argp.add_argument( '--volume-extra-tag', metavar='KEY=VALUE', type=key_tag_pair, action='append', help='Extra",
"operations to assign to newly created ' 'volumes. Make sure to choose an",
"%s. Using snapshot %s.', old_volume_id, old_az, new_az, snapshot_id) self.state = 'created' self.snapshot_id =",
"condition.') argp.add_argument( '--attach-device', metavar='PATH|auto', required=True, help='Name of device to use when attaching a",
"newly created ' 'volumes. Make sure to choose an appropriate volume type to",
"until attachment ' 'succeeds') argp.add_argument( '--volume-extra-tag', metavar='KEY=VALUE', type=key_tag_pair, action='append', help='Extra tags to be",
"'--volume-type', metavar='TYPE', choices=ebs.VOLUME_TYPES, default='gp2', help='Volume type to use for newly created volumes') argp.add_argument(",
"self.state = 'created' self.snapshot_id = snapshot_id self.old_volume_id = old_volume_id break else: logger.info('Did not",
"tags to be applied to newly create volumes, but which are ' 'not",
"scratch') else: logger.info('Creating volume from snapshot %s', self.snapshot_id) new_volume = ebs.create_volume( id_tags=self.args.volume_id_tag, extra_tags=self.args.volume_extra_tag,",
"which case tags will be ' 'combined as an AND condition.') argp.add_argument( '--attach-device',",
"self.state = None self.volume_id = None self.old_volume_id = None self.snapshot_id = None self.attached_device",
"to determine if a new one is needed ' 'and applied to new",
"instead') snapshot = ebs.find_existing_snapshot( search_tags=self.args.snapshot_search_tag) self.state = 'created' self.snapshot_id = snapshot and snapshot['SnapshotId']",
"new_az = self.instance_info['Placement']['AvailabilityZone'] filters = [{'Name': 'volume-id', 'Values': [old_volume_id]}] snapshot = ebs.find_existing_snapshot(filters=filters) if",
"= ebs.get_instance_info(args.instance_id) resource_state = ResourceState(args, instance_info) resource_state.survey() resource_state.converge() print(json.dumps(resource_state.to_json())) return 0 if __name__",
"Will be used to search ' 'currently attached volumes to determine if a",
"'match.') argp.add_argument( '--move-to-current-az', action='store_true', default=False, help=\"If there is a volume available in a",
"in current AZ. ' 'Searching for available volumes to move in other AZ')",
"for identification') argp.add_argument( '--encrypt-kms-key-id', metavar='KEY-ID', default=None, help='Enable encryption and use the given KMS",
"' '\"/dev/sdb\". Can be set to \"auto\" to use a safe default. '",
"be combined as an AND condition.') argp.add_argument( '--volume-size', metavar='GB', type=positive_int, required=True, help='Size to",
"help='Name of device to use when attaching a volume, such as ' '\"/dev/sdb\".",
"\"deleting the original.\") return argp.parse_args() def positive_int(s): n = int(s) if n <=",
"snapshot %s', self.snapshot_id) new_volume = ebs.create_volume( id_tags=self.args.volume_id_tag, extra_tags=self.args.volume_extra_tag, availability_zone=availability_zone, volume_type=self.args.volume_type, size=self.args.volume_size, iops=self.args.volume_iops, kms_key_id=self.args.encrypt_kms_key_id,",
"if isinstance(s, bytes): s = str(s, 'utf-8') elif not isinstance(s, str): raise TypeError('Input",
"'volumes') argp.add_argument( '--volume-type', metavar='TYPE', choices=ebs.VOLUME_TYPES, default='gp2', help='Volume type to use for newly created",
"volumes with given specifications in current ' 'AZ: %s', ', '.join(map(lambda v: v['VolumeId'],",
"isinstance(s, bytes): s = str(s, 'utf-8') elif not isinstance(s, str): raise TypeError('Input must",
"AZ %s, will attempt to move ' 'it to current AZ %s. Using",
"I/O operations to assign to newly created ' 'volumes. Make sure to choose",
"cloning it and \" \"deleting the original.\") return argp.parse_args() def positive_int(s): n =",
"self.snapshot_id = snapshot and snapshot['SnapshotId'] def converge(self): if not self.volume_id: availability_zone = \\",
"which are ' 'not used for identification') argp.add_argument( '--encrypt-kms-key-id', metavar='KEY-ID', default=None, help='Enable encryption",
"it and \" \"deleting the original.\") return argp.parse_args() def positive_int(s): n = int(s)",
"original.\") return argp.parse_args() def positive_int(s): n = int(s) if n <= 0: raise",
"positive: {}'.format(n)) return n def key_tag_pair(s): if isinstance(s, bytes): s = str(s, 'utf-8')",
"AZ, by cloning it and \" \"deleting the original.\") return argp.parse_args() def positive_int(s):",
"attached_volumes[0]['Attachments'][0]['Device'] logger.info( 'Found volume already attached to instance: %s', volume_id) self.state = 'present'",
"in other AZ ' 'move. Creating new volume from scratch.') self.state = 'created'",
"action='store_true', default=False, help=\"If there is a volume available in a different AZ than",
"else: logger.info('Did not find any available volumes in other AZ ' 'move. Creating",
"self.args.move_to_current_az: logger.info('Did not find any available volumes in current AZ. ' 'Searching for",
"encryption and use the given KMS key ID for newly created ' 'volumes')",
"AND condition.') argp.add_argument( '--volume-size', metavar='GB', type=positive_int, required=True, help='Size to assign to newly created",
"elif not isinstance(s, str): raise TypeError('Input must be a string') try: key, value",
"%s, will attempt to move ' 'it to current AZ %s. Using snapshot",
"__future__ import unicode_literals from builtins import str, bytes import argparse import json import",
"key ID for newly created ' 'volumes') argp.add_argument( '--volume-type', metavar='TYPE', choices=ebs.VOLUME_TYPES, default='gp2', help='Volume",
"argp.add_argument( '--attach-device', metavar='PATH|auto', required=True, help='Name of device to use when attaching a volume,",
"= snapshot_id self.old_volume_id = old_volume_id break else: logger.info('Did not find any available volumes",
"ebs.find_system_block_device(self.volume_id, self.attached_device) if self.old_volume_id: ebs.delete_volume(volume_id=self.old_volume_id) def to_json(self): return {'volume_id': self.volume_id, 'attached_device': self.attached_device, 'result':",
"a different AZ than the \" \"current one, instead of skipping it and",
"= str(s, 'utf-8') elif not isinstance(s, str): raise TypeError('Input must be a string')",
"be used to search ' 'currently attached volumes to determine if a new",
"'succeeds') argp.add_argument( '--volume-extra-tag', metavar='KEY=VALUE', type=key_tag_pair, action='append', help='Extra tags to be applied to newly",
"'--volume-size', metavar='GB', type=positive_int, required=True, help='Size to assign to newly created volumes, in GBs.')",
"' 'volumes') argp.add_argument( '--volume-type', metavar='TYPE', choices=ebs.VOLUME_TYPES, default='gp2', help='Volume type to use for newly",
"current_az=False) for old_volume in other_az_volumes: old_volume_id = old_volume['VolumeId'] old_az = old_volume['AvailabilityZone'] new_az =",
"snapshots') argp.add_argument( '--instance-id', metavar='ID', required=True, help='Instance ID to attach volumes to') argp.add_argument( '--volume-id-tag',",
"logger.info('Creating volume from scratch') else: logger.info('Creating volume from snapshot %s', self.snapshot_id) new_volume =",
"= ebs.attach_volume( volume_id=self.volume_id, instance_info=self.instance_info, device_name=self.args.attach_device) self.attached_device = \\ ebs.find_system_block_device(self.volume_id, self.attached_device) if self.old_volume_id: ebs.delete_volume(volume_id=self.old_volume_id)",
"\"current one, instead of skipping it and looking for snapshots \" \"by tag,",
"not self.snapshot_id: logger.info('Creating volume from scratch') else: logger.info('Creating volume from snapshot %s', self.snapshot_id)",
"times, in which case tags will be ' 'combined as an AND condition.')",
"metavar='KEY=VALUE', type=key_tag_pair, action='append', help='Extra tags to be applied to newly create volumes, but",
"volume_id self.attached_device = attached_device return logger.debug('Looking up existing available volumes in AZ') volumes",
"volumes in other AZ ' 'move. Creating new volume from scratch.') self.state =",
"self.volume_id: availability_zone = \\ self.instance_info['Placement']['AvailabilityZone'] logger.info('About to create volume in AZ %s', availability_zone)",
"applied to new volumes. Can be provided multiple times, in ' 'which case",
"an AND condition.') argp.add_argument( '--attach-device', metavar='PATH|auto', required=True, help='Name of device to use when",
"be skipped, and the ' 'next name in alphabetical order will be tried",
"skipping it and looking for snapshots \" \"by tag, try to move it",
"newly created ' 'volumes') argp.add_argument( '--volume-type', metavar='TYPE', choices=ebs.VOLUME_TYPES, default='gp2', help='Volume type to use",
"'--move-to-current-az', action='store_true', default=False, help=\"If there is a volume available in a different AZ",
"__init__(self, args, instance_info): self.args = args self.instance_info = instance_info self.state = None self.volume_id",
"current AZ. ' 'Searching for available volumes to move in other AZ') other_az_volumes",
"try: key, value = s.split('=', 1) except ValueError: raise ValueError('Missing tag value: {}'.format(s))",
"old_volume in other_az_volumes: old_volume_id = old_volume['VolumeId'] old_az = old_volume['AvailabilityZone'] new_az = self.instance_info['Placement']['AvailabilityZone'] filters",
"argparse import json import logging import random from . import ebs logger =",
"find any available volumes. Searching for a ' 'suitable snapshot instead') snapshot =",
"snapshot instead') snapshot = ebs.find_existing_snapshot( search_tags=self.args.snapshot_search_tag) self.state = 'created' self.snapshot_id = snapshot and",
"order will be tried until attachment ' 'succeeds') argp.add_argument( '--volume-extra-tag', metavar='KEY=VALUE', type=key_tag_pair, action='append',",
"int(s) if n <= 0: raise ValueError('Value must be positive: {}'.format(n)) return n",
"be provided multiple times, in ' 'which case tags will be combined as",
"for old_volume in other_az_volumes: old_volume_id = old_volume['VolumeId'] old_az = old_volume['AvailabilityZone'] new_az = self.instance_info['Placement']['AvailabilityZone']",
"%s in AZ %s, will attempt to move ' 'it to current AZ",
"safe default. ' 'Device names found to be already in use will be",
"self.attached_device = ebs.attach_volume( volume_id=self.volume_id, instance_info=self.instance_info, device_name=self.args.attach_device) self.attached_device = \\ ebs.find_system_block_device(self.volume_id, self.attached_device) if self.old_volume_id:",
"str(s, 'utf-8') elif not isinstance(s, str): raise TypeError('Input must be a string') try:",
"volumes to move in other AZ') other_az_volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=False) for",
"a string') try: key, value = s.split('=', 1) except ValueError: raise ValueError('Missing tag",
"KMS key ID for newly created ' 'volumes') argp.add_argument( '--volume-type', metavar='TYPE', choices=ebs.VOLUME_TYPES, default='gp2',",
"None def survey(self): logger.debug('Looking up currently attached volumes') attached_volumes = \\ ebs.find_attached_volumes(self.args.volume_id_tag, self.instance_info)",
"scratch.') self.state = 'created' else: logger.info('Did not find any available volumes. Searching for",
"it to the current AZ, by cloning it and \" \"deleting the original.\")",
"be already in use will be skipped, and the ' 'next name in",
"self.old_volume_id = old_volume_id break else: logger.info('Did not find any available volumes in other",
"volumes to determine if a new one is needed ' 'and applied to",
"self.snapshot_id = snapshot_id self.old_volume_id = old_volume_id break else: logger.info('Did not find any available",
"multiple times, in ' 'which case tags will be combined as an AND",
"to newly created ' 'volumes. Make sure to choose an appropriate volume type",
"type to use for newly created volumes') argp.add_argument( '--volume-iops', metavar='COUNT', type=positive_int, default=None, help='Number",
"import ebs logger = logging.getLogger('ebs-snatcher.main') def get_args(): # pragma: no cover argp =",
"get_args() instance_info = ebs.get_instance_info(args.instance_id) resource_state = ResourceState(args, instance_info) resource_state.survey() resource_state.converge() print(json.dumps(resource_state.to_json())) return 0",
"if not self.volume_id: availability_zone = \\ self.instance_info['Placement']['AvailabilityZone'] logger.info('About to create volume in AZ",
"combined as an AND condition.') argp.add_argument( '--volume-size', metavar='GB', type=positive_int, required=True, help='Size to assign",
"default=None, help='Enable encryption and use the given KMS key ID for newly created",
"from snapshot %s', self.snapshot_id) new_volume = ebs.create_volume( id_tags=self.args.volume_id_tag, extra_tags=self.args.volume_extra_tag, availability_zone=availability_zone, volume_type=self.args.volume_type, size=self.args.volume_size, iops=self.args.volume_iops,",
"in which case tags will be ' 'combined as an AND condition.') argp.add_argument(",
"given KMS key ID for newly created ' 'volumes') argp.add_argument( '--volume-type', metavar='TYPE', choices=ebs.VOLUME_TYPES,",
"' 'AZ: %s', ', '.join(map(lambda v: v['VolumeId'], volumes))) self.state = 'attached' self.volume_id =",
"move in other AZ') other_az_volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=False) for old_volume in",
"[old_volume_id]}] snapshot = ebs.find_existing_snapshot(filters=filters) if snapshot: snapshot_id = snapshot['SnapshotId'] logger.info( 'Found volume %s",
"new one is needed ' 'and applied to new volumes. Can be provided",
"<reponame>Cobliteam/ebs_snatcher from __future__ import unicode_literals from builtins import str, bytes import argparse import",
"newly created volumes') argp.add_argument( '--volume-iops', metavar='COUNT', type=positive_int, default=None, help='Number of provisioned I/O operations",
"str): raise TypeError('Input must be a string') try: key, value = s.split('=', 1)",
"other_az_volumes: old_volume_id = old_volume['VolumeId'] old_az = old_volume['AvailabilityZone'] new_az = self.instance_info['Placement']['AvailabilityZone'] filters = [{'Name':",
"volume available in a different AZ than the \" \"current one, instead of",
"self.snapshot_id = None self.attached_device = None def survey(self): logger.debug('Looking up currently attached volumes')",
"ebs logger = logging.getLogger('ebs-snatcher.main') def get_args(): # pragma: no cover argp = argparse.ArgumentParser(",
"def to_json(self): return {'volume_id': self.volume_id, 'attached_device': self.attached_device, 'result': self.state, 'src_snapshot_id': self.snapshot_id} def main():",
"\\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=True) if volumes: logger.info( 'Found available volumes with given specifications",
"value class ResourceState(object): def __init__(self, args, instance_info): self.args = args self.instance_info = instance_info",
"if n <= 0: raise ValueError('Value must be positive: {}'.format(n)) return n def",
"'ebs-snatcher', description='Automatically provision AWS EBS volumes from snapshots') argp.add_argument( '--instance-id', metavar='ID', required=True, help='Instance",
"for available volumes to move in other AZ') other_az_volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info,",
"for snapshots \" \"by tag, try to move it to the current AZ,",
"choose an appropriate volume type to ' 'match.') argp.add_argument( '--move-to-current-az', action='store_true', default=False, help=\"If",
"ID for newly created ' 'volumes') argp.add_argument( '--volume-type', metavar='TYPE', choices=ebs.VOLUME_TYPES, default='gp2', help='Volume type",
"argp.add_argument( '--instance-id', metavar='ID', required=True, help='Instance ID to attach volumes to') argp.add_argument( '--volume-id-tag', metavar='KEY=VALUE',",
"create new volumes from.' 'Can be provided multiple times, in which case tags",
"new_az, snapshot_id) self.state = 'created' self.snapshot_id = snapshot_id self.old_volume_id = old_volume_id break else:",
"volume type to ' 'match.') argp.add_argument( '--move-to-current-az', action='store_true', default=False, help=\"If there is a",
"Can be provided multiple times, in ' 'which case tags will be combined",
"and snapshot['SnapshotId'] def converge(self): if not self.volume_id: availability_zone = \\ self.instance_info['Placement']['AvailabilityZone'] logger.info('About to",
"a new one is needed ' 'and applied to new volumes. Can be",
"self.volume_id = volume_id self.attached_device = attached_device return logger.debug('Looking up existing available volumes in",
"import random from . import ebs logger = logging.getLogger('ebs-snatcher.main') def get_args(): # pragma:",
"attachment ' 'succeeds') argp.add_argument( '--volume-extra-tag', metavar='KEY=VALUE', type=key_tag_pair, action='append', help='Extra tags to be applied",
"{}'.format(s)) return key, value class ResourceState(object): def __init__(self, args, instance_info): self.args = args",
"self.attached_device: self.attached_device = ebs.attach_volume( volume_id=self.volume_id, instance_info=self.instance_info, device_name=self.args.attach_device) self.attached_device = \\ ebs.find_system_block_device(self.volume_id, self.attached_device) if",
"= int(s) if n <= 0: raise ValueError('Value must be positive: {}'.format(n)) return",
"will be skipped, and the ' 'next name in alphabetical order will be",
"= ebs.create_volume( id_tags=self.args.volume_id_tag, extra_tags=self.args.volume_extra_tag, availability_zone=availability_zone, volume_type=self.args.volume_type, size=self.args.volume_size, iops=self.args.volume_iops, kms_key_id=self.args.encrypt_kms_key_id, src_snapshot_id=self.snapshot_id) self.volume_id = new_volume['VolumeId']",
"import str, bytes import argparse import json import logging import random from .",
"\\ self.instance_info['Placement']['AvailabilityZone'] logger.info('About to create volume in AZ %s', availability_zone) if not self.snapshot_id:",
"import json import logging import random from . import ebs logger = logging.getLogger('ebs-snatcher.main')",
"newly created volumes, in GBs.') argp.add_argument( '--snapshot-search-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag used",
"to move in other AZ') other_az_volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=False) for old_volume",
"the original.\") return argp.parse_args() def positive_int(s): n = int(s) if n <= 0:",
"volume_id = attached_volumes[0]['VolumeId'] attached_device = attached_volumes[0]['Attachments'][0]['Device'] logger.info( 'Found volume already attached to instance:",
"instance: %s', volume_id) self.state = 'present' self.volume_id = volume_id self.attached_device = attached_device return",
"= 'present' self.volume_id = volume_id self.attached_device = attached_device return logger.debug('Looking up existing available",
"other AZ') other_az_volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=False) for old_volume in other_az_volumes: old_volume_id",
"filters = [{'Name': 'volume-id', 'Values': [old_volume_id]}] snapshot = ebs.find_existing_snapshot(filters=filters) if snapshot: snapshot_id =",
"'volume-id', 'Values': [old_volume_id]}] snapshot = ebs.find_existing_snapshot(filters=filters) if snapshot: snapshot_id = snapshot['SnapshotId'] logger.info( 'Found",
"= None self.snapshot_id = None self.attached_device = None def survey(self): logger.debug('Looking up currently",
"to instance: %s', volume_id) self.state = 'present' self.volume_id = volume_id self.attached_device = attached_device",
"to create volume in AZ %s', availability_zone) if not self.snapshot_id: logger.info('Creating volume from",
"= \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=True) if volumes: logger.info( 'Found available volumes with given",
"old_volume['AvailabilityZone'] new_az = self.instance_info['Placement']['AvailabilityZone'] filters = [{'Name': 'volume-id', 'Values': [old_volume_id]}] snapshot = ebs.find_existing_snapshot(filters=filters)",
"self.instance_info['Placement']['AvailabilityZone'] logger.info('About to create volume in AZ %s', availability_zone) if not self.snapshot_id: logger.info('Creating",
"' 'it to current AZ %s. Using snapshot %s.', old_volume_id, old_az, new_az, snapshot_id)",
"attached_device = attached_volumes[0]['Attachments'][0]['Device'] logger.info( 'Found volume already attached to instance: %s', volume_id) self.state",
"volumes in current AZ. ' 'Searching for available volumes to move in other",
"volumes. Searching for a ' 'suitable snapshot instead') snapshot = ebs.find_existing_snapshot( search_tags=self.args.snapshot_search_tag) self.state",
"break else: logger.info('Did not find any available volumes in other AZ ' 'move.",
"create volume in AZ %s', availability_zone) if not self.snapshot_id: logger.info('Creating volume from scratch')",
"argp.add_argument( '--volume-iops', metavar='COUNT', type=positive_int, default=None, help='Number of provisioned I/O operations to assign to",
"other AZ ' 'move. Creating new volume from scratch.') self.state = 'created' else:",
"args, instance_info): self.args = args self.instance_info = instance_info self.state = None self.volume_id =",
"argp.add_argument( '--volume-extra-tag', metavar='KEY=VALUE', type=key_tag_pair, action='append', help='Extra tags to be applied to newly create",
"attached volumes to determine if a new one is needed ' 'and applied",
"to move it to the current AZ, by cloning it and \" \"deleting",
"volumes. Will be used to search ' 'currently attached volumes to determine if",
"logger.info( 'Found volume already attached to instance: %s', volume_id) self.state = 'present' self.volume_id",
"'--volume-extra-tag', metavar='KEY=VALUE', type=key_tag_pair, action='append', help='Extra tags to be applied to newly create volumes,",
"logging import random from . import ebs logger = logging.getLogger('ebs-snatcher.main') def get_args(): #",
"the ' 'next name in alphabetical order will be tried until attachment '",
"are ' 'not used for identification') argp.add_argument( '--encrypt-kms-key-id', metavar='KEY-ID', default=None, help='Enable encryption and",
"default=False, help=\"If there is a volume available in a different AZ than the",
"logging.getLogger('ebs-snatcher.main') def get_args(): # pragma: no cover argp = argparse.ArgumentParser( 'ebs-snatcher', description='Automatically provision",
"in AZ %s, will attempt to move ' 'it to current AZ %s.",
"if volumes: logger.info( 'Found available volumes with given specifications in current ' 'AZ:",
"use the given KMS key ID for newly created ' 'volumes') argp.add_argument( '--volume-type',",
"provision AWS EBS volumes from snapshots') argp.add_argument( '--instance-id', metavar='ID', required=True, help='Instance ID to",
"looking for snapshots \" \"by tag, try to move it to the current",
"default=None, help='Number of provisioned I/O operations to assign to newly created ' 'volumes.",
"use when attaching a volume, such as ' '\"/dev/sdb\". Can be set to",
"AZ than the \" \"current one, instead of skipping it and looking for",
"snapshots \" \"by tag, try to move it to the current AZ, by",
"multiple times, in which case tags will be ' 'combined as an AND",
"' 'move. Creating new volume from scratch.') self.state = 'created' else: logger.info('Did not",
"current AZ %s. Using snapshot %s.', old_volume_id, old_az, new_az, snapshot_id) self.state = 'created'",
"availability_zone = \\ self.instance_info['Placement']['AvailabilityZone'] logger.info('About to create volume in AZ %s', availability_zone) if",
"args = get_args() instance_info = ebs.get_instance_info(args.instance_id) resource_state = ResourceState(args, instance_info) resource_state.survey() resource_state.converge() print(json.dumps(resource_state.to_json()))",
"choices=ebs.VOLUME_TYPES, default='gp2', help='Volume type to use for newly created volumes') argp.add_argument( '--volume-iops', metavar='COUNT',",
"to_json(self): return {'volume_id': self.volume_id, 'attached_device': self.attached_device, 'result': self.state, 'src_snapshot_id': self.snapshot_id} def main(): logging.basicConfig(level=logging.DEBUG)",
"= random.choice(volumes)['VolumeId'] return if self.args.move_to_current_az: logger.info('Did not find any available volumes in current",
"in AZ') volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=True) if volumes: logger.info( 'Found available",
"assign to newly created ' 'volumes. Make sure to choose an appropriate volume",
"self.attached_device = attached_device return logger.debug('Looking up existing available volumes in AZ') volumes =",
"snapshot['SnapshotId'] logger.info( 'Found volume %s in AZ %s, will attempt to move '",
"to current AZ %s. Using snapshot %s.', old_volume_id, old_az, new_az, snapshot_id) self.state =",
"id_tags=self.args.volume_id_tag, extra_tags=self.args.volume_extra_tag, availability_zone=availability_zone, volume_type=self.args.volume_type, size=self.args.volume_size, iops=self.args.volume_iops, kms_key_id=self.args.encrypt_kms_key_id, src_snapshot_id=self.snapshot_id) self.volume_id = new_volume['VolumeId'] if not",
"not find any available volumes in other AZ ' 'move. Creating new volume",
"not find any available volumes in current AZ. ' 'Searching for available volumes",
"n <= 0: raise ValueError('Value must be positive: {}'.format(n)) return n def key_tag_pair(s):",
"'move. Creating new volume from scratch.') self.state = 'created' else: logger.info('Did not find",
"pragma: no cover argp = argparse.ArgumentParser( 'ebs-snatcher', description='Automatically provision AWS EBS volumes from",
"different AZ than the \" \"current one, instead of skipping it and looking",
"Make sure to choose an appropriate volume type to ' 'match.') argp.add_argument( '--move-to-current-az',",
"tried until attachment ' 'succeeds') argp.add_argument( '--volume-extra-tag', metavar='KEY=VALUE', type=key_tag_pair, action='append', help='Extra tags to",
"'suitable snapshot instead') snapshot = ebs.find_existing_snapshot( search_tags=self.args.snapshot_search_tag) self.state = 'created' self.snapshot_id = snapshot",
"metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag used to identify desired volumes. Will be used",
"self.snapshot_id} def main(): logging.basicConfig(level=logging.DEBUG) args = get_args() instance_info = ebs.get_instance_info(args.instance_id) resource_state = ResourceState(args,",
"one is needed ' 'and applied to new volumes. Can be provided multiple",
"from scratch') else: logger.info('Creating volume from snapshot %s', self.snapshot_id) new_volume = ebs.create_volume( id_tags=self.args.volume_id_tag,",
"newly create volumes, but which are ' 'not used for identification') argp.add_argument( '--encrypt-kms-key-id',",
"current AZ, by cloning it and \" \"deleting the original.\") return argp.parse_args() def",
"def positive_int(s): n = int(s) if n <= 0: raise ValueError('Value must be",
"'it to current AZ %s. Using snapshot %s.', old_volume_id, old_az, new_az, snapshot_id) self.state",
"ValueError('Value must be positive: {}'.format(n)) return n def key_tag_pair(s): if isinstance(s, bytes): s",
"of device to use when attaching a volume, such as ' '\"/dev/sdb\". Can",
"from scratch.') self.state = 'created' else: logger.info('Did not find any available volumes. Searching",
"size=self.args.volume_size, iops=self.args.volume_iops, kms_key_id=self.args.encrypt_kms_key_id, src_snapshot_id=self.snapshot_id) self.volume_id = new_volume['VolumeId'] if not self.attached_device: self.attached_device = ebs.attach_volume(",
"required=True, help='Instance ID to attach volumes to') argp.add_argument( '--volume-id-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append',",
"attached_volumes = \\ ebs.find_attached_volumes(self.args.volume_id_tag, self.instance_info) if attached_volumes: volume_id = attached_volumes[0]['VolumeId'] attached_device = attached_volumes[0]['Attachments'][0]['Device']",
"iops=self.args.volume_iops, kms_key_id=self.args.encrypt_kms_key_id, src_snapshot_id=self.snapshot_id) self.volume_id = new_volume['VolumeId'] if not self.attached_device: self.attached_device = ebs.attach_volume( volume_id=self.volume_id,",
"= \\ self.instance_info['Placement']['AvailabilityZone'] logger.info('About to create volume in AZ %s', availability_zone) if not",
"= ebs.find_existing_snapshot( search_tags=self.args.snapshot_search_tag) self.state = 'created' self.snapshot_id = snapshot and snapshot['SnapshotId'] def converge(self):",
"up existing available volumes in AZ') volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=True) if",
"argp.add_argument( '--volume-size', metavar='GB', type=positive_int, required=True, help='Size to assign to newly created volumes, in",
"required=True, help='Name of device to use when attaching a volume, such as '",
"= 'created' else: logger.info('Did not find any available volumes. Searching for a '",
"identify desired volumes. Will be used to search ' 'currently attached volumes to",
"= None self.old_volume_id = None self.snapshot_id = None self.attached_device = None def survey(self):",
"available in a different AZ than the \" \"current one, instead of skipping",
"and \" \"deleting the original.\") return argp.parse_args() def positive_int(s): n = int(s) if",
"0: raise ValueError('Value must be positive: {}'.format(n)) return n def key_tag_pair(s): if isinstance(s,",
"required=True, action='append', help='Tag used to identify desired volumes. Will be used to search",
"to assign to newly created volumes, in GBs.') argp.add_argument( '--snapshot-search-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True,",
"def survey(self): logger.debug('Looking up currently attached volumes') attached_volumes = \\ ebs.find_attached_volumes(self.args.volume_id_tag, self.instance_info) if",
"'src_snapshot_id': self.snapshot_id} def main(): logging.basicConfig(level=logging.DEBUG) args = get_args() instance_info = ebs.get_instance_info(args.instance_id) resource_state =",
"help='Enable encryption and use the given KMS key ID for newly created '",
"in use will be skipped, and the ' 'next name in alphabetical order",
"old_volume['VolumeId'] old_az = old_volume['AvailabilityZone'] new_az = self.instance_info['Placement']['AvailabilityZone'] filters = [{'Name': 'volume-id', 'Values': [old_volume_id]}]",
"in alphabetical order will be tried until attachment ' 'succeeds') argp.add_argument( '--volume-extra-tag', metavar='KEY=VALUE',",
"= \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=False) for old_volume in other_az_volumes: old_volume_id = old_volume['VolumeId'] old_az",
"desired volumes. Will be used to search ' 'currently attached volumes to determine",
"self.attached_device = \\ ebs.find_system_block_device(self.volume_id, self.attached_device) if self.old_volume_id: ebs.delete_volume(volume_id=self.old_volume_id) def to_json(self): return {'volume_id': self.volume_id,",
"existing available volumes in AZ') volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=True) if volumes:",
"src_snapshot_id=self.snapshot_id) self.volume_id = new_volume['VolumeId'] if not self.attached_device: self.attached_device = ebs.attach_volume( volume_id=self.volume_id, instance_info=self.instance_info, device_name=self.args.attach_device)",
"tag value: {}'.format(s)) return key, value class ResourceState(object): def __init__(self, args, instance_info): self.args",
"will attempt to move ' 'it to current AZ %s. Using snapshot %s.',",
"'--volume-id-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag used to identify desired volumes. Will be",
"appropriate volume type to ' 'match.') argp.add_argument( '--move-to-current-az', action='store_true', default=False, help=\"If there is",
"volumes, in GBs.') argp.add_argument( '--snapshot-search-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag used to identify",
"in other AZ') other_az_volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=False) for old_volume in other_az_volumes:",
"self.snapshot_id: logger.info('Creating volume from scratch') else: logger.info('Creating volume from snapshot %s', self.snapshot_id) new_volume",
"ebs.find_existing_snapshot( search_tags=self.args.snapshot_search_tag) self.state = 'created' self.snapshot_id = snapshot and snapshot['SnapshotId'] def converge(self): if",
"but which are ' 'not used for identification') argp.add_argument( '--encrypt-kms-key-id', metavar='KEY-ID', default=None, help='Enable",
"required=True, help='Size to assign to newly created volumes, in GBs.') argp.add_argument( '--snapshot-search-tag', metavar='KEY=VALUE',",
"= snapshot and snapshot['SnapshotId'] def converge(self): if not self.volume_id: availability_zone = \\ self.instance_info['Placement']['AvailabilityZone']",
"metavar='KEY-ID', default=None, help='Enable encryption and use the given KMS key ID for newly",
"volumes to') argp.add_argument( '--volume-id-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag used to identify desired",
"%s', self.snapshot_id) new_volume = ebs.create_volume( id_tags=self.args.volume_id_tag, extra_tags=self.args.volume_extra_tag, availability_zone=availability_zone, volume_type=self.args.volume_type, size=self.args.volume_size, iops=self.args.volume_iops, kms_key_id=self.args.encrypt_kms_key_id, src_snapshot_id=self.snapshot_id)",
"to create new volumes from.' 'Can be provided multiple times, in which case",
"metavar='GB', type=positive_int, required=True, help='Size to assign to newly created volumes, in GBs.') argp.add_argument(",
"return logger.debug('Looking up existing available volumes in AZ') volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info,",
"new_volume = ebs.create_volume( id_tags=self.args.volume_id_tag, extra_tags=self.args.volume_extra_tag, availability_zone=availability_zone, volume_type=self.args.volume_type, size=self.args.volume_size, iops=self.args.volume_iops, kms_key_id=self.args.encrypt_kms_key_id, src_snapshot_id=self.snapshot_id) self.volume_id =",
"'currently attached volumes to determine if a new one is needed ' 'and",
"new volumes from.' 'Can be provided multiple times, in which case tags will",
"snapshots to create new volumes from.' 'Can be provided multiple times, in which",
"current ' 'AZ: %s', ', '.join(map(lambda v: v['VolumeId'], volumes))) self.state = 'attached' self.volume_id",
"new_volume['VolumeId'] if not self.attached_device: self.attached_device = ebs.attach_volume( volume_id=self.volume_id, instance_info=self.instance_info, device_name=self.args.attach_device) self.attached_device = \\",
"= s.split('=', 1) except ValueError: raise ValueError('Missing tag value: {}'.format(s)) return key, value",
"created volumes, in GBs.') argp.add_argument( '--snapshot-search-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag used to",
"'which case tags will be combined as an AND condition.') argp.add_argument( '--volume-size', metavar='GB',",
"specifications in current ' 'AZ: %s', ', '.join(map(lambda v: v['VolumeId'], volumes))) self.state =",
"times, in ' 'which case tags will be combined as an AND condition.')",
"volumes from.' 'Can be provided multiple times, in which case tags will be",
"self.instance_info['Placement']['AvailabilityZone'] filters = [{'Name': 'volume-id', 'Values': [old_volume_id]}] snapshot = ebs.find_existing_snapshot(filters=filters) if snapshot: snapshot_id",
"= new_volume['VolumeId'] if not self.attached_device: self.attached_device = ebs.attach_volume( volume_id=self.volume_id, instance_info=self.instance_info, device_name=self.args.attach_device) self.attached_device =",
"logger.info('Did not find any available volumes in current AZ. ' 'Searching for available",
"and the ' 'next name in alphabetical order will be tried until attachment",
"instead of skipping it and looking for snapshots \" \"by tag, try to",
"determine if a new one is needed ' 'and applied to new volumes.",
"self.attached_device = None def survey(self): logger.debug('Looking up currently attached volumes') attached_volumes = \\",
"json import logging import random from . import ebs logger = logging.getLogger('ebs-snatcher.main') def",
"to choose an appropriate volume type to ' 'match.') argp.add_argument( '--move-to-current-az', action='store_true', default=False,",
"ID to attach volumes to') argp.add_argument( '--volume-id-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag used",
"attached_device return logger.debug('Looking up existing available volumes in AZ') volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag,",
"ResourceState(args, instance_info) resource_state.survey() resource_state.converge() print(json.dumps(resource_state.to_json())) return 0 if __name__ == '__main__': main() #",
"self.attached_device) if self.old_volume_id: ebs.delete_volume(volume_id=self.old_volume_id) def to_json(self): return {'volume_id': self.volume_id, 'attached_device': self.attached_device, 'result': self.state,",
"of skipping it and looking for snapshots \" \"by tag, try to move",
"help='Extra tags to be applied to newly create volumes, but which are '",
"if not self.attached_device: self.attached_device = ebs.attach_volume( volume_id=self.volume_id, instance_info=self.instance_info, device_name=self.args.attach_device) self.attached_device = \\ ebs.find_system_block_device(self.volume_id,",
"as an AND condition.') argp.add_argument( '--attach-device', metavar='PATH|auto', required=True, help='Name of device to use",
"ebs.find_attached_volumes(self.args.volume_id_tag, self.instance_info) if attached_volumes: volume_id = attached_volumes[0]['VolumeId'] attached_device = attached_volumes[0]['Attachments'][0]['Device'] logger.info( 'Found volume",
"action='append', help='Tag used to identify desired volumes. Will be used to search '",
"ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=False) for old_volume in other_az_volumes: old_volume_id = old_volume['VolumeId'] old_az = old_volume['AvailabilityZone']",
"instance_info = ebs.get_instance_info(args.instance_id) resource_state = ResourceState(args, instance_info) resource_state.survey() resource_state.converge() print(json.dumps(resource_state.to_json())) return 0 if",
"' 'next name in alphabetical order will be tried until attachment ' 'succeeds')",
"default. ' 'Device names found to be already in use will be skipped,",
". import ebs logger = logging.getLogger('ebs-snatcher.main') def get_args(): # pragma: no cover argp",
"volumes. Can be provided multiple times, in ' 'which case tags will be",
"to search ' 'currently attached volumes to determine if a new one is",
"else: logger.info('Did not find any available volumes. Searching for a ' 'suitable snapshot",
"Searching for a ' 'suitable snapshot instead') snapshot = ebs.find_existing_snapshot( search_tags=self.args.snapshot_search_tag) self.state =",
"be ' 'combined as an AND condition.') argp.add_argument( '--attach-device', metavar='PATH|auto', required=True, help='Name of",
"logger.debug('Looking up existing available volumes in AZ') volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=True)",
"logging.basicConfig(level=logging.DEBUG) args = get_args() instance_info = ebs.get_instance_info(args.instance_id) resource_state = ResourceState(args, instance_info) resource_state.survey() resource_state.converge()",
"ebs.find_existing_snapshot(filters=filters) if snapshot: snapshot_id = snapshot['SnapshotId'] logger.info( 'Found volume %s in AZ %s,",
"is a volume available in a different AZ than the \" \"current one,",
"' 'not used for identification') argp.add_argument( '--encrypt-kms-key-id', metavar='KEY-ID', default=None, help='Enable encryption and use",
"move ' 'it to current AZ %s. Using snapshot %s.', old_volume_id, old_az, new_az,",
"self.state = 'present' self.volume_id = volume_id self.attached_device = attached_device return logger.debug('Looking up existing",
"help='Instance ID to attach volumes to') argp.add_argument( '--volume-id-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag",
"Creating new volume from scratch.') self.state = 'created' else: logger.info('Did not find any",
"from.' 'Can be provided multiple times, in which case tags will be '",
"survey(self): logger.debug('Looking up currently attached volumes') attached_volumes = \\ ebs.find_attached_volumes(self.args.volume_id_tag, self.instance_info) if attached_volumes:",
"is needed ' 'and applied to new volumes. Can be provided multiple times,",
"type=positive_int, required=True, help='Size to assign to newly created volumes, in GBs.') argp.add_argument( '--snapshot-search-tag',",
"\" \"by tag, try to move it to the current AZ, by cloning",
"= ebs.find_existing_snapshot(filters=filters) if snapshot: snapshot_id = snapshot['SnapshotId'] logger.info( 'Found volume %s in AZ",
"to assign to newly created ' 'volumes. Make sure to choose an appropriate",
"to move ' 'it to current AZ %s. Using snapshot %s.', old_volume_id, old_az,",
"provisioned I/O operations to assign to newly created ' 'volumes. Make sure to",
"def get_args(): # pragma: no cover argp = argparse.ArgumentParser( 'ebs-snatcher', description='Automatically provision AWS",
"availability_zone=availability_zone, volume_type=self.args.volume_type, size=self.args.volume_size, iops=self.args.volume_iops, kms_key_id=self.args.encrypt_kms_key_id, src_snapshot_id=self.snapshot_id) self.volume_id = new_volume['VolumeId'] if not self.attached_device: self.attached_device",
"volume_type=self.args.volume_type, size=self.args.volume_size, iops=self.args.volume_iops, kms_key_id=self.args.encrypt_kms_key_id, src_snapshot_id=self.snapshot_id) self.volume_id = new_volume['VolumeId'] if not self.attached_device: self.attached_device =",
"self.volume_id, 'attached_device': self.attached_device, 'result': self.state, 'src_snapshot_id': self.snapshot_id} def main(): logging.basicConfig(level=logging.DEBUG) args = get_args()",
"argparse.ArgumentParser( 'ebs-snatcher', description='Automatically provision AWS EBS volumes from snapshots') argp.add_argument( '--instance-id', metavar='ID', required=True,",
"help=\"If there is a volume available in a different AZ than the \"",
"in AZ %s', availability_zone) if not self.snapshot_id: logger.info('Creating volume from scratch') else: logger.info('Creating",
"v['VolumeId'], volumes))) self.state = 'attached' self.volume_id = random.choice(volumes)['VolumeId'] return if self.args.move_to_current_az: logger.info('Did not",
"= snapshot['SnapshotId'] logger.info( 'Found volume %s in AZ %s, will attempt to move",
"used to identify snapshots to create new volumes from.' 'Can be provided multiple",
"in current ' 'AZ: %s', ', '.join(map(lambda v: v['VolumeId'], volumes))) self.state = 'attached'",
"random.choice(volumes)['VolumeId'] return if self.args.move_to_current_az: logger.info('Did not find any available volumes in current AZ.",
"type=key_tag_pair, required=True, action='append', help='Tag used to identify snapshots to create new volumes from.'",
"skipped, and the ' 'next name in alphabetical order will be tried until",
"help='Tag used to identify snapshots to create new volumes from.' 'Can be provided",
"\"by tag, try to move it to the current AZ, by cloning it",
"'--volume-iops', metavar='COUNT', type=positive_int, default=None, help='Number of provisioned I/O operations to assign to newly",
"from __future__ import unicode_literals from builtins import str, bytes import argparse import json",
"be provided multiple times, in which case tags will be ' 'combined as",
"use will be skipped, and the ' 'next name in alphabetical order will",
"than the \" \"current one, instead of skipping it and looking for snapshots",
"any available volumes. Searching for a ' 'suitable snapshot instead') snapshot = ebs.find_existing_snapshot(",
"def converge(self): if not self.volume_id: availability_zone = \\ self.instance_info['Placement']['AvailabilityZone'] logger.info('About to create volume",
"to be already in use will be skipped, and the ' 'next name",
"by cloning it and \" \"deleting the original.\") return argp.parse_args() def positive_int(s): n",
"None self.volume_id = None self.old_volume_id = None self.snapshot_id = None self.attached_device = None",
"snapshot_id = snapshot['SnapshotId'] logger.info( 'Found volume %s in AZ %s, will attempt to",
"\" \"deleting the original.\") return argp.parse_args() def positive_int(s): n = int(s) if n",
"argp.add_argument( '--encrypt-kms-key-id', metavar='KEY-ID', default=None, help='Enable encryption and use the given KMS key ID",
"except ValueError: raise ValueError('Missing tag value: {}'.format(s)) return key, value class ResourceState(object): def",
"to attach volumes to') argp.add_argument( '--volume-id-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag used to",
"self.instance_info, current_az=True) if volumes: logger.info( 'Found available volumes with given specifications in current",
"cover argp = argparse.ArgumentParser( 'ebs-snatcher', description='Automatically provision AWS EBS volumes from snapshots') argp.add_argument(",
"class ResourceState(object): def __init__(self, args, instance_info): self.args = args self.instance_info = instance_info self.state",
"logger.info( 'Found available volumes with given specifications in current ' 'AZ: %s', ',",
"v: v['VolumeId'], volumes))) self.state = 'attached' self.volume_id = random.choice(volumes)['VolumeId'] return if self.args.move_to_current_az: logger.info('Did",
"any available volumes in current AZ. ' 'Searching for available volumes to move",
"'\"/dev/sdb\". Can be set to \"auto\" to use a safe default. ' 'Device",
"attach volumes to') argp.add_argument( '--volume-id-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag used to identify",
"from builtins import str, bytes import argparse import json import logging import random",
"'attached' self.volume_id = random.choice(volumes)['VolumeId'] return if self.args.move_to_current_az: logger.info('Did not find any available volumes",
"if attached_volumes: volume_id = attached_volumes[0]['VolumeId'] attached_device = attached_volumes[0]['Attachments'][0]['Device'] logger.info( 'Found volume already attached",
"' 'volumes. Make sure to choose an appropriate volume type to ' 'match.')",
"n = int(s) if n <= 0: raise ValueError('Value must be positive: {}'.format(n))",
"any available volumes in other AZ ' 'move. Creating new volume from scratch.')",
"needed ' 'and applied to new volumes. Can be provided multiple times, in",
"\" \"current one, instead of skipping it and looking for snapshots \" \"by",
"attached_volumes[0]['VolumeId'] attached_device = attached_volumes[0]['Attachments'][0]['Device'] logger.info( 'Found volume already attached to instance: %s', volume_id)",
"an appropriate volume type to ' 'match.') argp.add_argument( '--move-to-current-az', action='store_true', default=False, help=\"If there",
"'.join(map(lambda v: v['VolumeId'], volumes))) self.state = 'attached' self.volume_id = random.choice(volumes)['VolumeId'] return if self.args.move_to_current_az:",
"resource_state = ResourceState(args, instance_info) resource_state.survey() resource_state.converge() print(json.dumps(resource_state.to_json())) return 0 if __name__ == '__main__':",
"if snapshot: snapshot_id = snapshot['SnapshotId'] logger.info( 'Found volume %s in AZ %s, will",
"{'volume_id': self.volume_id, 'attached_device': self.attached_device, 'result': self.state, 'src_snapshot_id': self.snapshot_id} def main(): logging.basicConfig(level=logging.DEBUG) args =",
"volumes))) self.state = 'attached' self.volume_id = random.choice(volumes)['VolumeId'] return if self.args.move_to_current_az: logger.info('Did not find",
"ebs.create_volume( id_tags=self.args.volume_id_tag, extra_tags=self.args.volume_extra_tag, availability_zone=availability_zone, volume_type=self.args.volume_type, size=self.args.volume_size, iops=self.args.volume_iops, kms_key_id=self.args.encrypt_kms_key_id, src_snapshot_id=self.snapshot_id) self.volume_id = new_volume['VolumeId'] if",
"argp = argparse.ArgumentParser( 'ebs-snatcher', description='Automatically provision AWS EBS volumes from snapshots') argp.add_argument( '--instance-id',",
"snapshot = ebs.find_existing_snapshot(filters=filters) if snapshot: snapshot_id = snapshot['SnapshotId'] logger.info( 'Found volume %s in",
"Can be set to \"auto\" to use a safe default. ' 'Device names",
"args self.instance_info = instance_info self.state = None self.volume_id = None self.old_volume_id = None",
"self.volume_id = random.choice(volumes)['VolumeId'] return if self.args.move_to_current_az: logger.info('Did not find any available volumes in",
"for newly created volumes') argp.add_argument( '--volume-iops', metavar='COUNT', type=positive_int, default=None, help='Number of provisioned I/O",
"[{'Name': 'volume-id', 'Values': [old_volume_id]}] snapshot = ebs.find_existing_snapshot(filters=filters) if snapshot: snapshot_id = snapshot['SnapshotId'] logger.info(",
"available volumes. Searching for a ' 'suitable snapshot instead') snapshot = ebs.find_existing_snapshot( search_tags=self.args.snapshot_search_tag)",
"logger.info('Did not find any available volumes. Searching for a ' 'suitable snapshot instead')",
"as an AND condition.') argp.add_argument( '--volume-size', metavar='GB', type=positive_int, required=True, help='Size to assign to",
"<= 0: raise ValueError('Value must be positive: {}'.format(n)) return n def key_tag_pair(s): if",
"try to move it to the current AZ, by cloning it and \"",
"volume %s in AZ %s, will attempt to move ' 'it to current",
"in ' 'which case tags will be combined as an AND condition.') argp.add_argument(",
"def key_tag_pair(s): if isinstance(s, bytes): s = str(s, 'utf-8') elif not isinstance(s, str):",
"converge(self): if not self.volume_id: availability_zone = \\ self.instance_info['Placement']['AvailabilityZone'] logger.info('About to create volume in",
"value = s.split('=', 1) except ValueError: raise ValueError('Missing tag value: {}'.format(s)) return key,",
"used to search ' 'currently attached volumes to determine if a new one",
"available volumes in AZ') volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=True) if volumes: logger.info(",
"' 'currently attached volumes to determine if a new one is needed '",
"to use for newly created volumes') argp.add_argument( '--volume-iops', metavar='COUNT', type=positive_int, default=None, help='Number of",
"import argparse import json import logging import random from . import ebs logger",
"to newly create volumes, but which are ' 'not used for identification') argp.add_argument(",
"random from . import ebs logger = logging.getLogger('ebs-snatcher.main') def get_args(): # pragma: no",
"None self.old_volume_id = None self.snapshot_id = None self.attached_device = None def survey(self): logger.debug('Looking",
"type=positive_int, default=None, help='Number of provisioned I/O operations to assign to newly created '",
"def __init__(self, args, instance_info): self.args = args self.instance_info = instance_info self.state = None",
"available volumes with given specifications in current ' 'AZ: %s', ', '.join(map(lambda v:",
"will be combined as an AND condition.') argp.add_argument( '--volume-size', metavar='GB', type=positive_int, required=True, help='Size",
"= attached_volumes[0]['Attachments'][0]['Device'] logger.info( 'Found volume already attached to instance: %s', volume_id) self.state =",
"attached to instance: %s', volume_id) self.state = 'present' self.volume_id = volume_id self.attached_device =",
"one, instead of skipping it and looking for snapshots \" \"by tag, try",
"get_args(): # pragma: no cover argp = argparse.ArgumentParser( 'ebs-snatcher', description='Automatically provision AWS EBS",
"ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=True) if volumes: logger.info( 'Found available volumes with given specifications in",
"case tags will be ' 'combined as an AND condition.') argp.add_argument( '--attach-device', metavar='PATH|auto',",
"description='Automatically provision AWS EBS volumes from snapshots') argp.add_argument( '--instance-id', metavar='ID', required=True, help='Instance ID",
"self.volume_id = None self.old_volume_id = None self.snapshot_id = None self.attached_device = None def",
"volumes: logger.info( 'Found available volumes with given specifications in current ' 'AZ: %s',",
"in other_az_volumes: old_volume_id = old_volume['VolumeId'] old_az = old_volume['AvailabilityZone'] new_az = self.instance_info['Placement']['AvailabilityZone'] filters =",
"the given KMS key ID for newly created ' 'volumes') argp.add_argument( '--volume-type', metavar='TYPE',",
"= attached_volumes[0]['VolumeId'] attached_device = attached_volumes[0]['Attachments'][0]['Device'] logger.info( 'Found volume already attached to instance: %s',",
"set to \"auto\" to use a safe default. ' 'Device names found to",
"ebs.delete_volume(volume_id=self.old_volume_id) def to_json(self): return {'volume_id': self.volume_id, 'attached_device': self.attached_device, 'result': self.state, 'src_snapshot_id': self.snapshot_id} def",
"new volume from scratch.') self.state = 'created' else: logger.info('Did not find any available",
"action='append', help='Extra tags to be applied to newly create volumes, but which are",
"volumes') attached_volumes = \\ ebs.find_attached_volumes(self.args.volume_id_tag, self.instance_info) if attached_volumes: volume_id = attached_volumes[0]['VolumeId'] attached_device =",
"\"auto\" to use a safe default. ' 'Device names found to be already",
"new volumes. Can be provided multiple times, in ' 'which case tags will",
"to newly created volumes, in GBs.') argp.add_argument( '--snapshot-search-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag",
"be positive: {}'.format(n)) return n def key_tag_pair(s): if isinstance(s, bytes): s = str(s,",
"bytes): s = str(s, 'utf-8') elif not isinstance(s, str): raise TypeError('Input must be",
"find any available volumes in current AZ. ' 'Searching for available volumes to",
"volume_id) self.state = 'present' self.volume_id = volume_id self.attached_device = attached_device return logger.debug('Looking up",
"already in use will be skipped, and the ' 'next name in alphabetical",
"import unicode_literals from builtins import str, bytes import argparse import json import logging",
"if self.old_volume_id: ebs.delete_volume(volume_id=self.old_volume_id) def to_json(self): return {'volume_id': self.volume_id, 'attached_device': self.attached_device, 'result': self.state, 'src_snapshot_id':",
"volume, such as ' '\"/dev/sdb\". Can be set to \"auto\" to use a",
"logger.info('Creating volume from snapshot %s', self.snapshot_id) new_volume = ebs.create_volume( id_tags=self.args.volume_id_tag, extra_tags=self.args.volume_extra_tag, availability_zone=availability_zone, volume_type=self.args.volume_type,",
"be tried until attachment ' 'succeeds') argp.add_argument( '--volume-extra-tag', metavar='KEY=VALUE', type=key_tag_pair, action='append', help='Extra tags",
"an AND condition.') argp.add_argument( '--volume-size', metavar='GB', type=positive_int, required=True, help='Size to assign to newly",
"applied to newly create volumes, but which are ' 'not used for identification')",
"attached volumes') attached_volumes = \\ ebs.find_attached_volumes(self.args.volume_id_tag, self.instance_info) if attached_volumes: volume_id = attached_volumes[0]['VolumeId'] attached_device",
"' 'Searching for available volumes to move in other AZ') other_az_volumes = \\",
"= [{'Name': 'volume-id', 'Values': [old_volume_id]}] snapshot = ebs.find_existing_snapshot(filters=filters) if snapshot: snapshot_id = snapshot['SnapshotId']",
"'--encrypt-kms-key-id', metavar='KEY-ID', default=None, help='Enable encryption and use the given KMS key ID for",
"= volume_id self.attached_device = attached_device return logger.debug('Looking up existing available volumes in AZ')",
"a ' 'suitable snapshot instead') snapshot = ebs.find_existing_snapshot( search_tags=self.args.snapshot_search_tag) self.state = 'created' self.snapshot_id",
"default='gp2', help='Volume type to use for newly created volumes') argp.add_argument( '--volume-iops', metavar='COUNT', type=positive_int,",
"snapshot %s.', old_volume_id, old_az, new_az, snapshot_id) self.state = 'created' self.snapshot_id = snapshot_id self.old_volume_id",
"be applied to newly create volumes, but which are ' 'not used for",
"EBS volumes from snapshots') argp.add_argument( '--instance-id', metavar='ID', required=True, help='Instance ID to attach volumes",
"metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag used to identify snapshots to create new volumes",
"{}'.format(n)) return n def key_tag_pair(s): if isinstance(s, bytes): s = str(s, 'utf-8') elif",
"= None self.attached_device = None def survey(self): logger.debug('Looking up currently attached volumes') attached_volumes",
"provided multiple times, in ' 'which case tags will be combined as an",
"logger = logging.getLogger('ebs-snatcher.main') def get_args(): # pragma: no cover argp = argparse.ArgumentParser( 'ebs-snatcher',",
"of provisioned I/O operations to assign to newly created ' 'volumes. Make sure",
"self.attached_device, 'result': self.state, 'src_snapshot_id': self.snapshot_id} def main(): logging.basicConfig(level=logging.DEBUG) args = get_args() instance_info =",
"to be applied to newly create volumes, but which are ' 'not used",
"string') try: key, value = s.split('=', 1) except ValueError: raise ValueError('Missing tag value:",
"other_az_volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=False) for old_volume in other_az_volumes: old_volume_id = old_volume['VolumeId']",
"old_volume_id, old_az, new_az, snapshot_id) self.state = 'created' self.snapshot_id = snapshot_id self.old_volume_id = old_volume_id",
"= 'created' self.snapshot_id = snapshot and snapshot['SnapshotId'] def converge(self): if not self.volume_id: availability_zone",
"use a safe default. ' 'Device names found to be already in use",
"\\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=False) for old_volume in other_az_volumes: old_volume_id = old_volume['VolumeId'] old_az =",
"help='Number of provisioned I/O operations to assign to newly created ' 'volumes. Make",
"= 'created' self.snapshot_id = snapshot_id self.old_volume_id = old_volume_id break else: logger.info('Did not find",
"= old_volume['VolumeId'] old_az = old_volume['AvailabilityZone'] new_az = self.instance_info['Placement']['AvailabilityZone'] filters = [{'Name': 'volume-id', 'Values':",
"' 'match.') argp.add_argument( '--move-to-current-az', action='store_true', default=False, help=\"If there is a volume available in",
"search ' 'currently attached volumes to determine if a new one is needed",
"ResourceState(object): def __init__(self, args, instance_info): self.args = args self.instance_info = instance_info self.state =",
"= old_volume['AvailabilityZone'] new_az = self.instance_info['Placement']['AvailabilityZone'] filters = [{'Name': 'volume-id', 'Values': [old_volume_id]}] snapshot =",
"metavar='ID', required=True, help='Instance ID to attach volumes to') argp.add_argument( '--volume-id-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True,",
"condition.') argp.add_argument( '--volume-size', metavar='GB', type=positive_int, required=True, help='Size to assign to newly created volumes,",
"argp.add_argument( '--move-to-current-az', action='store_true', default=False, help=\"If there is a volume available in a different",
"old_volume_id = old_volume['VolumeId'] old_az = old_volume['AvailabilityZone'] new_az = self.instance_info['Placement']['AvailabilityZone'] filters = [{'Name': 'volume-id',",
"and use the given KMS key ID for newly created ' 'volumes') argp.add_argument(",
"volumes in AZ') volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=True) if volumes: logger.info( 'Found",
"use for newly created volumes') argp.add_argument( '--volume-iops', metavar='COUNT', type=positive_int, default=None, help='Number of provisioned",
"currently attached volumes') attached_volumes = \\ ebs.find_attached_volumes(self.args.volume_id_tag, self.instance_info) if attached_volumes: volume_id = attached_volumes[0]['VolumeId']",
"help='Tag used to identify desired volumes. Will be used to search ' 'currently",
"resource_state.converge() print(json.dumps(resource_state.to_json())) return 0 if __name__ == '__main__': main() # pragma: no cover",
"already attached to instance: %s', volume_id) self.state = 'present' self.volume_id = volume_id self.attached_device",
"= None def survey(self): logger.debug('Looking up currently attached volumes') attached_volumes = \\ ebs.find_attached_volumes(self.args.volume_id_tag,",
"not self.volume_id: availability_zone = \\ self.instance_info['Placement']['AvailabilityZone'] logger.info('About to create volume in AZ %s',",
"there is a volume available in a different AZ than the \" \"current",
"self.old_volume_id = None self.snapshot_id = None self.attached_device = None def survey(self): logger.debug('Looking up",
"self.args = args self.instance_info = instance_info self.state = None self.volume_id = None self.old_volume_id",
"snapshot = ebs.find_existing_snapshot( search_tags=self.args.snapshot_search_tag) self.state = 'created' self.snapshot_id = snapshot and snapshot['SnapshotId'] def",
"'present' self.volume_id = volume_id self.attached_device = attached_device return logger.debug('Looking up existing available volumes",
"volumes, but which are ' 'not used for identification') argp.add_argument( '--encrypt-kms-key-id', metavar='KEY-ID', default=None,",
"Using snapshot %s.', old_volume_id, old_az, new_az, snapshot_id) self.state = 'created' self.snapshot_id = snapshot_id",
"' 'combined as an AND condition.') argp.add_argument( '--attach-device', metavar='PATH|auto', required=True, help='Name of device",
"if a new one is needed ' 'and applied to new volumes. Can",
"'next name in alphabetical order will be tried until attachment ' 'succeeds') argp.add_argument(",
"and looking for snapshots \" \"by tag, try to move it to the",
"'Device names found to be already in use will be skipped, and the",
"self.state = 'created' self.snapshot_id = snapshot and snapshot['SnapshotId'] def converge(self): if not self.volume_id:",
"AZ %s', availability_zone) if not self.snapshot_id: logger.info('Creating volume from scratch') else: logger.info('Creating volume",
"old_az, new_az, snapshot_id) self.state = 'created' self.snapshot_id = snapshot_id self.old_volume_id = old_volume_id break",
"to new volumes. Can be provided multiple times, in ' 'which case tags",
"= old_volume_id break else: logger.info('Did not find any available volumes in other AZ",
"used for identification') argp.add_argument( '--encrypt-kms-key-id', metavar='KEY-ID', default=None, help='Enable encryption and use the given",
"find any available volumes in other AZ ' 'move. Creating new volume from",
"instance_info self.state = None self.volume_id = None self.old_volume_id = None self.snapshot_id = None",
"volume in AZ %s', availability_zone) if not self.snapshot_id: logger.info('Creating volume from scratch') else:",
"volumes from snapshots') argp.add_argument( '--instance-id', metavar='ID', required=True, help='Instance ID to attach volumes to')",
"' 'suitable snapshot instead') snapshot = ebs.find_existing_snapshot( search_tags=self.args.snapshot_search_tag) self.state = 'created' self.snapshot_id =",
"move it to the current AZ, by cloning it and \" \"deleting the",
"resource_state.survey() resource_state.converge() print(json.dumps(resource_state.to_json())) return 0 if __name__ == '__main__': main() # pragma: no",
"'Can be provided multiple times, in which case tags will be ' 'combined",
"snapshot_id) self.state = 'created' self.snapshot_id = snapshot_id self.old_volume_id = old_volume_id break else: logger.info('Did",
"None self.attached_device = None def survey(self): logger.debug('Looking up currently attached volumes') attached_volumes =",
"AZ. ' 'Searching for available volumes to move in other AZ') other_az_volumes =",
"created ' 'volumes') argp.add_argument( '--volume-type', metavar='TYPE', choices=ebs.VOLUME_TYPES, default='gp2', help='Volume type to use for",
"= \\ ebs.find_attached_volumes(self.args.volume_id_tag, self.instance_info) if attached_volumes: volume_id = attached_volumes[0]['VolumeId'] attached_device = attached_volumes[0]['Attachments'][0]['Device'] logger.info(",
"'AZ: %s', ', '.join(map(lambda v: v['VolumeId'], volumes))) self.state = 'attached' self.volume_id = random.choice(volumes)['VolumeId']",
"ValueError: raise ValueError('Missing tag value: {}'.format(s)) return key, value class ResourceState(object): def __init__(self,",
"raise ValueError('Missing tag value: {}'.format(s)) return key, value class ResourceState(object): def __init__(self, args,",
"to \"auto\" to use a safe default. ' 'Device names found to be",
"self.volume_id = new_volume['VolumeId'] if not self.attached_device: self.attached_device = ebs.attach_volume( volume_id=self.volume_id, instance_info=self.instance_info, device_name=self.args.attach_device) self.attached_device",
"'--attach-device', metavar='PATH|auto', required=True, help='Name of device to use when attaching a volume, such",
"available volumes to move in other AZ') other_az_volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=False)",
"names found to be already in use will be skipped, and the '",
"self.snapshot_id) new_volume = ebs.create_volume( id_tags=self.args.volume_id_tag, extra_tags=self.args.volume_extra_tag, availability_zone=availability_zone, volume_type=self.args.volume_type, size=self.args.volume_size, iops=self.args.volume_iops, kms_key_id=self.args.encrypt_kms_key_id, src_snapshot_id=self.snapshot_id) self.volume_id",
"return {'volume_id': self.volume_id, 'attached_device': self.attached_device, 'result': self.state, 'src_snapshot_id': self.snapshot_id} def main(): logging.basicConfig(level=logging.DEBUG) args",
"metavar='PATH|auto', required=True, help='Name of device to use when attaching a volume, such as",
"to use a safe default. ' 'Device names found to be already in",
"search_tags=self.args.snapshot_search_tag) self.state = 'created' self.snapshot_id = snapshot and snapshot['SnapshotId'] def converge(self): if not",
"key, value = s.split('=', 1) except ValueError: raise ValueError('Missing tag value: {}'.format(s)) return",
"to identify desired volumes. Will be used to search ' 'currently attached volumes",
"tags will be combined as an AND condition.') argp.add_argument( '--volume-size', metavar='GB', type=positive_int, required=True,",
"to ' 'match.') argp.add_argument( '--move-to-current-az', action='store_true', default=False, help=\"If there is a volume available",
"must be positive: {}'.format(n)) return n def key_tag_pair(s): if isinstance(s, bytes): s =",
"positive_int(s): n = int(s) if n <= 0: raise ValueError('Value must be positive:",
"= argparse.ArgumentParser( 'ebs-snatcher', description='Automatically provision AWS EBS volumes from snapshots') argp.add_argument( '--instance-id', metavar='ID',",
"n def key_tag_pair(s): if isinstance(s, bytes): s = str(s, 'utf-8') elif not isinstance(s,",
"logger.debug('Looking up currently attached volumes') attached_volumes = \\ ebs.find_attached_volumes(self.args.volume_id_tag, self.instance_info) if attached_volumes: volume_id",
"= self.instance_info['Placement']['AvailabilityZone'] filters = [{'Name': 'volume-id', 'Values': [old_volume_id]}] snapshot = ebs.find_existing_snapshot(filters=filters) if snapshot:",
"'volumes. Make sure to choose an appropriate volume type to ' 'match.') argp.add_argument(",
"'Values': [old_volume_id]}] snapshot = ebs.find_existing_snapshot(filters=filters) if snapshot: snapshot_id = snapshot['SnapshotId'] logger.info( 'Found volume",
"'attached_device': self.attached_device, 'result': self.state, 'src_snapshot_id': self.snapshot_id} def main(): logging.basicConfig(level=logging.DEBUG) args = get_args() instance_info",
"volume from scratch') else: logger.info('Creating volume from snapshot %s', self.snapshot_id) new_volume = ebs.create_volume(",
"'utf-8') elif not isinstance(s, str): raise TypeError('Input must be a string') try: key,",
"ebs.get_instance_info(args.instance_id) resource_state = ResourceState(args, instance_info) resource_state.survey() resource_state.converge() print(json.dumps(resource_state.to_json())) return 0 if __name__ ==",
"from snapshots') argp.add_argument( '--instance-id', metavar='ID', required=True, help='Instance ID to attach volumes to') argp.add_argument(",
"extra_tags=self.args.volume_extra_tag, availability_zone=availability_zone, volume_type=self.args.volume_type, size=self.args.volume_size, iops=self.args.volume_iops, kms_key_id=self.args.encrypt_kms_key_id, src_snapshot_id=self.snapshot_id) self.volume_id = new_volume['VolumeId'] if not self.attached_device:",
"unicode_literals from builtins import str, bytes import argparse import json import logging import",
"key_tag_pair(s): if isinstance(s, bytes): s = str(s, 'utf-8') elif not isinstance(s, str): raise",
"for newly created ' 'volumes') argp.add_argument( '--volume-type', metavar='TYPE', choices=ebs.VOLUME_TYPES, default='gp2', help='Volume type to",
"old_az = old_volume['AvailabilityZone'] new_az = self.instance_info['Placement']['AvailabilityZone'] filters = [{'Name': 'volume-id', 'Values': [old_volume_id]}] snapshot",
"in a different AZ than the \" \"current one, instead of skipping it",
"self.instance_info) if attached_volumes: volume_id = attached_volumes[0]['VolumeId'] attached_device = attached_volumes[0]['Attachments'][0]['Device'] logger.info( 'Found volume already",
"%s.', old_volume_id, old_az, new_az, snapshot_id) self.state = 'created' self.snapshot_id = snapshot_id self.old_volume_id =",
"key, value class ResourceState(object): def __init__(self, args, instance_info): self.args = args self.instance_info =",
"identify snapshots to create new volumes from.' 'Can be provided multiple times, in",
"def main(): logging.basicConfig(level=logging.DEBUG) args = get_args() instance_info = ebs.get_instance_info(args.instance_id) resource_state = ResourceState(args, instance_info)",
"attached_volumes: volume_id = attached_volumes[0]['VolumeId'] attached_device = attached_volumes[0]['Attachments'][0]['Device'] logger.info( 'Found volume already attached to",
"self.old_volume_id: ebs.delete_volume(volume_id=self.old_volume_id) def to_json(self): return {'volume_id': self.volume_id, 'attached_device': self.attached_device, 'result': self.state, 'src_snapshot_id': self.snapshot_id}",
"action='append', help='Tag used to identify snapshots to create new volumes from.' 'Can be",
"volume_id=self.volume_id, instance_info=self.instance_info, device_name=self.args.attach_device) self.attached_device = \\ ebs.find_system_block_device(self.volume_id, self.attached_device) if self.old_volume_id: ebs.delete_volume(volume_id=self.old_volume_id) def to_json(self):",
"help='Size to assign to newly created volumes, in GBs.') argp.add_argument( '--snapshot-search-tag', metavar='KEY=VALUE', type=key_tag_pair,",
"up currently attached volumes') attached_volumes = \\ ebs.find_attached_volumes(self.args.volume_id_tag, self.instance_info) if attached_volumes: volume_id =",
"return argp.parse_args() def positive_int(s): n = int(s) if n <= 0: raise ValueError('Value",
"found to be already in use will be skipped, and the ' 'next",
"'combined as an AND condition.') argp.add_argument( '--attach-device', metavar='PATH|auto', required=True, help='Name of device to",
"to') argp.add_argument( '--volume-id-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag used to identify desired volumes.",
"available volumes in other AZ ' 'move. Creating new volume from scratch.') self.state",
"'result': self.state, 'src_snapshot_id': self.snapshot_id} def main(): logging.basicConfig(level=logging.DEBUG) args = get_args() instance_info = ebs.get_instance_info(args.instance_id)",
"TypeError('Input must be a string') try: key, value = s.split('=', 1) except ValueError:",
"volumes') argp.add_argument( '--volume-iops', metavar='COUNT', type=positive_int, default=None, help='Number of provisioned I/O operations to assign",
"import logging import random from . import ebs logger = logging.getLogger('ebs-snatcher.main') def get_args():",
"name in alphabetical order will be tried until attachment ' 'succeeds') argp.add_argument( '--volume-extra-tag',",
"not isinstance(s, str): raise TypeError('Input must be a string') try: key, value =",
"it and looking for snapshots \" \"by tag, try to move it to",
"not self.attached_device: self.attached_device = ebs.attach_volume( volume_id=self.volume_id, instance_info=self.instance_info, device_name=self.args.attach_device) self.attached_device = \\ ebs.find_system_block_device(self.volume_id, self.attached_device)",
"= ResourceState(args, instance_info) resource_state.survey() resource_state.converge() print(json.dumps(resource_state.to_json())) return 0 if __name__ == '__main__': main()",
"bytes import argparse import json import logging import random from . import ebs",
"GBs.') argp.add_argument( '--snapshot-search-tag', metavar='KEY=VALUE', type=key_tag_pair, required=True, action='append', help='Tag used to identify snapshots to",
"ValueError('Missing tag value: {}'.format(s)) return key, value class ResourceState(object): def __init__(self, args, instance_info):",
"'Found volume %s in AZ %s, will attempt to move ' 'it to",
"' 'Device names found to be already in use will be skipped, and",
"created volumes') argp.add_argument( '--volume-iops', metavar='COUNT', type=positive_int, default=None, help='Number of provisioned I/O operations to",
"if self.args.move_to_current_az: logger.info('Did not find any available volumes in current AZ. ' 'Searching",
"volumes = \\ ebs.find_available_volumes(self.args.volume_id_tag, self.instance_info, current_az=True) if volumes: logger.info( 'Found available volumes with",
"device_name=self.args.attach_device) self.attached_device = \\ ebs.find_system_block_device(self.volume_id, self.attached_device) if self.old_volume_id: ebs.delete_volume(volume_id=self.old_volume_id) def to_json(self): return {'volume_id':",
"volume from snapshot %s', self.snapshot_id) new_volume = ebs.create_volume( id_tags=self.args.volume_id_tag, extra_tags=self.args.volume_extra_tag, availability_zone=availability_zone, volume_type=self.args.volume_type, size=self.args.volume_size,",
"when attaching a volume, such as ' '\"/dev/sdb\". Can be set to \"auto\"",
"isinstance(s, str): raise TypeError('Input must be a string') try: key, value = s.split('=',",
"\\ ebs.find_attached_volumes(self.args.volume_id_tag, self.instance_info) if attached_volumes: volume_id = attached_volumes[0]['VolumeId'] attached_device = attached_volumes[0]['Attachments'][0]['Device'] logger.info( 'Found",
"self.instance_info = instance_info self.state = None self.volume_id = None self.old_volume_id = None self.snapshot_id",
"old_volume_id break else: logger.info('Did not find any available volumes in other AZ '",
"'Found available volumes with given specifications in current ' 'AZ: %s', ', '.join(map(lambda",
"be a string') try: key, value = s.split('=', 1) except ValueError: raise ValueError('Missing",
"tag, try to move it to the current AZ, by cloning it and",
"required=True, action='append', help='Tag used to identify snapshots to create new volumes from.' 'Can",
"case tags will be combined as an AND condition.') argp.add_argument( '--volume-size', metavar='GB', type=positive_int,",
"a safe default. ' 'Device names found to be already in use will",
"metavar='COUNT', type=positive_int, default=None, help='Number of provisioned I/O operations to assign to newly created",
"instance_info): self.args = args self.instance_info = instance_info self.state = None self.volume_id = None",
"will be ' 'combined as an AND condition.') argp.add_argument( '--attach-device', metavar='PATH|auto', required=True, help='Name",
"= instance_info self.state = None self.volume_id = None self.old_volume_id = None self.snapshot_id =",
"None self.snapshot_id = None self.attached_device = None def survey(self): logger.debug('Looking up currently attached",
"used to identify desired volumes. Will be used to search ' 'currently attached",
"snapshot_id self.old_volume_id = old_volume_id break else: logger.info('Did not find any available volumes in",
"return n def key_tag_pair(s): if isinstance(s, bytes): s = str(s, 'utf-8') elif not",
"type=key_tag_pair, action='append', help='Extra tags to be applied to newly create volumes, but which"
] |
[
"assert new_replica_found volume = common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name) assert volume[\"state\"] == common.VOLUME_STATE_ATTACHED",
"== base_image host_id = get_self_host_id() volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) assert",
"False for replica in volume[\"replicas\"]: if replica[\"name\"] == replica1[\"name\"]: found = True break",
"volume_name assert len(volume[\"replicas\"]) == 2 replica0 = volume[\"replicas\"][0] assert replica0[\"name\"] != \"\" replica1",
"= common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"] == volume_name assert volume[\"size\"] == size assert volume[\"numberOfReplicas\"]",
"def test_ha_simple_recovery(client, volume_name): # NOQA ha_simple_recovery_test(client, volume_name, SIZE) def ha_simple_recovery_test(client, volume_name, size, base_image=\"\"):",
"!= replica0[\"name\"] and \\ r[\"name\"] != replica1[\"name\"]: new_replica_found = True break if new_replica_found:",
"= volume[\"replicas\"][1][\"name\"] data = write_volume_random_data(volume) common.k8s_delete_replica_pods_for_volume(volume_name) volume = common.wait_for_volume_faulted(client, volume_name) assert len(volume[\"replicas\"]) ==",
"get_volume_endpoint(volume) == DEV_PATH + volume_name assert len(volume[\"replicas\"]) == 2 replica0 = volume[\"replicas\"][0] assert",
"get_self_host_id() volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) assert len(volume[\"replicas\"]) == 2 replica0_name",
"replica1 = volume[\"replicas\"][1] assert replica1[\"name\"] != \"\" data = write_volume_random_data(volume) volume = volume.replicaRemove(name=replica0[\"name\"])",
"numberOfReplicas=2, baseImage=base_image) volume = common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"] == volume_name assert volume[\"size\"] ==",
"volume_name) assert len(volume[\"replicas\"]) == 2 replica0_name = volume[\"replicas\"][0][\"name\"] replica1_name = volume[\"replicas\"][1][\"name\"] data =",
"volume[\"size\"] == SIZE assert volume[\"numberOfReplicas\"] == 2 assert volume[\"state\"] == \"detached\" assert volume[\"created\"]",
"= common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"] == volume_name assert volume[\"size\"] == SIZE assert volume[\"numberOfReplicas\"]",
"NOQA from common import SIZE, DEV_PATH from common import check_volume_data, get_self_host_id, get_volume_endpoint from",
"= False for replica in volume[\"replicas\"]: if replica[\"name\"] == replica1[\"name\"]: found = True",
"NOQA ha_simple_recovery_test(client, volume_name, SIZE) def ha_simple_recovery_test(client, volume_name, size, base_image=\"\"): # NOQA volume =",
"volume[\"replicas\"][0] assert replica0[\"name\"] != \"\" replica1 = volume[\"replicas\"][1] assert replica1[\"name\"] != \"\" data",
"r in v[\"replicas\"]: if r[\"name\"] != replica0[\"name\"] and \\ r[\"name\"] != replica1[\"name\"]: new_replica_found",
"True break if new_replica_found: break time.sleep(RETRY_ITERVAL) assert new_replica_found volume = common.wait_for_volume_healthy(client, volume_name) volume",
"volume_name) volume = client.by_id_volume(volume_name) assert volume[\"state\"] == common.VOLUME_STATE_ATTACHED assert volume[\"robustness\"] == common.VOLUME_ROBUSTNESS_HEALTHY assert",
"= common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name) assert volume[\"state\"] == common.VOLUME_STATE_ATTACHED assert volume[\"robustness\"] ==",
"== DEV_PATH + volume_name assert len(volume[\"replicas\"]) == 2 replica0 = volume[\"replicas\"][0] assert replica0[\"name\"]",
"volume[\"robustness\"] == common.VOLUME_ROBUSTNESS_HEALTHY assert len(volume[\"replicas\"]) >= 2 found = False for replica in",
"volume[\"size\"] == size assert volume[\"numberOfReplicas\"] == 2 assert volume[\"state\"] == \"detached\" assert volume[\"created\"]",
"import client, volume_name # NOQA from common import SIZE, DEV_PATH from common import",
"volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) check_volume_data(volume, data) volume = volume.detach() volume",
"= volume[\"replicas\"][0][\"name\"] replica1_name = volume[\"replicas\"][1][\"name\"] data = write_volume_random_data(volume) common.k8s_delete_replica_pods_for_volume(volume_name) volume = common.wait_for_volume_faulted(client, volume_name)",
"\"detached\" assert volume[\"created\"] != \"\" assert volume[\"baseImage\"] == base_image host_id = get_self_host_id() volume",
"v[\"replicas\"]: if r[\"name\"] != replica0[\"name\"] and \\ r[\"name\"] != replica1[\"name\"]: new_replica_found = True",
"import write_volume_random_data from common import RETRY_COUNTS, RETRY_ITERVAL @pytest.mark.coretest # NOQA def test_ha_simple_recovery(client, volume_name):",
"# NOQA def test_ha_simple_recovery(client, volume_name): # NOQA ha_simple_recovery_test(client, volume_name, SIZE) def ha_simple_recovery_test(client, volume_name,",
"\"\" volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) check_volume_data(volume, data) volume = volume.detach()",
"volume[\"created\"] != \"\" assert volume[\"baseImage\"] == base_image host_id = get_self_host_id() volume = volume.attach(hostId=host_id)",
"size=SIZE, numberOfReplicas=2, baseImage=base_image) volume = common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"] == volume_name assert volume[\"size\"]",
"volume[\"replicas\"][1][\"name\"] data = write_volume_random_data(volume) common.k8s_delete_replica_pods_for_volume(volume_name) volume = common.wait_for_volume_faulted(client, volume_name) assert len(volume[\"replicas\"]) == 2",
"volume = common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name) assert get_volume_endpoint(volume) == DEV_PATH + volume_name",
"assert volume[\"replicas\"][1][\"failedAt\"] != \"\" volume.salvage(names=[replica0_name, replica1_name]) volume = common.wait_for_volume_detached(client, volume_name) assert len(volume[\"replicas\"]) ==",
"= client.create_volume(name=volume_name, size=size, numberOfReplicas=2, baseImage=base_image) volume = common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"] == volume_name",
"baseImage=base_image) volume = common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"] == volume_name assert volume[\"size\"] == size",
"common.wait_for_volume_detached(client, volume_name) assert len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"] == \"\" assert volume[\"replicas\"][1][\"failedAt\"] ==",
"assert get_volume_endpoint(volume) == DEV_PATH + volume_name assert len(volume[\"replicas\"]) == 2 replica0 = volume[\"replicas\"][0]",
"volume = client.create_volume(name=volume_name, size=SIZE, numberOfReplicas=2, baseImage=base_image) volume = common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"] ==",
"# NOQA volume = client.create_volume(name=volume_name, size=SIZE, numberOfReplicas=2, baseImage=base_image) volume = common.wait_for_volume_detached(client, volume_name) assert",
"size, base_image=\"\"): # NOQA volume = client.create_volume(name=volume_name, size=size, numberOfReplicas=2, baseImage=base_image) volume = common.wait_for_volume_detached(client,",
"== \"\" volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) check_volume_data(volume, data) volume =",
"def test_ha_salvage(client, volume_name): # NOQA ha_salvage_test(client, volume_name) def ha_salvage_test(client, volume_name, base_image=\"\"): # NOQA",
"@pytest.mark.coretest # NOQA def test_ha_salvage(client, volume_name): # NOQA ha_salvage_test(client, volume_name) def ha_salvage_test(client, volume_name,",
"\"\" volume.salvage(names=[replica0_name, replica1_name]) volume = common.wait_for_volume_detached(client, volume_name) assert len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"]",
"volume = common.wait_for_volume_detached(client, volume_name) assert len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"] == \"\" assert",
"for i in range(RETRY_COUNTS): v = client.by_id_volume(volume_name) for r in v[\"replicas\"]: if r[\"name\"]",
"client.by_id_volume(volume_name) for r in v[\"replicas\"]: if r[\"name\"] != replica0[\"name\"] and \\ r[\"name\"] !=",
"SIZE, DEV_PATH from common import check_volume_data, get_self_host_id, get_volume_endpoint from common import write_volume_random_data from",
"0 @pytest.mark.coretest # NOQA def test_ha_salvage(client, volume_name): # NOQA ha_salvage_test(client, volume_name) def ha_salvage_test(client,",
"common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"] == volume_name assert volume[\"size\"] == size assert volume[\"numberOfReplicas\"] ==",
"volume = common.wait_for_volume_faulted(client, volume_name) assert len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"] != \"\" assert",
"from common import client, volume_name # NOQA from common import SIZE, DEV_PATH from",
"data) volume = volume.detach() volume = common.wait_for_volume_detached(client, volume_name) client.delete(volume) common.wait_for_volume_delete(client, volume_name) volumes =",
"= volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) assert len(volume[\"replicas\"]) == 2 replica0_name = volume[\"replicas\"][0][\"name\"]",
"assert replica0[\"name\"] != \"\" replica1 = volume[\"replicas\"][1] assert replica1[\"name\"] != \"\" data =",
"NOQA volume = client.create_volume(name=volume_name, size=SIZE, numberOfReplicas=2, baseImage=base_image) volume = common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"]",
"common.wait_for_volume_healthy(client, volume_name) check_volume_data(volume, data) volume = volume.detach() volume = common.wait_for_volume_detached(client, volume_name) client.delete(volume) common.wait_for_volume_delete(client,",
"i in range(RETRY_COUNTS): v = client.by_id_volume(volume_name) for r in v[\"replicas\"]: if r[\"name\"] !=",
"len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"] != \"\" assert volume[\"replicas\"][1][\"failedAt\"] != \"\" volume.salvage(names=[replica0_name, replica1_name])",
"volume_name) client.delete(volume) common.wait_for_volume_delete(client, volume_name) volumes = client.list_volume() assert len(volumes) == 0 @pytest.mark.coretest #",
"assert len(volume[\"replicas\"]) == 2 replica0_name = volume[\"replicas\"][0][\"name\"] replica1_name = volume[\"replicas\"][1][\"name\"] data = write_volume_random_data(volume)",
"new_replica_found = True break if new_replica_found: break time.sleep(RETRY_ITERVAL) assert new_replica_found volume = common.wait_for_volume_healthy(client,",
"import SIZE, DEV_PATH from common import check_volume_data, get_self_host_id, get_volume_endpoint from common import write_volume_random_data",
"= client.by_id_volume(volume_name) assert volume[\"state\"] == common.VOLUME_STATE_ATTACHED assert volume[\"robustness\"] == common.VOLUME_ROBUSTNESS_HEALTHY assert len(volume[\"replicas\"]) >=",
"new_replica_found: break time.sleep(RETRY_ITERVAL) assert new_replica_found volume = common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name) assert",
"assert len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"] == \"\" assert volume[\"replicas\"][1][\"failedAt\"] == \"\" volume",
"if r[\"name\"] != replica0[\"name\"] and \\ r[\"name\"] != replica1[\"name\"]: new_replica_found = True break",
"replica1_name = volume[\"replicas\"][1][\"name\"] data = write_volume_random_data(volume) common.k8s_delete_replica_pods_for_volume(volume_name) volume = common.wait_for_volume_faulted(client, volume_name) assert len(volume[\"replicas\"])",
"volume[\"name\"] == volume_name assert volume[\"size\"] == SIZE assert volume[\"numberOfReplicas\"] == 2 assert volume[\"state\"]",
"!= \"\" assert volume[\"baseImage\"] == base_image host_id = get_self_host_id() volume = volume.attach(hostId=host_id) volume",
"volume = common.wait_for_volume_detached(client, volume_name) client.delete(volume) common.wait_for_volume_delete(client, volume_name) volumes = client.list_volume() assert len(volumes) ==",
"get_volume_endpoint from common import write_volume_random_data from common import RETRY_COUNTS, RETRY_ITERVAL @pytest.mark.coretest # NOQA",
"+ volume_name assert len(volume[\"replicas\"]) == 2 replica0 = volume[\"replicas\"][0] assert replica0[\"name\"] != \"\"",
"volume = common.wait_for_volume_healthy(client, volume_name) check_volume_data(volume, data) volume = volume.detach() volume = common.wait_for_volume_detached(client, volume_name)",
"check_volume_data(volume, data) volume = volume.detach() volume = common.wait_for_volume_detached(client, volume_name) client.delete(volume) common.wait_for_volume_delete(client, volume_name) volumes",
"replica1_name]) volume = common.wait_for_volume_detached(client, volume_name) assert len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"] == \"\"",
"assert volume[\"replicas\"][1][\"failedAt\"] == \"\" volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) check_volume_data(volume, data)",
"assert replica1[\"name\"] != \"\" data = write_volume_random_data(volume) volume = volume.replicaRemove(name=replica0[\"name\"]) # wait until",
"data = write_volume_random_data(volume) common.k8s_delete_replica_pods_for_volume(volume_name) volume = common.wait_for_volume_faulted(client, volume_name) assert len(volume[\"replicas\"]) == 2 assert",
"== replica1[\"name\"]: found = True break assert found check_volume_data(volume, data) volume = volume.detach()",
"volume_name) assert len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"] != \"\" assert volume[\"replicas\"][1][\"failedAt\"] != \"\"",
"common import RETRY_COUNTS, RETRY_ITERVAL @pytest.mark.coretest # NOQA def test_ha_simple_recovery(client, volume_name): # NOQA ha_simple_recovery_test(client,",
"# NOQA ha_simple_recovery_test(client, volume_name, SIZE) def ha_simple_recovery_test(client, volume_name, size, base_image=\"\"): # NOQA volume",
"2 replica0 = volume[\"replicas\"][0] assert replica0[\"name\"] != \"\" replica1 = volume[\"replicas\"][1] assert replica1[\"name\"]",
"common import SIZE, DEV_PATH from common import check_volume_data, get_self_host_id, get_volume_endpoint from common import",
"\"\" replica1 = volume[\"replicas\"][1] assert replica1[\"name\"] != \"\" data = write_volume_random_data(volume) volume =",
"volume[\"numberOfReplicas\"] == 2 assert volume[\"state\"] == \"detached\" assert volume[\"created\"] != \"\" assert volume[\"baseImage\"]",
"volume.detach() volume = common.wait_for_volume_detached(client, volume_name) client.delete(volume) common.wait_for_volume_delete(client, volume_name) volumes = client.list_volume() assert len(volumes)",
"DEV_PATH + volume_name assert len(volume[\"replicas\"]) == 2 replica0 = volume[\"replicas\"][0] assert replica0[\"name\"] !=",
"volume[\"replicas\"][0][\"failedAt\"] == \"\" assert volume[\"replicas\"][1][\"failedAt\"] == \"\" volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client,",
"volume_name): # NOQA ha_salvage_test(client, volume_name) def ha_salvage_test(client, volume_name, base_image=\"\"): # NOQA volume =",
"client.delete(volume) common.wait_for_volume_delete(client, volume_name) volumes = client.list_volume() assert len(volumes) == 0 @pytest.mark.coretest # NOQA",
"# NOQA from common import SIZE, DEV_PATH from common import check_volume_data, get_self_host_id, get_volume_endpoint",
"assert volume[\"replicas\"][0][\"failedAt\"] != \"\" assert volume[\"replicas\"][1][\"failedAt\"] != \"\" volume.salvage(names=[replica0_name, replica1_name]) volume = common.wait_for_volume_detached(client,",
"import common import time from common import client, volume_name # NOQA from common",
"volume[\"replicas\"][1][\"failedAt\"] == \"\" volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) check_volume_data(volume, data) volume",
"if replica[\"name\"] == replica1[\"name\"]: found = True break assert found check_volume_data(volume, data) volume",
"\"\" assert volume[\"replicas\"][1][\"failedAt\"] != \"\" volume.salvage(names=[replica0_name, replica1_name]) volume = common.wait_for_volume_detached(client, volume_name) assert len(volume[\"replicas\"])",
"= False for i in range(RETRY_COUNTS): v = client.by_id_volume(volume_name) for r in v[\"replicas\"]:",
"wait until we saw a replica starts rebuilding new_replica_found = False for i",
"\\ r[\"name\"] != replica1[\"name\"]: new_replica_found = True break if new_replica_found: break time.sleep(RETRY_ITERVAL) assert",
"volume_name) volume = client.by_id_volume(volume_name) assert get_volume_endpoint(volume) == DEV_PATH + volume_name assert len(volume[\"replicas\"]) ==",
"found = False for replica in volume[\"replicas\"]: if replica[\"name\"] == replica1[\"name\"]: found =",
"volume[\"replicas\"][0][\"failedAt\"] != \"\" assert volume[\"replicas\"][1][\"failedAt\"] != \"\" volume.salvage(names=[replica0_name, replica1_name]) volume = common.wait_for_volume_detached(client, volume_name)",
"volume_name) def ha_salvage_test(client, volume_name, base_image=\"\"): # NOQA volume = client.create_volume(name=volume_name, size=SIZE, numberOfReplicas=2, baseImage=base_image)",
"client, volume_name # NOQA from common import SIZE, DEV_PATH from common import check_volume_data,",
"# NOQA def test_ha_salvage(client, volume_name): # NOQA ha_salvage_test(client, volume_name) def ha_salvage_test(client, volume_name, base_image=\"\"):",
"assert volume[\"baseImage\"] == base_image host_id = get_self_host_id() volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client,",
"new_replica_found volume = common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name) assert volume[\"state\"] == common.VOLUME_STATE_ATTACHED assert",
"volume_name, size, base_image=\"\"): # NOQA volume = client.create_volume(name=volume_name, size=size, numberOfReplicas=2, baseImage=base_image) volume =",
"replica0_name = volume[\"replicas\"][0][\"name\"] replica1_name = volume[\"replicas\"][1][\"name\"] data = write_volume_random_data(volume) common.k8s_delete_replica_pods_for_volume(volume_name) volume = common.wait_for_volume_faulted(client,",
"replica in volume[\"replicas\"]: if replica[\"name\"] == replica1[\"name\"]: found = True break assert found",
"SIZE) def ha_simple_recovery_test(client, volume_name, size, base_image=\"\"): # NOQA volume = client.create_volume(name=volume_name, size=size, numberOfReplicas=2,",
"assert volume[\"created\"] != \"\" assert volume[\"baseImage\"] == base_image host_id = get_self_host_id() volume =",
"found = True break assert found check_volume_data(volume, data) volume = volume.detach() volume =",
"volume_name) assert len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"] == \"\" assert volume[\"replicas\"][1][\"failedAt\"] == \"\"",
"= volume.replicaRemove(name=replica0[\"name\"]) # wait until we saw a replica starts rebuilding new_replica_found =",
"import pytest import common import time from common import client, volume_name # NOQA",
"time from common import client, volume_name # NOQA from common import SIZE, DEV_PATH",
"= write_volume_random_data(volume) volume = volume.replicaRemove(name=replica0[\"name\"]) # wait until we saw a replica starts",
"== 2 replica0_name = volume[\"replicas\"][0][\"name\"] replica1_name = volume[\"replicas\"][1][\"name\"] data = write_volume_random_data(volume) common.k8s_delete_replica_pods_for_volume(volume_name) volume",
"volume = client.by_id_volume(volume_name) assert get_volume_endpoint(volume) == DEV_PATH + volume_name assert len(volume[\"replicas\"]) == 2",
"== size assert volume[\"numberOfReplicas\"] == 2 assert volume[\"state\"] == \"detached\" assert volume[\"created\"] !=",
"from common import write_volume_random_data from common import RETRY_COUNTS, RETRY_ITERVAL @pytest.mark.coretest # NOQA def",
"replica1[\"name\"] != \"\" data = write_volume_random_data(volume) volume = volume.replicaRemove(name=replica0[\"name\"]) # wait until we",
"== 2 assert volume[\"state\"] == \"detached\" assert volume[\"created\"] != \"\" assert volume[\"baseImage\"] ==",
"assert volume[\"state\"] == \"detached\" assert volume[\"created\"] != \"\" assert volume[\"baseImage\"] == base_image host_id",
"volume[\"replicas\"]: if replica[\"name\"] == replica1[\"name\"]: found = True break assert found check_volume_data(volume, data)",
"== volume_name assert volume[\"size\"] == size assert volume[\"numberOfReplicas\"] == 2 assert volume[\"state\"] ==",
"break assert found check_volume_data(volume, data) volume = volume.detach() volume = common.wait_for_volume_detached(client, volume_name) client.delete(volume)",
"replica0[\"name\"] and \\ r[\"name\"] != replica1[\"name\"]: new_replica_found = True break if new_replica_found: break",
"= client.by_id_volume(volume_name) for r in v[\"replicas\"]: if r[\"name\"] != replica0[\"name\"] and \\ r[\"name\"]",
"# wait until we saw a replica starts rebuilding new_replica_found = False for",
"saw a replica starts rebuilding new_replica_found = False for i in range(RETRY_COUNTS): v",
"= common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name) assert get_volume_endpoint(volume) == DEV_PATH + volume_name assert",
"volume_name, base_image=\"\"): # NOQA volume = client.create_volume(name=volume_name, size=SIZE, numberOfReplicas=2, baseImage=base_image) volume = common.wait_for_volume_detached(client,",
"= volume.detach() volume = common.wait_for_volume_detached(client, volume_name) client.delete(volume) common.wait_for_volume_delete(client, volume_name) volumes = client.list_volume() assert",
"write_volume_random_data(volume) volume = volume.replicaRemove(name=replica0[\"name\"]) # wait until we saw a replica starts rebuilding",
"write_volume_random_data(volume) common.k8s_delete_replica_pods_for_volume(volume_name) volume = common.wait_for_volume_faulted(client, volume_name) assert len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"] !=",
"volume[\"replicas\"][1] assert replica1[\"name\"] != \"\" data = write_volume_random_data(volume) volume = volume.replicaRemove(name=replica0[\"name\"]) # wait",
"replica starts rebuilding new_replica_found = False for i in range(RETRY_COUNTS): v = client.by_id_volume(volume_name)",
"replica0[\"name\"] != \"\" replica1 = volume[\"replicas\"][1] assert replica1[\"name\"] != \"\" data = write_volume_random_data(volume)",
"= client.by_id_volume(volume_name) assert get_volume_endpoint(volume) == DEV_PATH + volume_name assert len(volume[\"replicas\"]) == 2 replica0",
"common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name) assert get_volume_endpoint(volume) == DEV_PATH + volume_name assert len(volume[\"replicas\"])",
"assert volume[\"numberOfReplicas\"] == 2 assert volume[\"state\"] == \"detached\" assert volume[\"created\"] != \"\" assert",
"len(volume[\"replicas\"]) == 2 replica0_name = volume[\"replicas\"][0][\"name\"] replica1_name = volume[\"replicas\"][1][\"name\"] data = write_volume_random_data(volume) common.k8s_delete_replica_pods_for_volume(volume_name)",
"!= \"\" replica1 = volume[\"replicas\"][1] assert replica1[\"name\"] != \"\" data = write_volume_random_data(volume) volume",
"== \"detached\" assert volume[\"created\"] != \"\" assert volume[\"baseImage\"] == base_image host_id = get_self_host_id()",
"assert volume[\"size\"] == SIZE assert volume[\"numberOfReplicas\"] == 2 assert volume[\"state\"] == \"detached\" assert",
"client.by_id_volume(volume_name) assert volume[\"state\"] == common.VOLUME_STATE_ATTACHED assert volume[\"robustness\"] == common.VOLUME_ROBUSTNESS_HEALTHY assert len(volume[\"replicas\"]) >= 2",
"common.VOLUME_ROBUSTNESS_HEALTHY assert len(volume[\"replicas\"]) >= 2 found = False for replica in volume[\"replicas\"]: if",
"ha_simple_recovery_test(client, volume_name, size, base_image=\"\"): # NOQA volume = client.create_volume(name=volume_name, size=size, numberOfReplicas=2, baseImage=base_image) volume",
"NOQA def test_ha_simple_recovery(client, volume_name): # NOQA ha_simple_recovery_test(client, volume_name, SIZE) def ha_simple_recovery_test(client, volume_name, size,",
"= volume[\"replicas\"][1] assert replica1[\"name\"] != \"\" data = write_volume_random_data(volume) volume = volume.replicaRemove(name=replica0[\"name\"]) #",
"starts rebuilding new_replica_found = False for i in range(RETRY_COUNTS): v = client.by_id_volume(volume_name) for",
"from common import RETRY_COUNTS, RETRY_ITERVAL @pytest.mark.coretest # NOQA def test_ha_simple_recovery(client, volume_name): # NOQA",
"rebuilding new_replica_found = False for i in range(RETRY_COUNTS): v = client.by_id_volume(volume_name) for r",
"assert len(volume[\"replicas\"]) >= 2 found = False for replica in volume[\"replicas\"]: if replica[\"name\"]",
"pytest import common import time from common import client, volume_name # NOQA from",
"get_self_host_id() volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name) assert get_volume_endpoint(volume)",
"assert found check_volume_data(volume, data) volume = volume.detach() volume = common.wait_for_volume_detached(client, volume_name) client.delete(volume) common.wait_for_volume_delete(client,",
"common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name) assert volume[\"state\"] == common.VOLUME_STATE_ATTACHED assert volume[\"robustness\"] == common.VOLUME_ROBUSTNESS_HEALTHY",
"if new_replica_found: break time.sleep(RETRY_ITERVAL) assert new_replica_found volume = common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name)",
"# NOQA ha_salvage_test(client, volume_name) def ha_salvage_test(client, volume_name, base_image=\"\"): # NOQA volume = client.create_volume(name=volume_name,",
"volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) assert len(volume[\"replicas\"]) == 2 replica0_name = volume[\"replicas\"][0][\"name\"] replica1_name",
"!= \"\" assert volume[\"replicas\"][1][\"failedAt\"] != \"\" volume.salvage(names=[replica0_name, replica1_name]) volume = common.wait_for_volume_detached(client, volume_name) assert",
"volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) check_volume_data(volume, data) volume = volume.detach() volume = common.wait_for_volume_detached(client,",
"== 2 replica0 = volume[\"replicas\"][0] assert replica0[\"name\"] != \"\" replica1 = volume[\"replicas\"][1] assert",
"== common.VOLUME_ROBUSTNESS_HEALTHY assert len(volume[\"replicas\"]) >= 2 found = False for replica in volume[\"replicas\"]:",
"client.list_volume() assert len(volumes) == 0 @pytest.mark.coretest # NOQA def test_ha_salvage(client, volume_name): # NOQA",
"volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name) assert get_volume_endpoint(volume) ==",
"= volume[\"replicas\"][0] assert replica0[\"name\"] != \"\" replica1 = volume[\"replicas\"][1] assert replica1[\"name\"] != \"\"",
"!= \"\" volume.salvage(names=[replica0_name, replica1_name]) volume = common.wait_for_volume_detached(client, volume_name) assert len(volume[\"replicas\"]) == 2 assert",
"= volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) check_volume_data(volume, data) volume = volume.detach() volume =",
"for replica in volume[\"replicas\"]: if replica[\"name\"] == replica1[\"name\"]: found = True break assert",
"== \"\" assert volume[\"replicas\"][1][\"failedAt\"] == \"\" volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name)",
"RETRY_COUNTS, RETRY_ITERVAL @pytest.mark.coretest # NOQA def test_ha_simple_recovery(client, volume_name): # NOQA ha_simple_recovery_test(client, volume_name, SIZE)",
"in v[\"replicas\"]: if r[\"name\"] != replica0[\"name\"] and \\ r[\"name\"] != replica1[\"name\"]: new_replica_found =",
"NOQA volume = client.create_volume(name=volume_name, size=size, numberOfReplicas=2, baseImage=base_image) volume = common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"]",
"= client.create_volume(name=volume_name, size=SIZE, numberOfReplicas=2, baseImage=base_image) volume = common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"] == volume_name",
"common import time from common import client, volume_name # NOQA from common import",
"assert len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"] != \"\" assert volume[\"replicas\"][1][\"failedAt\"] != \"\" volume.salvage(names=[replica0_name,",
"volume[\"replicas\"][0][\"name\"] replica1_name = volume[\"replicas\"][1][\"name\"] data = write_volume_random_data(volume) common.k8s_delete_replica_pods_for_volume(volume_name) volume = common.wait_for_volume_faulted(client, volume_name) assert",
"== 0 @pytest.mark.coretest # NOQA def test_ha_salvage(client, volume_name): # NOQA ha_salvage_test(client, volume_name) def",
"a replica starts rebuilding new_replica_found = False for i in range(RETRY_COUNTS): v =",
"= write_volume_random_data(volume) common.k8s_delete_replica_pods_for_volume(volume_name) volume = common.wait_for_volume_faulted(client, volume_name) assert len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"]",
"2 assert volume[\"state\"] == \"detached\" assert volume[\"created\"] != \"\" assert volume[\"baseImage\"] == base_image",
"volume.replicaRemove(name=replica0[\"name\"]) # wait until we saw a replica starts rebuilding new_replica_found = False",
"write_volume_random_data from common import RETRY_COUNTS, RETRY_ITERVAL @pytest.mark.coretest # NOQA def test_ha_simple_recovery(client, volume_name): #",
"len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"] == \"\" assert volume[\"replicas\"][1][\"failedAt\"] == \"\" volume =",
"client.create_volume(name=volume_name, size=size, numberOfReplicas=2, baseImage=base_image) volume = common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"] == volume_name assert",
"\"\" assert volume[\"replicas\"][1][\"failedAt\"] == \"\" volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) check_volume_data(volume,",
">= 2 found = False for replica in volume[\"replicas\"]: if replica[\"name\"] == replica1[\"name\"]:",
"NOQA def test_ha_salvage(client, volume_name): # NOQA ha_salvage_test(client, volume_name) def ha_salvage_test(client, volume_name, base_image=\"\"): #",
"== common.VOLUME_STATE_ATTACHED assert volume[\"robustness\"] == common.VOLUME_ROBUSTNESS_HEALTHY assert len(volume[\"replicas\"]) >= 2 found = False",
"host_id = get_self_host_id() volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) assert len(volume[\"replicas\"]) ==",
"= True break if new_replica_found: break time.sleep(RETRY_ITERVAL) assert new_replica_found volume = common.wait_for_volume_healthy(client, volume_name)",
"import time from common import client, volume_name # NOQA from common import SIZE,",
"common import write_volume_random_data from common import RETRY_COUNTS, RETRY_ITERVAL @pytest.mark.coretest # NOQA def test_ha_simple_recovery(client,",
"len(volume[\"replicas\"]) >= 2 found = False for replica in volume[\"replicas\"]: if replica[\"name\"] ==",
"volume = volume.replicaRemove(name=replica0[\"name\"]) # wait until we saw a replica starts rebuilding new_replica_found",
"volume = client.create_volume(name=volume_name, size=size, numberOfReplicas=2, baseImage=base_image) volume = common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"] ==",
"volume[\"state\"] == \"detached\" assert volume[\"created\"] != \"\" assert volume[\"baseImage\"] == base_image host_id =",
"common.wait_for_volume_healthy(client, volume_name) assert len(volume[\"replicas\"]) == 2 replica0_name = volume[\"replicas\"][0][\"name\"] replica1_name = volume[\"replicas\"][1][\"name\"] data",
"# NOQA volume = client.create_volume(name=volume_name, size=size, numberOfReplicas=2, baseImage=base_image) volume = common.wait_for_volume_detached(client, volume_name) assert",
"test_ha_salvage(client, volume_name): # NOQA ha_salvage_test(client, volume_name) def ha_salvage_test(client, volume_name, base_image=\"\"): # NOQA volume",
"== 2 assert volume[\"replicas\"][0][\"failedAt\"] == \"\" assert volume[\"replicas\"][1][\"failedAt\"] == \"\" volume = volume.attach(hostId=host_id)",
"DEV_PATH from common import check_volume_data, get_self_host_id, get_volume_endpoint from common import write_volume_random_data from common",
"volume = common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name) assert volume[\"state\"] == common.VOLUME_STATE_ATTACHED assert volume[\"robustness\"]",
"2 assert volume[\"replicas\"][0][\"failedAt\"] != \"\" assert volume[\"replicas\"][1][\"failedAt\"] != \"\" volume.salvage(names=[replica0_name, replica1_name]) volume =",
"import check_volume_data, get_self_host_id, get_volume_endpoint from common import write_volume_random_data from common import RETRY_COUNTS, RETRY_ITERVAL",
"ha_simple_recovery_test(client, volume_name, SIZE) def ha_simple_recovery_test(client, volume_name, size, base_image=\"\"): # NOQA volume = client.create_volume(name=volume_name,",
"volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name) assert get_volume_endpoint(volume) == DEV_PATH +",
"get_self_host_id, get_volume_endpoint from common import write_volume_random_data from common import RETRY_COUNTS, RETRY_ITERVAL @pytest.mark.coretest #",
"SIZE assert volume[\"numberOfReplicas\"] == 2 assert volume[\"state\"] == \"detached\" assert volume[\"created\"] != \"\"",
"volume[\"replicas\"][1][\"failedAt\"] != \"\" volume.salvage(names=[replica0_name, replica1_name]) volume = common.wait_for_volume_detached(client, volume_name) assert len(volume[\"replicas\"]) == 2",
"= client.list_volume() assert len(volumes) == 0 @pytest.mark.coretest # NOQA def test_ha_salvage(client, volume_name): #",
"volume_name assert volume[\"size\"] == size assert volume[\"numberOfReplicas\"] == 2 assert volume[\"state\"] == \"detached\"",
"common.VOLUME_STATE_ATTACHED assert volume[\"robustness\"] == common.VOLUME_ROBUSTNESS_HEALTHY assert len(volume[\"replicas\"]) >= 2 found = False for",
"ha_salvage_test(client, volume_name) def ha_salvage_test(client, volume_name, base_image=\"\"): # NOQA volume = client.create_volume(name=volume_name, size=SIZE, numberOfReplicas=2,",
"client.create_volume(name=volume_name, size=SIZE, numberOfReplicas=2, baseImage=base_image) volume = common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"] == volume_name assert",
"assert volume[\"robustness\"] == common.VOLUME_ROBUSTNESS_HEALTHY assert len(volume[\"replicas\"]) >= 2 found = False for replica",
"RETRY_ITERVAL @pytest.mark.coretest # NOQA def test_ha_simple_recovery(client, volume_name): # NOQA ha_simple_recovery_test(client, volume_name, SIZE) def",
"data = write_volume_random_data(volume) volume = volume.replicaRemove(name=replica0[\"name\"]) # wait until we saw a replica",
"base_image=\"\"): # NOQA volume = client.create_volume(name=volume_name, size=size, numberOfReplicas=2, baseImage=base_image) volume = common.wait_for_volume_detached(client, volume_name)",
"replica1[\"name\"]: found = True break assert found check_volume_data(volume, data) volume = volume.detach() volume",
"volume_name, SIZE) def ha_simple_recovery_test(client, volume_name, size, base_image=\"\"): # NOQA volume = client.create_volume(name=volume_name, size=size,",
"def ha_simple_recovery_test(client, volume_name, size, base_image=\"\"): # NOQA volume = client.create_volume(name=volume_name, size=size, numberOfReplicas=2, baseImage=base_image)",
"len(volumes) == 0 @pytest.mark.coretest # NOQA def test_ha_salvage(client, volume_name): # NOQA ha_salvage_test(client, volume_name)",
"from common import check_volume_data, get_self_host_id, get_volume_endpoint from common import write_volume_random_data from common import",
"r[\"name\"] != replica0[\"name\"] and \\ r[\"name\"] != replica1[\"name\"]: new_replica_found = True break if",
"check_volume_data, get_self_host_id, get_volume_endpoint from common import write_volume_random_data from common import RETRY_COUNTS, RETRY_ITERVAL @pytest.mark.coretest",
"from common import SIZE, DEV_PATH from common import check_volume_data, get_self_host_id, get_volume_endpoint from common",
"\"\" assert volume[\"baseImage\"] == base_image host_id = get_self_host_id() volume = volume.attach(hostId=host_id) volume =",
"volume = common.wait_for_volume_healthy(client, volume_name) assert len(volume[\"replicas\"]) == 2 replica0_name = volume[\"replicas\"][0][\"name\"] replica1_name =",
"volumes = client.list_volume() assert len(volumes) == 0 @pytest.mark.coretest # NOQA def test_ha_salvage(client, volume_name):",
"size=size, numberOfReplicas=2, baseImage=base_image) volume = common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"] == volume_name assert volume[\"size\"]",
"volume_name) assert volume[\"name\"] == volume_name assert volume[\"size\"] == size assert volume[\"numberOfReplicas\"] == 2",
"!= replica1[\"name\"]: new_replica_found = True break if new_replica_found: break time.sleep(RETRY_ITERVAL) assert new_replica_found volume",
"volume_name assert volume[\"size\"] == SIZE assert volume[\"numberOfReplicas\"] == 2 assert volume[\"state\"] == \"detached\"",
"2 assert volume[\"replicas\"][0][\"failedAt\"] == \"\" assert volume[\"replicas\"][1][\"failedAt\"] == \"\" volume = volume.attach(hostId=host_id) volume",
"and \\ r[\"name\"] != replica1[\"name\"]: new_replica_found = True break if new_replica_found: break time.sleep(RETRY_ITERVAL)",
"= get_self_host_id() volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) assert len(volume[\"replicas\"]) == 2",
"base_image host_id = get_self_host_id() volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) volume =",
"def ha_salvage_test(client, volume_name, base_image=\"\"): # NOQA volume = client.create_volume(name=volume_name, size=SIZE, numberOfReplicas=2, baseImage=base_image) volume",
"= get_self_host_id() volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name) assert",
"replica[\"name\"] == replica1[\"name\"]: found = True break assert found check_volume_data(volume, data) volume =",
"v = client.by_id_volume(volume_name) for r in v[\"replicas\"]: if r[\"name\"] != replica0[\"name\"] and \\",
"replica0 = volume[\"replicas\"][0] assert replica0[\"name\"] != \"\" replica1 = volume[\"replicas\"][1] assert replica1[\"name\"] !=",
"assert len(volume[\"replicas\"]) == 2 replica0 = volume[\"replicas\"][0] assert replica0[\"name\"] != \"\" replica1 =",
"replica1[\"name\"]: new_replica_found = True break if new_replica_found: break time.sleep(RETRY_ITERVAL) assert new_replica_found volume =",
"common import check_volume_data, get_self_host_id, get_volume_endpoint from common import write_volume_random_data from common import RETRY_COUNTS,",
"volume[\"baseImage\"] == base_image host_id = get_self_host_id() volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name)",
"assert volume[\"size\"] == size assert volume[\"numberOfReplicas\"] == 2 assert volume[\"state\"] == \"detached\" assert",
"\"\" data = write_volume_random_data(volume) volume = volume.replicaRemove(name=replica0[\"name\"]) # wait until we saw a",
"for r in v[\"replicas\"]: if r[\"name\"] != replica0[\"name\"] and \\ r[\"name\"] != replica1[\"name\"]:",
"assert volume[\"name\"] == volume_name assert volume[\"size\"] == size assert volume[\"numberOfReplicas\"] == 2 assert",
"in volume[\"replicas\"]: if replica[\"name\"] == replica1[\"name\"]: found = True break assert found check_volume_data(volume,",
"host_id = get_self_host_id() volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name)",
"common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"] == volume_name assert volume[\"size\"] == SIZE assert volume[\"numberOfReplicas\"] ==",
"volume = volume.detach() volume = common.wait_for_volume_detached(client, volume_name) client.delete(volume) common.wait_for_volume_delete(client, volume_name) volumes = client.list_volume()",
"volume_name): # NOQA ha_simple_recovery_test(client, volume_name, SIZE) def ha_simple_recovery_test(client, volume_name, size, base_image=\"\"): # NOQA",
"client.by_id_volume(volume_name) assert get_volume_endpoint(volume) == DEV_PATH + volume_name assert len(volume[\"replicas\"]) == 2 replica0 =",
"== volume_name assert volume[\"size\"] == SIZE assert volume[\"numberOfReplicas\"] == 2 assert volume[\"state\"] ==",
"assert volume[\"name\"] == volume_name assert volume[\"size\"] == SIZE assert volume[\"numberOfReplicas\"] == 2 assert",
"False for i in range(RETRY_COUNTS): v = client.by_id_volume(volume_name) for r in v[\"replicas\"]: if",
"= common.wait_for_volume_detached(client, volume_name) assert len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"] == \"\" assert volume[\"replicas\"][1][\"failedAt\"]",
"= common.wait_for_volume_healthy(client, volume_name) check_volume_data(volume, data) volume = volume.detach() volume = common.wait_for_volume_detached(client, volume_name) client.delete(volume)",
"= common.wait_for_volume_detached(client, volume_name) client.delete(volume) common.wait_for_volume_delete(client, volume_name) volumes = client.list_volume() assert len(volumes) == 0",
"size assert volume[\"numberOfReplicas\"] == 2 assert volume[\"state\"] == \"detached\" assert volume[\"created\"] != \"\"",
"baseImage=base_image) volume = common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"] == volume_name assert volume[\"size\"] == SIZE",
"volume = common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"] == volume_name assert volume[\"size\"] == SIZE assert",
"2 replica0_name = volume[\"replicas\"][0][\"name\"] replica1_name = volume[\"replicas\"][1][\"name\"] data = write_volume_random_data(volume) common.k8s_delete_replica_pods_for_volume(volume_name) volume =",
"NOQA ha_salvage_test(client, volume_name) def ha_salvage_test(client, volume_name, base_image=\"\"): # NOQA volume = client.create_volume(name=volume_name, size=SIZE,",
"base_image host_id = get_self_host_id() volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) assert len(volume[\"replicas\"])",
"in range(RETRY_COUNTS): v = client.by_id_volume(volume_name) for r in v[\"replicas\"]: if r[\"name\"] != replica0[\"name\"]",
"volume_name # NOQA from common import SIZE, DEV_PATH from common import check_volume_data, get_self_host_id,",
"== SIZE assert volume[\"numberOfReplicas\"] == 2 assert volume[\"state\"] == \"detached\" assert volume[\"created\"] !=",
"volume = client.by_id_volume(volume_name) assert volume[\"state\"] == common.VOLUME_STATE_ATTACHED assert volume[\"robustness\"] == common.VOLUME_ROBUSTNESS_HEALTHY assert len(volume[\"replicas\"])",
"time.sleep(RETRY_ITERVAL) assert new_replica_found volume = common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name) assert volume[\"state\"] ==",
"new_replica_found = False for i in range(RETRY_COUNTS): v = client.by_id_volume(volume_name) for r in",
"volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) assert len(volume[\"replicas\"]) == 2 replica0_name =",
"test_ha_simple_recovery(client, volume_name): # NOQA ha_simple_recovery_test(client, volume_name, SIZE) def ha_simple_recovery_test(client, volume_name, size, base_image=\"\"): #",
"range(RETRY_COUNTS): v = client.by_id_volume(volume_name) for r in v[\"replicas\"]: if r[\"name\"] != replica0[\"name\"] and",
"= common.wait_for_volume_healthy(client, volume_name) assert len(volume[\"replicas\"]) == 2 replica0_name = volume[\"replicas\"][0][\"name\"] replica1_name = volume[\"replicas\"][1][\"name\"]",
"ha_salvage_test(client, volume_name, base_image=\"\"): # NOQA volume = client.create_volume(name=volume_name, size=SIZE, numberOfReplicas=2, baseImage=base_image) volume =",
"== base_image host_id = get_self_host_id() volume = volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) volume",
"volume_name) check_volume_data(volume, data) volume = volume.detach() volume = common.wait_for_volume_detached(client, volume_name) client.delete(volume) common.wait_for_volume_delete(client, volume_name)",
"volume = common.wait_for_volume_detached(client, volume_name) assert volume[\"name\"] == volume_name assert volume[\"size\"] == size assert",
"found check_volume_data(volume, data) volume = volume.detach() volume = common.wait_for_volume_detached(client, volume_name) client.delete(volume) common.wait_for_volume_delete(client, volume_name)",
"until we saw a replica starts rebuilding new_replica_found = False for i in",
"assert volume[\"state\"] == common.VOLUME_STATE_ATTACHED assert volume[\"robustness\"] == common.VOLUME_ROBUSTNESS_HEALTHY assert len(volume[\"replicas\"]) >= 2 found",
"common.wait_for_volume_delete(client, volume_name) volumes = client.list_volume() assert len(volumes) == 0 @pytest.mark.coretest # NOQA def",
"= volume.attach(hostId=host_id) volume = common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name) assert get_volume_endpoint(volume) == DEV_PATH",
"volume[\"name\"] == volume_name assert volume[\"size\"] == size assert volume[\"numberOfReplicas\"] == 2 assert volume[\"state\"]",
"common.wait_for_volume_detached(client, volume_name) client.delete(volume) common.wait_for_volume_delete(client, volume_name) volumes = client.list_volume() assert len(volumes) == 0 @pytest.mark.coretest",
"True break assert found check_volume_data(volume, data) volume = volume.detach() volume = common.wait_for_volume_detached(client, volume_name)",
"common.k8s_delete_replica_pods_for_volume(volume_name) volume = common.wait_for_volume_faulted(client, volume_name) assert len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"] != \"\"",
"assert volume[\"replicas\"][0][\"failedAt\"] == \"\" assert volume[\"replicas\"][1][\"failedAt\"] == \"\" volume = volume.attach(hostId=host_id) volume =",
"import RETRY_COUNTS, RETRY_ITERVAL @pytest.mark.coretest # NOQA def test_ha_simple_recovery(client, volume_name): # NOQA ha_simple_recovery_test(client, volume_name,",
"assert len(volumes) == 0 @pytest.mark.coretest # NOQA def test_ha_salvage(client, volume_name): # NOQA ha_salvage_test(client,",
"common.wait_for_volume_faulted(client, volume_name) assert len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"] != \"\" assert volume[\"replicas\"][1][\"failedAt\"] !=",
"volume[\"state\"] == common.VOLUME_STATE_ATTACHED assert volume[\"robustness\"] == common.VOLUME_ROBUSTNESS_HEALTHY assert len(volume[\"replicas\"]) >= 2 found =",
"!= \"\" data = write_volume_random_data(volume) volume = volume.replicaRemove(name=replica0[\"name\"]) # wait until we saw",
"@pytest.mark.coretest # NOQA def test_ha_simple_recovery(client, volume_name): # NOQA ha_simple_recovery_test(client, volume_name, SIZE) def ha_simple_recovery_test(client,",
"we saw a replica starts rebuilding new_replica_found = False for i in range(RETRY_COUNTS):",
"len(volume[\"replicas\"]) == 2 replica0 = volume[\"replicas\"][0] assert replica0[\"name\"] != \"\" replica1 = volume[\"replicas\"][1]",
"r[\"name\"] != replica1[\"name\"]: new_replica_found = True break if new_replica_found: break time.sleep(RETRY_ITERVAL) assert new_replica_found",
"volume_name) volumes = client.list_volume() assert len(volumes) == 0 @pytest.mark.coretest # NOQA def test_ha_salvage(client,",
"volume_name) assert volume[\"name\"] == volume_name assert volume[\"size\"] == SIZE assert volume[\"numberOfReplicas\"] == 2",
"2 found = False for replica in volume[\"replicas\"]: if replica[\"name\"] == replica1[\"name\"]: found",
"common import client, volume_name # NOQA from common import SIZE, DEV_PATH from common",
"break if new_replica_found: break time.sleep(RETRY_ITERVAL) assert new_replica_found volume = common.wait_for_volume_healthy(client, volume_name) volume =",
"volume.salvage(names=[replica0_name, replica1_name]) volume = common.wait_for_volume_detached(client, volume_name) assert len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"] ==",
"break time.sleep(RETRY_ITERVAL) assert new_replica_found volume = common.wait_for_volume_healthy(client, volume_name) volume = client.by_id_volume(volume_name) assert volume[\"state\"]",
"= True break assert found check_volume_data(volume, data) volume = volume.detach() volume = common.wait_for_volume_detached(client,",
"= common.wait_for_volume_faulted(client, volume_name) assert len(volume[\"replicas\"]) == 2 assert volume[\"replicas\"][0][\"failedAt\"] != \"\" assert volume[\"replicas\"][1][\"failedAt\"]",
"== 2 assert volume[\"replicas\"][0][\"failedAt\"] != \"\" assert volume[\"replicas\"][1][\"failedAt\"] != \"\" volume.salvage(names=[replica0_name, replica1_name]) volume",
"base_image=\"\"): # NOQA volume = client.create_volume(name=volume_name, size=SIZE, numberOfReplicas=2, baseImage=base_image) volume = common.wait_for_volume_detached(client, volume_name)"
] |
[
"__init__(self, input_channels, hidden_channels, width = 128): ''' :param input_channels: the number of input",
"= torch.nn.Linear(width, width) self.linear3 = torch.nn.Linear(width, input_channels * hidden_channels) def forward(self, t, z):",
"matrix, # because we need it to represent a linear map from R^input_channels",
"f_{\\theta} in our neural CDE model ''' def __init__(self, input_channels, hidden_channels, width =",
"is normally embedded in the data :param z: input to the network &",
"because we need it to represent a linear map from R^input_channels to R^hidden_channels.",
"super(F, self).__init__() self.input_channels = input_channels self.hidden_channels = hidden_channels self.linear1 = torch.nn.Linear(hidden_channels, width) self.linear2",
"''' :param t: t is normally embedded in the data :param z: input",
"F(torch.nn.Module): ''' Defines the neural network denoted f_{\\theta} in our neural CDE model",
"# Ignoring the batch dimension, the shape of the output tensor must be",
"hidden_channels) def forward(self, t, z): ''' :param t: t is normally embedded in",
"the shape of the output tensor must be a matrix, # because we",
"= 128): ''' :param input_channels: the number of input channels in the data",
"width) self.linear3 = torch.nn.Linear(width, input_channels * hidden_channels) def forward(self, t, z): ''' :param",
"batch dimension, the shape of the output tensor must be a matrix, #",
"input channels in the data X. :param hidden_channels: the number of channels for",
"(batch, hidden_channels) :return: F(z) ''' z = self.linear1(z) z = z.tanh() z =",
"the number of input channels in the data X. :param hidden_channels: the number",
"torch.nn.Linear(width, input_channels * hidden_channels) def forward(self, t, z): ''' :param t: t is",
"hidden_channels) :return: F(z) ''' z = self.linear1(z) z = z.tanh() z = self.linear2(z)",
"it to represent a linear map from R^input_channels to R^hidden_channels. z = z.view(z.size(0),",
"tanh non-linearity. z = z.tanh() # Ignoring the batch dimension, the shape of",
"= input_channels self.hidden_channels = hidden_channels self.linear1 = torch.nn.Linear(hidden_channels, width) self.linear2 = torch.nn.Linear(width, width)",
"to represent a linear map from R^input_channels to R^hidden_channels. z = z.view(z.size(0), self.hidden_channels,",
"need it to represent a linear map from R^input_channels to R^hidden_channels. z =",
"data :param z: input to the network & has shape (batch, hidden_channels) :return:",
"z: input to the network & has shape (batch, hidden_channels) :return: F(z) '''",
"has shape (batch, hidden_channels) :return: F(z) ''' z = self.linear1(z) z = z.tanh()",
":param t: t is normally embedded in the data :param z: input to",
"torch class F(torch.nn.Module): ''' Defines the neural network denoted f_{\\theta} in our neural",
"denoted f_{\\theta} in our neural CDE model ''' def __init__(self, input_channels, hidden_channels, width",
":param hidden_channels: the number of channels for z_t. (We use h = 32)",
"number of channels for z_t. (We use h = 32) ''' #torch.manual_seed(3) super(F,",
"data X. :param hidden_channels: the number of channels for z_t. (We use h",
"self.linear2 = torch.nn.Linear(width, width) self.linear3 = torch.nn.Linear(width, input_channels * hidden_channels) def forward(self, t,",
"to the network & has shape (batch, hidden_channels) :return: F(z) ''' z =",
"hidden_channels self.linear1 = torch.nn.Linear(hidden_channels, width) self.linear2 = torch.nn.Linear(width, width) self.linear3 = torch.nn.Linear(width, input_channels",
"class F(torch.nn.Module): ''' Defines the neural network denoted f_{\\theta} in our neural CDE",
"self.linear1 = torch.nn.Linear(hidden_channels, width) self.linear2 = torch.nn.Linear(width, width) self.linear3 = torch.nn.Linear(width, input_channels *",
"embedded in the data :param z: input to the network & has shape",
"forward(self, t, z): ''' :param t: t is normally embedded in the data",
"channels in the data X. :param hidden_channels: the number of channels for z_t.",
"represent a linear map from R^input_channels to R^hidden_channels. z = z.view(z.size(0), self.hidden_channels, self.input_channels)",
"shape of the output tensor must be a matrix, # because we need",
"Defines the neural network denoted f_{\\theta} in our neural CDE model ''' def",
"self).__init__() self.input_channels = input_channels self.hidden_channels = hidden_channels self.linear1 = torch.nn.Linear(hidden_channels, width) self.linear2 =",
"t, z): ''' :param t: t is normally embedded in the data :param",
"neural network denoted f_{\\theta} in our neural CDE model ''' def __init__(self, input_channels,",
"final tanh non-linearity. z = z.tanh() # Ignoring the batch dimension, the shape",
"our neural CDE model ''' def __init__(self, input_channels, hidden_channels, width = 128): '''",
"we need it to represent a linear map from R^input_channels to R^hidden_channels. z",
"h = 32) ''' #torch.manual_seed(3) super(F, self).__init__() self.input_channels = input_channels self.hidden_channels = hidden_channels",
"input to the network & has shape (batch, hidden_channels) :return: F(z) ''' z",
"(We use h = 32) ''' #torch.manual_seed(3) super(F, self).__init__() self.input_channels = input_channels self.hidden_channels",
"z.tanh() # Ignoring the batch dimension, the shape of the output tensor must",
":param z: input to the network & has shape (batch, hidden_channels) :return: F(z)",
"channels for z_t. (We use h = 32) ''' #torch.manual_seed(3) super(F, self).__init__() self.input_channels",
"= z.tanh() # Ignoring the batch dimension, the shape of the output tensor",
"32) ''' #torch.manual_seed(3) super(F, self).__init__() self.input_channels = input_channels self.hidden_channels = hidden_channels self.linear1 =",
"z = z.tanh() z = self.linear2(z) z = z.tanh() z = self.linear3(z) #",
"must be a matrix, # because we need it to represent a linear",
"= self.linear3(z) # A final tanh non-linearity. z = z.tanh() # Ignoring the",
"self.hidden_channels = hidden_channels self.linear1 = torch.nn.Linear(hidden_channels, width) self.linear2 = torch.nn.Linear(width, width) self.linear3 =",
"z.tanh() z = self.linear3(z) # A final tanh non-linearity. z = z.tanh() #",
"#torch.manual_seed(3) super(F, self).__init__() self.input_channels = input_channels self.hidden_channels = hidden_channels self.linear1 = torch.nn.Linear(hidden_channels, width)",
"self.input_channels = input_channels self.hidden_channels = hidden_channels self.linear1 = torch.nn.Linear(hidden_channels, width) self.linear2 = torch.nn.Linear(width,",
"def __init__(self, input_channels, hidden_channels, width = 128): ''' :param input_channels: the number of",
"= 32) ''' #torch.manual_seed(3) super(F, self).__init__() self.input_channels = input_channels self.hidden_channels = hidden_channels self.linear1",
":return: F(z) ''' z = self.linear1(z) z = z.tanh() z = self.linear2(z) z",
"of the output tensor must be a matrix, # because we need it",
"the network & has shape (batch, hidden_channels) :return: F(z) ''' z = self.linear1(z)",
"width = 128): ''' :param input_channels: the number of input channels in the",
"def forward(self, t, z): ''' :param t: t is normally embedded in the",
"= z.tanh() z = self.linear2(z) z = z.tanh() z = self.linear3(z) # A",
"Ignoring the batch dimension, the shape of the output tensor must be a",
"of input channels in the data X. :param hidden_channels: the number of channels",
"z): ''' :param t: t is normally embedded in the data :param z:",
"F(z) ''' z = self.linear1(z) z = z.tanh() z = self.linear2(z) z =",
"<reponame>jb-c/dissertation<gh_stars>0 import torch class F(torch.nn.Module): ''' Defines the neural network denoted f_{\\theta} in",
"''' #torch.manual_seed(3) super(F, self).__init__() self.input_channels = input_channels self.hidden_channels = hidden_channels self.linear1 = torch.nn.Linear(hidden_channels,",
"= self.linear2(z) z = z.tanh() z = self.linear3(z) # A final tanh non-linearity.",
"A final tanh non-linearity. z = z.tanh() # Ignoring the batch dimension, the",
"self.linear3(z) # A final tanh non-linearity. z = z.tanh() # Ignoring the batch",
"t: t is normally embedded in the data :param z: input to the",
"self.linear2(z) z = z.tanh() z = self.linear3(z) # A final tanh non-linearity. z",
"shape (batch, hidden_channels) :return: F(z) ''' z = self.linear1(z) z = z.tanh() z",
"z = self.linear1(z) z = z.tanh() z = self.linear2(z) z = z.tanh() z",
"= z.tanh() z = self.linear3(z) # A final tanh non-linearity. z = z.tanh()",
"tensor must be a matrix, # because we need it to represent a",
"= hidden_channels self.linear1 = torch.nn.Linear(hidden_channels, width) self.linear2 = torch.nn.Linear(width, width) self.linear3 = torch.nn.Linear(width,",
"& has shape (batch, hidden_channels) :return: F(z) ''' z = self.linear1(z) z =",
"output tensor must be a matrix, # because we need it to represent",
"hidden_channels, width = 128): ''' :param input_channels: the number of input channels in",
"torch.nn.Linear(hidden_channels, width) self.linear2 = torch.nn.Linear(width, width) self.linear3 = torch.nn.Linear(width, input_channels * hidden_channels) def",
"linear map from R^input_channels to R^hidden_channels. z = z.view(z.size(0), self.hidden_channels, self.input_channels) return z",
"in our neural CDE model ''' def __init__(self, input_channels, hidden_channels, width = 128):",
"X. :param hidden_channels: the number of channels for z_t. (We use h =",
"# because we need it to represent a linear map from R^input_channels to",
"z.tanh() z = self.linear2(z) z = z.tanh() z = self.linear3(z) # A final",
"hidden_channels: the number of channels for z_t. (We use h = 32) '''",
"z_t. (We use h = 32) ''' #torch.manual_seed(3) super(F, self).__init__() self.input_channels = input_channels",
"the data :param z: input to the network & has shape (batch, hidden_channels)",
"the number of channels for z_t. (We use h = 32) ''' #torch.manual_seed(3)",
"''' def __init__(self, input_channels, hidden_channels, width = 128): ''' :param input_channels: the number",
"the output tensor must be a matrix, # because we need it to",
"input_channels: the number of input channels in the data X. :param hidden_channels: the",
"the batch dimension, the shape of the output tensor must be a matrix,",
"for z_t. (We use h = 32) ''' #torch.manual_seed(3) super(F, self).__init__() self.input_channels =",
"128): ''' :param input_channels: the number of input channels in the data X.",
"the neural network denoted f_{\\theta} in our neural CDE model ''' def __init__(self,",
"of channels for z_t. (We use h = 32) ''' #torch.manual_seed(3) super(F, self).__init__()",
"torch.nn.Linear(width, width) self.linear3 = torch.nn.Linear(width, input_channels * hidden_channels) def forward(self, t, z): '''",
"input_channels, hidden_channels, width = 128): ''' :param input_channels: the number of input channels",
"use h = 32) ''' #torch.manual_seed(3) super(F, self).__init__() self.input_channels = input_channels self.hidden_channels =",
"input_channels self.hidden_channels = hidden_channels self.linear1 = torch.nn.Linear(hidden_channels, width) self.linear2 = torch.nn.Linear(width, width) self.linear3",
"z = self.linear2(z) z = z.tanh() z = self.linear3(z) # A final tanh",
"# A final tanh non-linearity. z = z.tanh() # Ignoring the batch dimension,",
"z = self.linear3(z) # A final tanh non-linearity. z = z.tanh() # Ignoring",
"input_channels * hidden_channels) def forward(self, t, z): ''' :param t: t is normally",
"= self.linear1(z) z = z.tanh() z = self.linear2(z) z = z.tanh() z =",
"''' Defines the neural network denoted f_{\\theta} in our neural CDE model '''",
"width) self.linear2 = torch.nn.Linear(width, width) self.linear3 = torch.nn.Linear(width, input_channels * hidden_channels) def forward(self,",
"a matrix, # because we need it to represent a linear map from",
"the data X. :param hidden_channels: the number of channels for z_t. (We use",
"network & has shape (batch, hidden_channels) :return: F(z) ''' z = self.linear1(z) z",
"* hidden_channels) def forward(self, t, z): ''' :param t: t is normally embedded",
"self.linear1(z) z = z.tanh() z = self.linear2(z) z = z.tanh() z = self.linear3(z)",
":param input_channels: the number of input channels in the data X. :param hidden_channels:",
"= torch.nn.Linear(hidden_channels, width) self.linear2 = torch.nn.Linear(width, width) self.linear3 = torch.nn.Linear(width, input_channels * hidden_channels)",
"''' z = self.linear1(z) z = z.tanh() z = self.linear2(z) z = z.tanh()",
"self.linear3 = torch.nn.Linear(width, input_channels * hidden_channels) def forward(self, t, z): ''' :param t:",
"= torch.nn.Linear(width, input_channels * hidden_channels) def forward(self, t, z): ''' :param t: t",
"''' :param input_channels: the number of input channels in the data X. :param",
"neural CDE model ''' def __init__(self, input_channels, hidden_channels, width = 128): ''' :param",
"t is normally embedded in the data :param z: input to the network",
"dimension, the shape of the output tensor must be a matrix, # because",
"network denoted f_{\\theta} in our neural CDE model ''' def __init__(self, input_channels, hidden_channels,",
"normally embedded in the data :param z: input to the network & has",
"CDE model ''' def __init__(self, input_channels, hidden_channels, width = 128): ''' :param input_channels:",
"z = z.tanh() z = self.linear3(z) # A final tanh non-linearity. z =",
"model ''' def __init__(self, input_channels, hidden_channels, width = 128): ''' :param input_channels: the",
"in the data :param z: input to the network & has shape (batch,",
"z = z.tanh() # Ignoring the batch dimension, the shape of the output",
"in the data X. :param hidden_channels: the number of channels for z_t. (We",
"number of input channels in the data X. :param hidden_channels: the number of",
"non-linearity. z = z.tanh() # Ignoring the batch dimension, the shape of the",
"import torch class F(torch.nn.Module): ''' Defines the neural network denoted f_{\\theta} in our",
"a linear map from R^input_channels to R^hidden_channels. z = z.view(z.size(0), self.hidden_channels, self.input_channels) return",
"be a matrix, # because we need it to represent a linear map"
] |
[
"= 2 if rlt == tmpy: tr += 1 else: fl += 1",
"x, y2, 'b', x, y3, 'y') #fig.savefig('level.png', dpi=100) #fig.show() tr = 0 fl",
"tmpy = 1 else: tmpx = [set21.val(), set22.val(), set23.val()] tmpy = 2 rlt",
"rlt[0] > rlt[1]: rlt = 1 else: rlt = 2 if rlt ==",
"= [jg2.cal([item, item ** 2, item ** 3]) for item in x] #ax.plot(x,",
"for i in xrange(1000): x.append([set11.val(), set12.val(), set13.val()]) y.append([1, 0]) for i in xrange(1000):",
"by level', fontsize=14, fontweight='bold') ax = fig.add_subplot(111) set11 = nd(3, 2.5) set12 =",
"from copy import deepcopy as dp import random import math from Function import",
"regularization as rg import numpy as np from copy import deepcopy as dp",
"(ty1, ty2, ty3) # print rlt #x = np.arange(-20.0, 20.0, 0.01) #y1 =",
"print rlt #x = np.arange(-20.0, 20.0, 0.01) #y1 = [tf.cal(item) for item in",
"= fig.add_subplot(111) set11 = nd(3, 2.5) set12 = nd(3, 2.5) set13 = nd(3,",
"x, y3, 'y') #fig.savefig('level.png', dpi=100) #fig.show() tr = 0 fl = 0 for",
"for item in x] #y2 = [jg1.cal([item, item ** 2, item ** 3])[0]",
"1 else: rlt = 2 if rlt == tmpy: tr += 1 else:",
"= [[item] for item in y2] jg = bpn([3, 4, 4, 2]) jg.train(x,",
"** 2, item ** 3]) for item in x] #ax.plot(x, y1, 'r', x,",
"(x ** 2) + 0.1 * (x ** 3) + 7 ) tf",
"copy import deepcopy as dp import random import math from Function import *",
"pass def cal(self, x): return ( 0.7 * x - 7 * (x",
"nd(3, 2.5) set21 = nd(-6, 1.0) set22 = nd(-6, 1.0) set23 = nd(-6,",
"20.0, 0.01) #y1 = [tf.cal(item) for item in x] #y2 = [jg1.cal([item, item",
"fig.add_subplot(111) set11 = nd(3, 2.5) set12 = nd(3, 2.5) set13 = nd(3, 2.5)",
"0.03, 0.0005) #for i in xrange(10): # tmp = random.uniform(0.1, 25.0) # ty1",
"y2 = [] for i in xrange(1000): x.append([set11.val(), set12.val(), set13.val()]) y.append([1, 0]) for",
"** 2, tmp ** 3] # tmp1 = dp(tmp) # ty2 = jg1.cal(tmp)[0]",
"testFunc(functionObject): def __init__(self): pass def cal(self, x): return ( 0.7 * x -",
"** 2, item ** 3])[0] * param[1] + param[0] for item in x]",
"= bpn([3, 4, 4, 2]) jg.train(x, y, 0.03, 0.0005) #for i in xrange(10):",
"bpn fig = plt.figure() fig.suptitle(u'Informations gragh paramed by level', fontsize=14, fontweight='bold') ax =",
"in xrange(1000): x.append([set11.val(), set12.val(), set13.val()]) y.append([1, 0]) for i in xrange(1000): x.append([set21.val(), set22.val(),",
"- 7 * (x ** 2) + 0.1 * (x ** 3) +",
"LinearRegression.regularization import regularization as rg import numpy as np from copy import deepcopy",
"nd(3, 2.5) set13 = nd(3, 2.5) set21 = nd(-6, 1.0) set22 = nd(-6,",
"[tmp * 1, tmp ** 2, tmp ** 3] # tmp1 = dp(tmp)",
"import numpy as np from copy import deepcopy as dp import random import",
"2, item ** 3])[0] * param[1] + param[0] for item in x] #y3",
"np from copy import deepcopy as dp import random import math from Function",
"# tmp = random.uniform(0.1, 25.0) # ty1 = tf.cal(tmp) # tmp = [tmp",
"= [] y2 = [] for i in xrange(1000): x.append([set11.val(), set12.val(), set13.val()]) y.append([1,",
"gradientDescent as glr from LinearRegression.regularization import regularization as rg import numpy as np",
"set21 = nd(-6, 1.0) set22 = nd(-6, 1.0) set23 = nd(-6, 1.0) class",
"as nd import matplotlib.pyplot as plt from NeuralNetwork import BPnetwork as bpn fig",
"import deepcopy as dp import random import math from Function import * from",
"rlt[1]: rlt = 1 else: rlt = 2 if rlt == tmpy: tr",
"x): return ( 0.7 * x - 7 * (x ** 2) +",
"rlt = 1 else: rlt = 2 if rlt == tmpy: tr +=",
"in x] #y2 = [jg1.cal([item, item ** 2, item ** 3])[0] * param[1]",
"import matplotlib.pyplot as plt from NeuralNetwork import BPnetwork as bpn fig = plt.figure()",
"0 for i in xrange(100): p = random.random() if p >= 0.5: tmpx",
"* (x ** 2) + 0.1 * (x ** 3) + 7 )",
"as dp import random import math from Function import * from Distribution import",
"+ param[0] # rlt = (ty1, ty2, ty3) # print rlt #x =",
"2]) jg.train(x, y, 0.03, 0.0005) #for i in xrange(10): # tmp = random.uniform(0.1,",
"for item in y2] jg = bpn([3, 4, 4, 2]) jg.train(x, y, 0.03,",
"set13.val()]) y.append([1, 0]) for i in xrange(1000): x.append([set21.val(), set22.val(), set23.val()]) y.append([0, 1]) y2",
"return ( 0.7 * x - 7 * (x ** 2) + 0.1",
"LinearRegression.HugeScaleLR import hugeScaleLR as hlr from LinearRegression.GradientDescent import gradientDescent as glr from LinearRegression.regularization",
"y.append([0, 1]) y2 = [[item] for item in y2] jg = bpn([3, 4,",
"plt from NeuralNetwork import BPnetwork as bpn fig = plt.figure() fig.suptitle(u'Informations gragh paramed",
"[jg1.cal([item, item ** 2, item ** 3])[0] * param[1] + param[0] for item",
"in xrange(100): p = random.random() if p >= 0.5: tmpx = [set11.val(), set12.val(),",
"jg.train(x, y, 0.03, 0.0005) #for i in xrange(10): # tmp = random.uniform(0.1, 25.0)",
"y2 = [[item] for item in y2] jg = bpn([3, 4, 4, 2])",
"# ty2 = ty2 * param[1] + param[0] # rlt = (ty1, ty2,",
"** 2) + 0.1 * (x ** 3) + 7 ) tf =",
"[set11.val(), set12.val(), set13.val()] tmpy = 1 else: tmpx = [set21.val(), set22.val(), set23.val()] tmpy",
"4, 2]) jg.train(x, y, 0.03, 0.0005) #for i in xrange(10): # tmp =",
") tf = testFunc() x = [] y = [] y2 = []",
"i in xrange(1000): x.append([set21.val(), set22.val(), set23.val()]) y.append([0, 1]) y2 = [[item] for item",
"import BPnetwork as bpn fig = plt.figure() fig.suptitle(u'Informations gragh paramed by level', fontsize=14,",
"testFunc() x = [] y = [] y2 = [] for i in",
"set11 = nd(3, 2.5) set12 = nd(3, 2.5) set13 = nd(3, 2.5) set21",
"from Function import * from Distribution import NormalDistribution as nd import matplotlib.pyplot as",
"nd import matplotlib.pyplot as plt from NeuralNetwork import BPnetwork as bpn fig =",
"ty2 = jg1.cal(tmp)[0] # ty3 = jg2.cal(tmp1) # ty2 = ty2 * param[1]",
"tmp = [tmp * 1, tmp ** 2, tmp ** 3] # tmp1",
"BPnetwork as bpn fig = plt.figure() fig.suptitle(u'Informations gragh paramed by level', fontsize=14, fontweight='bold')",
"> rlt[1]: rlt = 1 else: rlt = 2 if rlt == tmpy:",
"as plt from NeuralNetwork import BPnetwork as bpn fig = plt.figure() fig.suptitle(u'Informations gragh",
"#fig.savefig('level.png', dpi=100) #fig.show() tr = 0 fl = 0 for i in xrange(100):",
"# tmp1 = dp(tmp) # ty2 = jg1.cal(tmp)[0] # ty3 = jg2.cal(tmp1) #",
"xrange(10): # tmp = random.uniform(0.1, 25.0) # ty1 = tf.cal(tmp) # tmp =",
"= 0 for i in xrange(100): p = random.random() if p >= 0.5:",
"2.5) set12 = nd(3, 2.5) set13 = nd(3, 2.5) set21 = nd(-6, 1.0)",
"for item in x] #ax.plot(x, y1, 'r', x, y2, 'b', x, y3, 'y')",
"param[1] + param[0] # rlt = (ty1, ty2, ty3) # print rlt #x",
"y = [] y2 = [] for i in xrange(1000): x.append([set11.val(), set12.val(), set13.val()])",
"== tmpy: tr += 1 else: fl += 1 print \"result: \" +",
"as glr from LinearRegression.regularization import regularization as rg import numpy as np from",
"0.1 * (x ** 3) + 7 ) tf = testFunc() x =",
"from LinearRegression.GradientDescent import gradientDescent as glr from LinearRegression.regularization import regularization as rg import",
"as bpn fig = plt.figure() fig.suptitle(u'Informations gragh paramed by level', fontsize=14, fontweight='bold') ax",
"nd(-6, 1.0) set23 = nd(-6, 1.0) class testFunc(functionObject): def __init__(self): pass def cal(self,",
"rlt #x = np.arange(-20.0, 20.0, 0.01) #y1 = [tf.cal(item) for item in x]",
"bpn([3, 4, 4, 2]) jg.train(x, y, 0.03, 0.0005) #for i in xrange(10): #",
"= 1 else: tmpx = [set21.val(), set22.val(), set23.val()] tmpy = 2 rlt =",
"ty2 * param[1] + param[0] # rlt = (ty1, ty2, ty3) # print",
"= jg1.cal(tmp)[0] # ty3 = jg2.cal(tmp1) # ty2 = ty2 * param[1] +",
"as hlr from LinearRegression.GradientDescent import gradientDescent as glr from LinearRegression.regularization import regularization as",
"ty1 = tf.cal(tmp) # tmp = [tmp * 1, tmp ** 2, tmp",
"tmp ** 2, tmp ** 3] # tmp1 = dp(tmp) # ty2 =",
"plt.figure() fig.suptitle(u'Informations gragh paramed by level', fontsize=14, fontweight='bold') ax = fig.add_subplot(111) set11 =",
"if p >= 0.5: tmpx = [set11.val(), set12.val(), set13.val()] tmpy = 1 else:",
"= [set21.val(), set22.val(), set23.val()] tmpy = 2 rlt = jg.cal(tmpx) if rlt[0] >",
"item in x] #ax.plot(x, y1, 'r', x, y2, 'b', x, y3, 'y') #fig.savefig('level.png',",
"for i in xrange(100): p = random.random() if p >= 0.5: tmpx =",
"1.0) set23 = nd(-6, 1.0) class testFunc(functionObject): def __init__(self): pass def cal(self, x):",
"0 fl = 0 for i in xrange(100): p = random.random() if p",
"hlr from LinearRegression.GradientDescent import gradientDescent as glr from LinearRegression.regularization import regularization as rg",
"in y2] jg = bpn([3, 4, 4, 2]) jg.train(x, y, 0.03, 0.0005) #for",
"import gradientDescent as glr from LinearRegression.regularization import regularization as rg import numpy as",
"= plt.figure() fig.suptitle(u'Informations gragh paramed by level', fontsize=14, fontweight='bold') ax = fig.add_subplot(111) set11",
"import * from Distribution import NormalDistribution as nd import matplotlib.pyplot as plt from",
"if rlt == tmpy: tr += 1 else: fl += 1 print \"result:",
"import random import math from Function import * from Distribution import NormalDistribution as",
"jg = bpn([3, 4, 4, 2]) jg.train(x, y, 0.03, 0.0005) #for i in",
"deepcopy as dp import random import math from Function import * from Distribution",
"nd(-6, 1.0) set22 = nd(-6, 1.0) set23 = nd(-6, 1.0) class testFunc(functionObject): def",
"import hugeScaleLR as hlr from LinearRegression.GradientDescent import gradientDescent as glr from LinearRegression.regularization import",
"in xrange(1000): x.append([set21.val(), set22.val(), set23.val()]) y.append([0, 1]) y2 = [[item] for item in",
"[[item] for item in y2] jg = bpn([3, 4, 4, 2]) jg.train(x, y,",
"y2] jg = bpn([3, 4, 4, 2]) jg.train(x, y, 0.03, 0.0005) #for i",
"set13 = nd(3, 2.5) set21 = nd(-6, 1.0) set22 = nd(-6, 1.0) set23",
"= testFunc() x = [] y = [] y2 = [] for i",
"# tmp = [tmp * 1, tmp ** 2, tmp ** 3] #",
"0.7 * x - 7 * (x ** 2) + 0.1 * (x",
"'y') #fig.savefig('level.png', dpi=100) #fig.show() tr = 0 fl = 0 for i in",
"= [set11.val(), set12.val(), set13.val()] tmpy = 1 else: tmpx = [set21.val(), set22.val(), set23.val()]",
"ty2, ty3) # print rlt #x = np.arange(-20.0, 20.0, 0.01) #y1 = [tf.cal(item)",
"= nd(-6, 1.0) class testFunc(functionObject): def __init__(self): pass def cal(self, x): return (",
"= random.uniform(0.1, 25.0) # ty1 = tf.cal(tmp) # tmp = [tmp * 1,",
"p = random.random() if p >= 0.5: tmpx = [set11.val(), set12.val(), set13.val()] tmpy",
"gragh paramed by level', fontsize=14, fontweight='bold') ax = fig.add_subplot(111) set11 = nd(3, 2.5)",
"x - 7 * (x ** 2) + 0.1 * (x ** 3)",
"+ 0.1 * (x ** 3) + 7 ) tf = testFunc() x",
"( 0.7 * x - 7 * (x ** 2) + 0.1 *",
"** 3] # tmp1 = dp(tmp) # ty2 = jg1.cal(tmp)[0] # ty3 =",
"ty3) # print rlt #x = np.arange(-20.0, 20.0, 0.01) #y1 = [tf.cal(item) for",
"item ** 3]) for item in x] #ax.plot(x, y1, 'r', x, y2, 'b',",
"fig = plt.figure() fig.suptitle(u'Informations gragh paramed by level', fontsize=14, fontweight='bold') ax = fig.add_subplot(111)",
"set13.val()] tmpy = 1 else: tmpx = [set21.val(), set22.val(), set23.val()] tmpy = 2",
"xrange(1000): x.append([set11.val(), set12.val(), set13.val()]) y.append([1, 0]) for i in xrange(1000): x.append([set21.val(), set22.val(), set23.val()])",
"item in x] #y3 = [jg2.cal([item, item ** 2, item ** 3]) for",
"= nd(3, 2.5) set13 = nd(3, 2.5) set21 = nd(-6, 1.0) set22 =",
"else: tmpx = [set21.val(), set22.val(), set23.val()] tmpy = 2 rlt = jg.cal(tmpx) if",
"x] #ax.plot(x, y1, 'r', x, y2, 'b', x, y3, 'y') #fig.savefig('level.png', dpi=100) #fig.show()",
"2.5) set13 = nd(3, 2.5) set21 = nd(-6, 1.0) set22 = nd(-6, 1.0)",
"as np from copy import deepcopy as dp import random import math from",
"set23.val()] tmpy = 2 rlt = jg.cal(tmpx) if rlt[0] > rlt[1]: rlt =",
"[jg2.cal([item, item ** 2, item ** 3]) for item in x] #ax.plot(x, y1,",
"x.append([set11.val(), set12.val(), set13.val()]) y.append([1, 0]) for i in xrange(1000): x.append([set21.val(), set22.val(), set23.val()]) y.append([0,",
"set12.val(), set13.val()] tmpy = 1 else: tmpx = [set21.val(), set22.val(), set23.val()] tmpy =",
"* x - 7 * (x ** 2) + 0.1 * (x **",
"random import math from Function import * from Distribution import NormalDistribution as nd",
"1.0) set22 = nd(-6, 1.0) set23 = nd(-6, 1.0) class testFunc(functionObject): def __init__(self):",
"# ty3 = jg2.cal(tmp1) # ty2 = ty2 * param[1] + param[0] #",
"2) + 0.1 * (x ** 3) + 7 ) tf = testFunc()",
"4, 4, 2]) jg.train(x, y, 0.03, 0.0005) #for i in xrange(10): # tmp",
"= [jg1.cal([item, item ** 2, item ** 3])[0] * param[1] + param[0] for",
"x] #y3 = [jg2.cal([item, item ** 2, item ** 3]) for item in",
"glr from LinearRegression.regularization import regularization as rg import numpy as np from copy",
"set22.val(), set23.val()] tmpy = 2 rlt = jg.cal(tmpx) if rlt[0] > rlt[1]: rlt",
"= nd(3, 2.5) set12 = nd(3, 2.5) set13 = nd(3, 2.5) set21 =",
"from LinearRegression.HugeScaleLR import hugeScaleLR as hlr from LinearRegression.GradientDescent import gradientDescent as glr from",
"Distribution import NormalDistribution as nd import matplotlib.pyplot as plt from NeuralNetwork import BPnetwork",
"from LinearRegression.regularization import regularization as rg import numpy as np from copy import",
"NormalDistribution as nd import matplotlib.pyplot as plt from NeuralNetwork import BPnetwork as bpn",
"0.01) #y1 = [tf.cal(item) for item in x] #y2 = [jg1.cal([item, item **",
"jg2.cal(tmp1) # ty2 = ty2 * param[1] + param[0] # rlt = (ty1,",
"set12.val(), set13.val()]) y.append([1, 0]) for i in xrange(1000): x.append([set21.val(), set22.val(), set23.val()]) y.append([0, 1])",
"# ty1 = tf.cal(tmp) # tmp = [tmp * 1, tmp ** 2,",
"= 2 rlt = jg.cal(tmpx) if rlt[0] > rlt[1]: rlt = 1 else:",
"for i in xrange(1000): x.append([set21.val(), set22.val(), set23.val()]) y.append([0, 1]) y2 = [[item] for",
"#x = np.arange(-20.0, 20.0, 0.01) #y1 = [tf.cal(item) for item in x] #y2",
"7 * (x ** 2) + 0.1 * (x ** 3) + 7",
"* param[1] + param[0] # rlt = (ty1, ty2, ty3) # print rlt",
"# print rlt #x = np.arange(-20.0, 20.0, 0.01) #y1 = [tf.cal(item) for item",
"= dp(tmp) # ty2 = jg1.cal(tmp)[0] # ty3 = jg2.cal(tmp1) # ty2 =",
"as rg import numpy as np from copy import deepcopy as dp import",
"#y1 = [tf.cal(item) for item in x] #y2 = [jg1.cal([item, item ** 2,",
"= np.arange(-20.0, 20.0, 0.01) #y1 = [tf.cal(item) for item in x] #y2 =",
"tmpx = [set11.val(), set12.val(), set13.val()] tmpy = 1 else: tmpx = [set21.val(), set22.val(),",
"tf.cal(tmp) # tmp = [tmp * 1, tmp ** 2, tmp ** 3]",
"tr += 1 else: fl += 1 print \"result: \" + str(float(tr) /",
"set12 = nd(3, 2.5) set13 = nd(3, 2.5) set21 = nd(-6, 1.0) set22",
"0.0005) #for i in xrange(10): # tmp = random.uniform(0.1, 25.0) # ty1 =",
"if rlt[0] > rlt[1]: rlt = 1 else: rlt = 2 if rlt",
"3] # tmp1 = dp(tmp) # ty2 = jg1.cal(tmp)[0] # ty3 = jg2.cal(tmp1)",
"np.arange(-20.0, 20.0, 0.01) #y1 = [tf.cal(item) for item in x] #y2 = [jg1.cal([item,",
"y3, 'y') #fig.savefig('level.png', dpi=100) #fig.show() tr = 0 fl = 0 for i",
"7 ) tf = testFunc() x = [] y = [] y2 =",
"else: rlt = 2 if rlt == tmpy: tr += 1 else: fl",
"tf = testFunc() x = [] y = [] y2 = [] for",
"tr = 0 fl = 0 for i in xrange(100): p = random.random()",
"math from Function import * from Distribution import NormalDistribution as nd import matplotlib.pyplot",
"= [tmp * 1, tmp ** 2, tmp ** 3] # tmp1 =",
"xrange(100): p = random.random() if p >= 0.5: tmpx = [set11.val(), set12.val(), set13.val()]",
"item ** 3])[0] * param[1] + param[0] for item in x] #y3 =",
"def cal(self, x): return ( 0.7 * x - 7 * (x **",
"* (x ** 3) + 7 ) tf = testFunc() x = []",
"+ param[0] for item in x] #y3 = [jg2.cal([item, item ** 2, item",
"class testFunc(functionObject): def __init__(self): pass def cal(self, x): return ( 0.7 * x",
"def __init__(self): pass def cal(self, x): return ( 0.7 * x - 7",
"tmpy = 2 rlt = jg.cal(tmpx) if rlt[0] > rlt[1]: rlt = 1",
"i in xrange(100): p = random.random() if p >= 0.5: tmpx = [set11.val(),",
"set23 = nd(-6, 1.0) class testFunc(functionObject): def __init__(self): pass def cal(self, x): return",
"xrange(1000): x.append([set21.val(), set22.val(), set23.val()]) y.append([0, 1]) y2 = [[item] for item in y2]",
"= nd(-6, 1.0) set23 = nd(-6, 1.0) class testFunc(functionObject): def __init__(self): pass def",
"y, 0.03, 0.0005) #for i in xrange(10): # tmp = random.uniform(0.1, 25.0) #",
"param[0] for item in x] #y3 = [jg2.cal([item, item ** 2, item **",
"[] for i in xrange(1000): x.append([set11.val(), set12.val(), set13.val()]) y.append([1, 0]) for i in",
"fontweight='bold') ax = fig.add_subplot(111) set11 = nd(3, 2.5) set12 = nd(3, 2.5) set13",
"set23.val()]) y.append([0, 1]) y2 = [[item] for item in y2] jg = bpn([3,",
"fontsize=14, fontweight='bold') ax = fig.add_subplot(111) set11 = nd(3, 2.5) set12 = nd(3, 2.5)",
"y.append([1, 0]) for i in xrange(1000): x.append([set21.val(), set22.val(), set23.val()]) y.append([0, 1]) y2 =",
"nd(3, 2.5) set12 = nd(3, 2.5) set13 = nd(3, 2.5) set21 = nd(-6,",
"2 if rlt == tmpy: tr += 1 else: fl += 1 print",
"** 3])[0] * param[1] + param[0] for item in x] #y3 = [jg2.cal([item,",
"paramed by level', fontsize=14, fontweight='bold') ax = fig.add_subplot(111) set11 = nd(3, 2.5) set12",
"rlt = 2 if rlt == tmpy: tr += 1 else: fl +=",
"set22 = nd(-6, 1.0) set23 = nd(-6, 1.0) class testFunc(functionObject): def __init__(self): pass",
"#y3 = [jg2.cal([item, item ** 2, item ** 3]) for item in x]",
"i in xrange(1000): x.append([set11.val(), set12.val(), set13.val()]) y.append([1, 0]) for i in xrange(1000): x.append([set21.val(),",
"fl = 0 for i in xrange(100): p = random.random() if p >=",
"jg.cal(tmpx) if rlt[0] > rlt[1]: rlt = 1 else: rlt = 2 if",
"#ax.plot(x, y1, 'r', x, y2, 'b', x, y3, 'y') #fig.savefig('level.png', dpi=100) #fig.show() tr",
"tmpx = [set21.val(), set22.val(), set23.val()] tmpy = 2 rlt = jg.cal(tmpx) if rlt[0]",
"item ** 2, item ** 3])[0] * param[1] + param[0] for item in",
"dp(tmp) # ty2 = jg1.cal(tmp)[0] # ty3 = jg2.cal(tmp1) # ty2 = ty2",
"1.0) class testFunc(functionObject): def __init__(self): pass def cal(self, x): return ( 0.7 *",
"1, tmp ** 2, tmp ** 3] # tmp1 = dp(tmp) # ty2",
"rg import numpy as np from copy import deepcopy as dp import random",
"3])[0] * param[1] + param[0] for item in x] #y3 = [jg2.cal([item, item",
"numpy as np from copy import deepcopy as dp import random import math",
"** 3]) for item in x] #ax.plot(x, y1, 'r', x, y2, 'b', x,",
"ax = fig.add_subplot(111) set11 = nd(3, 2.5) set12 = nd(3, 2.5) set13 =",
"(x ** 3) + 7 ) tf = testFunc() x = [] y",
"dp import random import math from Function import * from Distribution import NormalDistribution",
"** 3) + 7 ) tf = testFunc() x = [] y =",
"* 1, tmp ** 2, tmp ** 3] # tmp1 = dp(tmp) #",
"rlt = (ty1, ty2, ty3) # print rlt #x = np.arange(-20.0, 20.0, 0.01)",
"level', fontsize=14, fontweight='bold') ax = fig.add_subplot(111) set11 = nd(3, 2.5) set12 = nd(3,",
"[] y = [] y2 = [] for i in xrange(1000): x.append([set11.val(), set12.val(),",
"p >= 0.5: tmpx = [set11.val(), set12.val(), set13.val()] tmpy = 1 else: tmpx",
"25.0) # ty1 = tf.cal(tmp) # tmp = [tmp * 1, tmp **",
"= [] for i in xrange(1000): x.append([set11.val(), set12.val(), set13.val()]) y.append([1, 0]) for i",
"matplotlib.pyplot as plt from NeuralNetwork import BPnetwork as bpn fig = plt.figure() fig.suptitle(u'Informations",
"[set21.val(), set22.val(), set23.val()] tmpy = 2 rlt = jg.cal(tmpx) if rlt[0] > rlt[1]:",
"ty3 = jg2.cal(tmp1) # ty2 = ty2 * param[1] + param[0] # rlt",
"= 0 fl = 0 for i in xrange(100): p = random.random() if",
"# ty2 = jg1.cal(tmp)[0] # ty3 = jg2.cal(tmp1) # ty2 = ty2 *",
"in xrange(10): # tmp = random.uniform(0.1, 25.0) # ty1 = tf.cal(tmp) # tmp",
"in x] #y3 = [jg2.cal([item, item ** 2, item ** 3]) for item",
"in x] #ax.plot(x, y1, 'r', x, y2, 'b', x, y3, 'y') #fig.savefig('level.png', dpi=100)",
"3) + 7 ) tf = testFunc() x = [] y = []",
"= [] y = [] y2 = [] for i in xrange(1000): x.append([set11.val(),",
"dpi=100) #fig.show() tr = 0 fl = 0 for i in xrange(100): p",
"# rlt = (ty1, ty2, ty3) # print rlt #x = np.arange(-20.0, 20.0,",
"3]) for item in x] #ax.plot(x, y1, 'r', x, y2, 'b', x, y3,",
"x = [] y = [] y2 = [] for i in xrange(1000):",
"'b', x, y3, 'y') #fig.savefig('level.png', dpi=100) #fig.show() tr = 0 fl = 0",
"y1, 'r', x, y2, 'b', x, y3, 'y') #fig.savefig('level.png', dpi=100) #fig.show() tr =",
"import regularization as rg import numpy as np from copy import deepcopy as",
"2.5) set21 = nd(-6, 1.0) set22 = nd(-6, 1.0) set23 = nd(-6, 1.0)",
"item in x] #y2 = [jg1.cal([item, item ** 2, item ** 3])[0] *",
"= nd(-6, 1.0) set22 = nd(-6, 1.0) set23 = nd(-6, 1.0) class testFunc(functionObject):",
"param[1] + param[0] for item in x] #y3 = [jg2.cal([item, item ** 2,",
"[] y2 = [] for i in xrange(1000): x.append([set11.val(), set12.val(), set13.val()]) y.append([1, 0])",
"tmp ** 3] # tmp1 = dp(tmp) # ty2 = jg1.cal(tmp)[0] # ty3",
"= jg.cal(tmpx) if rlt[0] > rlt[1]: rlt = 1 else: rlt = 2",
"1]) y2 = [[item] for item in y2] jg = bpn([3, 4, 4,",
"= 1 else: rlt = 2 if rlt == tmpy: tr += 1",
"= tf.cal(tmp) # tmp = [tmp * 1, tmp ** 2, tmp **",
"__init__(self): pass def cal(self, x): return ( 0.7 * x - 7 *",
"rlt = jg.cal(tmpx) if rlt[0] > rlt[1]: rlt = 1 else: rlt =",
"from Distribution import NormalDistribution as nd import matplotlib.pyplot as plt from NeuralNetwork import",
"= random.random() if p >= 0.5: tmpx = [set11.val(), set12.val(), set13.val()] tmpy =",
"x.append([set21.val(), set22.val(), set23.val()]) y.append([0, 1]) y2 = [[item] for item in y2] jg",
"random.random() if p >= 0.5: tmpx = [set11.val(), set12.val(), set13.val()] tmpy = 1",
"i in xrange(10): # tmp = random.uniform(0.1, 25.0) # ty1 = tf.cal(tmp) #",
"ty2 = ty2 * param[1] + param[0] # rlt = (ty1, ty2, ty3)",
"2 rlt = jg.cal(tmpx) if rlt[0] > rlt[1]: rlt = 1 else: rlt",
"param[0] # rlt = (ty1, ty2, ty3) # print rlt #x = np.arange(-20.0,",
"'r', x, y2, 'b', x, y3, 'y') #fig.savefig('level.png', dpi=100) #fig.show() tr = 0",
"rlt == tmpy: tr += 1 else: fl += 1 print \"result: \"",
"* from Distribution import NormalDistribution as nd import matplotlib.pyplot as plt from NeuralNetwork",
"0]) for i in xrange(1000): x.append([set21.val(), set22.val(), set23.val()]) y.append([0, 1]) y2 = [[item]",
"for item in x] #y3 = [jg2.cal([item, item ** 2, item ** 3])",
"Function import * from Distribution import NormalDistribution as nd import matplotlib.pyplot as plt",
"#fig.show() tr = 0 fl = 0 for i in xrange(100): p =",
"= (ty1, ty2, ty3) # print rlt #x = np.arange(-20.0, 20.0, 0.01) #y1",
"2, item ** 3]) for item in x] #ax.plot(x, y1, 'r', x, y2,",
"[tf.cal(item) for item in x] #y2 = [jg1.cal([item, item ** 2, item **",
"from NeuralNetwork import BPnetwork as bpn fig = plt.figure() fig.suptitle(u'Informations gragh paramed by",
"set22.val(), set23.val()]) y.append([0, 1]) y2 = [[item] for item in y2] jg =",
"tmp = random.uniform(0.1, 25.0) # ty1 = tf.cal(tmp) # tmp = [tmp *",
"jg1.cal(tmp)[0] # ty3 = jg2.cal(tmp1) # ty2 = ty2 * param[1] + param[0]",
"tmpy: tr += 1 else: fl += 1 print \"result: \" + str(float(tr)",
"1 else: fl += 1 print \"result: \" + str(float(tr) / (tr +",
"= nd(3, 2.5) set21 = nd(-6, 1.0) set22 = nd(-6, 1.0) set23 =",
"* param[1] + param[0] for item in x] #y3 = [jg2.cal([item, item **",
"cal(self, x): return ( 0.7 * x - 7 * (x ** 2)",
"item in y2] jg = bpn([3, 4, 4, 2]) jg.train(x, y, 0.03, 0.0005)",
"#for i in xrange(10): # tmp = random.uniform(0.1, 25.0) # ty1 = tf.cal(tmp)",
"fig.suptitle(u'Informations gragh paramed by level', fontsize=14, fontweight='bold') ax = fig.add_subplot(111) set11 = nd(3,",
"NeuralNetwork import BPnetwork as bpn fig = plt.figure() fig.suptitle(u'Informations gragh paramed by level',",
"else: fl += 1 print \"result: \" + str(float(tr) / (tr + fl))",
"0.5: tmpx = [set11.val(), set12.val(), set13.val()] tmpy = 1 else: tmpx = [set21.val(),",
"1 else: tmpx = [set21.val(), set22.val(), set23.val()] tmpy = 2 rlt = jg.cal(tmpx)",
"item ** 2, item ** 3]) for item in x] #ax.plot(x, y1, 'r',",
"= ty2 * param[1] + param[0] # rlt = (ty1, ty2, ty3) #",
"import math from Function import * from Distribution import NormalDistribution as nd import",
"= jg2.cal(tmp1) # ty2 = ty2 * param[1] + param[0] # rlt =",
"+= 1 else: fl += 1 print \"result: \" + str(float(tr) / (tr",
"LinearRegression.GradientDescent import gradientDescent as glr from LinearRegression.regularization import regularization as rg import numpy",
"tmp1 = dp(tmp) # ty2 = jg1.cal(tmp)[0] # ty3 = jg2.cal(tmp1) # ty2",
"hugeScaleLR as hlr from LinearRegression.GradientDescent import gradientDescent as glr from LinearRegression.regularization import regularization",
">= 0.5: tmpx = [set11.val(), set12.val(), set13.val()] tmpy = 1 else: tmpx =",
"random.uniform(0.1, 25.0) # ty1 = tf.cal(tmp) # tmp = [tmp * 1, tmp",
"y2, 'b', x, y3, 'y') #fig.savefig('level.png', dpi=100) #fig.show() tr = 0 fl =",
"x] #y2 = [jg1.cal([item, item ** 2, item ** 3])[0] * param[1] +",
"= [tf.cal(item) for item in x] #y2 = [jg1.cal([item, item ** 2, item",
"nd(-6, 1.0) class testFunc(functionObject): def __init__(self): pass def cal(self, x): return ( 0.7",
"import NormalDistribution as nd import matplotlib.pyplot as plt from NeuralNetwork import BPnetwork as",
"#y2 = [jg1.cal([item, item ** 2, item ** 3])[0] * param[1] + param[0]",
"+ 7 ) tf = testFunc() x = [] y = [] y2",
"2, tmp ** 3] # tmp1 = dp(tmp) # ty2 = jg1.cal(tmp)[0] #"
] |
[
"e está ou não na lista''' valores = [] while True: valores.append(int(input('Digite um",
"forma decrescente. C) Se o valor 5 foi digitado e está ou não",
"valores.sort(reverse=True) print(f'Os valores em ordem decrescente são {valores}') if 5 in valores: print('O",
"valores, ordenada de forma decrescente. C) Se o valor 5 foi digitado e",
"valor 5 faz parte da lista! ') else: print('O valor 5 não foi",
"decrescente. C) Se o valor 5 foi digitado e está ou não na",
"if resp in 'Nn': break print('='*30) print(f'Você digitou {len(valores)} elementos. ') valores.sort(reverse=True) print(f'Os",
"')) if resp in 'Nn': break print('='*30) print(f'Você digitou {len(valores)} elementos. ') valores.sort(reverse=True)",
"ordem decrescente são {valores}') if 5 in valores: print('O valor 5 faz parte",
"5 foi digitado e está ou não na lista''' valores = [] while",
"C) Se o valor 5 foi digitado e está ou não na lista'''",
"digitados. B) A Lista de valores, ordenada de forma decrescente. C) Se o",
"foi digitado e está ou não na lista''' valores = [] while True:",
"em uma lista, depois disso,mostre: A) Quantos números foram digitados. B) A Lista",
"valores = [] while True: valores.append(int(input('Digite um valor: '))) resp = str(input('Gostaria de",
"vários números e colocar em uma lista, depois disso,mostre: A) Quantos números foram",
"elementos. ') valores.sort(reverse=True) print(f'Os valores em ordem decrescente são {valores}') if 5 in",
"if 5 in valores: print('O valor 5 faz parte da lista! ') else:",
"5 faz parte da lista! ') else: print('O valor 5 não foi encontrado",
"A Lista de valores, ordenada de forma decrescente. C) Se o valor 5",
"programa que vai ler vários números e colocar em uma lista, depois disso,mostre:",
"True: valores.append(int(input('Digite um valor: '))) resp = str(input('Gostaria de continuar? [S/N] ')) if",
"in valores: print('O valor 5 faz parte da lista! ') else: print('O valor",
"de valores, ordenada de forma decrescente. C) Se o valor 5 foi digitado",
"foram digitados. B) A Lista de valores, ordenada de forma decrescente. C) Se",
"e colocar em uma lista, depois disso,mostre: A) Quantos números foram digitados. B)",
"<filename>Ex81.py '''Faça um programa que vai ler vários números e colocar em uma",
"um valor: '))) resp = str(input('Gostaria de continuar? [S/N] ')) if resp in",
"Se o valor 5 foi digitado e está ou não na lista''' valores",
"lista, depois disso,mostre: A) Quantos números foram digitados. B) A Lista de valores,",
"while True: valores.append(int(input('Digite um valor: '))) resp = str(input('Gostaria de continuar? [S/N] '))",
"Quantos números foram digitados. B) A Lista de valores, ordenada de forma decrescente.",
"A) Quantos números foram digitados. B) A Lista de valores, ordenada de forma",
"parte da lista! ') else: print('O valor 5 não foi encontrado na lista!",
"= str(input('Gostaria de continuar? [S/N] ')) if resp in 'Nn': break print('='*30) print(f'Você",
"= [] while True: valores.append(int(input('Digite um valor: '))) resp = str(input('Gostaria de continuar?",
"está ou não na lista''' valores = [] while True: valores.append(int(input('Digite um valor:",
"print('O valor 5 faz parte da lista! ') else: print('O valor 5 não",
"resp in 'Nn': break print('='*30) print(f'Você digitou {len(valores)} elementos. ') valores.sort(reverse=True) print(f'Os valores",
"que vai ler vários números e colocar em uma lista, depois disso,mostre: A)",
"da lista! ') else: print('O valor 5 não foi encontrado na lista! ')",
"de forma decrescente. C) Se o valor 5 foi digitado e está ou",
"'''Faça um programa que vai ler vários números e colocar em uma lista,",
"uma lista, depois disso,mostre: A) Quantos números foram digitados. B) A Lista de",
"ou não na lista''' valores = [] while True: valores.append(int(input('Digite um valor: ')))",
"o valor 5 foi digitado e está ou não na lista''' valores =",
"str(input('Gostaria de continuar? [S/N] ')) if resp in 'Nn': break print('='*30) print(f'Você digitou",
"print('='*30) print(f'Você digitou {len(valores)} elementos. ') valores.sort(reverse=True) print(f'Os valores em ordem decrescente são",
"valores em ordem decrescente são {valores}') if 5 in valores: print('O valor 5",
"na lista''' valores = [] while True: valores.append(int(input('Digite um valor: '))) resp =",
"'))) resp = str(input('Gostaria de continuar? [S/N] ')) if resp in 'Nn': break",
"um programa que vai ler vários números e colocar em uma lista, depois",
"de continuar? [S/N] ')) if resp in 'Nn': break print('='*30) print(f'Você digitou {len(valores)}",
"vai ler vários números e colocar em uma lista, depois disso,mostre: A) Quantos",
"valor: '))) resp = str(input('Gostaria de continuar? [S/N] ')) if resp in 'Nn':",
"B) A Lista de valores, ordenada de forma decrescente. C) Se o valor",
"print(f'Você digitou {len(valores)} elementos. ') valores.sort(reverse=True) print(f'Os valores em ordem decrescente são {valores}')",
"[S/N] ')) if resp in 'Nn': break print('='*30) print(f'Você digitou {len(valores)} elementos. ')",
"in 'Nn': break print('='*30) print(f'Você digitou {len(valores)} elementos. ') valores.sort(reverse=True) print(f'Os valores em",
"são {valores}') if 5 in valores: print('O valor 5 faz parte da lista!",
"{len(valores)} elementos. ') valores.sort(reverse=True) print(f'Os valores em ordem decrescente são {valores}') if 5",
"ordenada de forma decrescente. C) Se o valor 5 foi digitado e está",
"[] while True: valores.append(int(input('Digite um valor: '))) resp = str(input('Gostaria de continuar? [S/N]",
"números foram digitados. B) A Lista de valores, ordenada de forma decrescente. C)",
"digitado e está ou não na lista''' valores = [] while True: valores.append(int(input('Digite",
"Lista de valores, ordenada de forma decrescente. C) Se o valor 5 foi",
"'Nn': break print('='*30) print(f'Você digitou {len(valores)} elementos. ') valores.sort(reverse=True) print(f'Os valores em ordem",
"depois disso,mostre: A) Quantos números foram digitados. B) A Lista de valores, ordenada",
"print(f'Os valores em ordem decrescente são {valores}') if 5 in valores: print('O valor",
"números e colocar em uma lista, depois disso,mostre: A) Quantos números foram digitados.",
"') valores.sort(reverse=True) print(f'Os valores em ordem decrescente são {valores}') if 5 in valores:",
"break print('='*30) print(f'Você digitou {len(valores)} elementos. ') valores.sort(reverse=True) print(f'Os valores em ordem decrescente",
"decrescente são {valores}') if 5 in valores: print('O valor 5 faz parte da",
"valores: print('O valor 5 faz parte da lista! ') else: print('O valor 5",
"não na lista''' valores = [] while True: valores.append(int(input('Digite um valor: '))) resp",
"valores.append(int(input('Digite um valor: '))) resp = str(input('Gostaria de continuar? [S/N] ')) if resp",
"{valores}') if 5 in valores: print('O valor 5 faz parte da lista! ')",
"colocar em uma lista, depois disso,mostre: A) Quantos números foram digitados. B) A",
"digitou {len(valores)} elementos. ') valores.sort(reverse=True) print(f'Os valores em ordem decrescente são {valores}') if",
"valor 5 foi digitado e está ou não na lista''' valores = []",
"lista''' valores = [] while True: valores.append(int(input('Digite um valor: '))) resp = str(input('Gostaria",
"5 in valores: print('O valor 5 faz parte da lista! ') else: print('O",
"disso,mostre: A) Quantos números foram digitados. B) A Lista de valores, ordenada de",
"continuar? [S/N] ')) if resp in 'Nn': break print('='*30) print(f'Você digitou {len(valores)} elementos.",
"faz parte da lista! ') else: print('O valor 5 não foi encontrado na",
"resp = str(input('Gostaria de continuar? [S/N] ')) if resp in 'Nn': break print('='*30)",
"ler vários números e colocar em uma lista, depois disso,mostre: A) Quantos números",
"em ordem decrescente são {valores}') if 5 in valores: print('O valor 5 faz"
] |
[
"'127.0.0.1' # Standard loopback interface address (localhost) PORT = 65433 # Port to",
"interface address (localhost) PORT = 65433 # Port to listen on (non-privileged ports",
"0: Male, 1: Female birthday = split[3] # yyyy/mm/dd countryc = split[4] #",
"Standard loopback interface address (localhost) PORT = 65433 # Port to listen on",
"= '127.0.0.1' # Standard loopback interface address (localhost) PORT = 65433 # Port",
"= s.accept() with conn: print('Connected by', addr) while True: data = conn.recv(1024).decode('utf-8') if",
"socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() conn, addr = s.accept() with conn: print('Connected",
"socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() conn, addr = s.accept() with conn:",
"key = KeyCreator() f = open(f'Etc/Users Account/Public Keys/{username}.pem','wb') f.write(key.public) # you should create",
"you should create it f.close() conn.sendall(key.private) conn.sendall(key.public) else: conn.sendall(b'e: account exists') except: conn.sendall(b'e:",
"# Standard loopback interface address (localhost) PORT = 65433 # Port to listen",
"split[1] # <NAME> gender = split[2] # 0: Male, 1: Female birthday =",
"split[2] # 0: Male, 1: Female birthday = split[3] # yyyy/mm/dd countryc =",
"s.accept() with conn: print('Connected by', addr) while True: data = conn.recv(1024).decode('utf-8') if data:",
"split[3] # yyyy/mm/dd countryc = split[4] # IR city = split[5] # Mashhad",
"manijamali2003 if not os.path.isfile (f'Etc/Users Account/{username}'): fullname = split[1] # <NAME> gender =",
"split = data.split(',') username = split[0] # manijamali2003 if not os.path.isfile (f'Etc/Users Account/{username}'):",
"f.write(key.public) # you should create it f.close() conn.sendall(key.private) conn.sendall(key.public) else: conn.sendall(b'e: account exists')",
"<NAME> gender = split[2] # 0: Male, 1: Female birthday = split[3] #",
"<reponame>manijamali2003/Nava #!/usr/bin/env python3 import os import socket, random,hashlib from Nava import * HOST",
"= split[4] # IR city = split[5] # Mashhad zipcode = split[6] #",
"data.split(',') username = split[0] # manijamali2003 if not os.path.isfile (f'Etc/Users Account/{username}'): fullname =",
"# 11111111 hashcode = split[7] # hash of password sha3_513 f = open(f'Etc/Users",
"Account/{username}','wb') f.write(f'{fullname},{gender},{birthday},{countryc},{city},{zipcode},{hashcode}'.encode()) f.close() key = KeyCreator() f = open(f'Etc/Users Account/Public Keys/{username}.pem','wb') f.write(key.public) #",
"HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT = 65433 #",
"f = open(f'Etc/Users Account/Public Keys/{username}.pem','wb') f.write(key.public) # you should create it f.close() conn.sendall(key.private)",
"= data.split(',') username = split[0] # manijamali2003 if not os.path.isfile (f'Etc/Users Account/{username}'): fullname",
"from Nava import * HOST = '127.0.0.1' # Standard loopback interface address (localhost)",
"s: s.bind((HOST, PORT)) s.listen() conn, addr = s.accept() with conn: print('Connected by', addr)",
"(f'Etc/Users Account/{username}'): fullname = split[1] # <NAME> gender = split[2] # 0: Male,",
"sha3_513 f = open(f'Etc/Users Account/{username}','wb') f.write(f'{fullname},{gender},{birthday},{countryc},{city},{zipcode},{hashcode}'.encode()) f.close() key = KeyCreator() f = open(f'Etc/Users",
"conn: print('Connected by', addr) while True: data = conn.recv(1024).decode('utf-8') if data: try: split",
"addr) while True: data = conn.recv(1024).decode('utf-8') if data: try: split = data.split(',') username",
"f.write(f'{fullname},{gender},{birthday},{countryc},{city},{zipcode},{hashcode}'.encode()) f.close() key = KeyCreator() f = open(f'Etc/Users Account/Public Keys/{username}.pem','wb') f.write(key.public) # you",
"fullname = split[1] # <NAME> gender = split[2] # 0: Male, 1: Female",
"= open(f'Etc/Users Account/Public Keys/{username}.pem','wb') f.write(key.public) # you should create it f.close() conn.sendall(key.private) conn.sendall(key.public)",
"create it f.close() conn.sendall(key.private) conn.sendall(key.public) else: conn.sendall(b'e: account exists') except: conn.sendall(b'e: some errors')",
"on (non-privileged ports are > 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT))",
"os.path.isfile (f'Etc/Users Account/{username}'): fullname = split[1] # <NAME> gender = split[2] # 0:",
"password sha3_513 f = open(f'Etc/Users Account/{username}','wb') f.write(f'{fullname},{gender},{birthday},{countryc},{city},{zipcode},{hashcode}'.encode()) f.close() key = KeyCreator() f =",
"= split[5] # Mashhad zipcode = split[6] # 11111111 hashcode = split[7] #",
"city = split[5] # Mashhad zipcode = split[6] # 11111111 hashcode = split[7]",
"(localhost) PORT = 65433 # Port to listen on (non-privileged ports are >",
"ports are > 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() conn,",
"= 65433 # Port to listen on (non-privileged ports are > 1023) with",
"f.close() key = KeyCreator() f = open(f'Etc/Users Account/Public Keys/{username}.pem','wb') f.write(key.public) # you should",
"IR city = split[5] # Mashhad zipcode = split[6] # 11111111 hashcode =",
"# you should create it f.close() conn.sendall(key.private) conn.sendall(key.public) else: conn.sendall(b'e: account exists') except:",
"Female birthday = split[3] # yyyy/mm/dd countryc = split[4] # IR city =",
"# 0: Male, 1: Female birthday = split[3] # yyyy/mm/dd countryc = split[4]",
"hashcode = split[7] # hash of password sha3_513 f = open(f'Etc/Users Account/{username}','wb') f.write(f'{fullname},{gender},{birthday},{countryc},{city},{zipcode},{hashcode}'.encode())",
"# IR city = split[5] # Mashhad zipcode = split[6] # 11111111 hashcode",
"if not os.path.isfile (f'Etc/Users Account/{username}'): fullname = split[1] # <NAME> gender = split[2]",
"= KeyCreator() f = open(f'Etc/Users Account/Public Keys/{username}.pem','wb') f.write(key.public) # you should create it",
"username = split[0] # manijamali2003 if not os.path.isfile (f'Etc/Users Account/{username}'): fullname = split[1]",
"= split[2] # 0: Male, 1: Female birthday = split[3] # yyyy/mm/dd countryc",
"import os import socket, random,hashlib from Nava import * HOST = '127.0.0.1' #",
"yyyy/mm/dd countryc = split[4] # IR city = split[5] # Mashhad zipcode =",
"gender = split[2] # 0: Male, 1: Female birthday = split[3] # yyyy/mm/dd",
"Account/Public Keys/{username}.pem','wb') f.write(key.public) # you should create it f.close() conn.sendall(key.private) conn.sendall(key.public) else: conn.sendall(b'e:",
"# hash of password sha3_513 f = open(f'Etc/Users Account/{username}','wb') f.write(f'{fullname},{gender},{birthday},{countryc},{city},{zipcode},{hashcode}'.encode()) f.close() key =",
"not os.path.isfile (f'Etc/Users Account/{username}'): fullname = split[1] # <NAME> gender = split[2] #",
"= conn.recv(1024).decode('utf-8') if data: try: split = data.split(',') username = split[0] # manijamali2003",
"import socket, random,hashlib from Nava import * HOST = '127.0.0.1' # Standard loopback",
"of password sha3_513 f = open(f'Etc/Users Account/{username}','wb') f.write(f'{fullname},{gender},{birthday},{countryc},{city},{zipcode},{hashcode}'.encode()) f.close() key = KeyCreator() f",
"import * HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT =",
"Male, 1: Female birthday = split[3] # yyyy/mm/dd countryc = split[4] # IR",
"11111111 hashcode = split[7] # hash of password sha3_513 f = open(f'Etc/Users Account/{username}','wb')",
"split[0] # manijamali2003 if not os.path.isfile (f'Etc/Users Account/{username}'): fullname = split[1] # <NAME>",
"by', addr) while True: data = conn.recv(1024).decode('utf-8') if data: try: split = data.split(',')",
"birthday = split[3] # yyyy/mm/dd countryc = split[4] # IR city = split[5]",
"data: try: split = data.split(',') username = split[0] # manijamali2003 if not os.path.isfile",
"1: Female birthday = split[3] # yyyy/mm/dd countryc = split[4] # IR city",
"try: split = data.split(',') username = split[0] # manijamali2003 if not os.path.isfile (f'Etc/Users",
"split[7] # hash of password sha3_513 f = open(f'Etc/Users Account/{username}','wb') f.write(f'{fullname},{gender},{birthday},{countryc},{city},{zipcode},{hashcode}'.encode()) f.close() key",
"address (localhost) PORT = 65433 # Port to listen on (non-privileged ports are",
"to listen on (non-privileged ports are > 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:",
"split[4] # IR city = split[5] # Mashhad zipcode = split[6] # 11111111",
"listen on (non-privileged ports are > 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST,",
"Keys/{username}.pem','wb') f.write(key.public) # you should create it f.close() conn.sendall(key.private) conn.sendall(key.public) else: conn.sendall(b'e: account",
"open(f'Etc/Users Account/{username}','wb') f.write(f'{fullname},{gender},{birthday},{countryc},{city},{zipcode},{hashcode}'.encode()) f.close() key = KeyCreator() f = open(f'Etc/Users Account/Public Keys/{username}.pem','wb') f.write(key.public)",
"countryc = split[4] # IR city = split[5] # Mashhad zipcode = split[6]",
"should create it f.close() conn.sendall(key.private) conn.sendall(key.public) else: conn.sendall(b'e: account exists') except: conn.sendall(b'e: some",
"random,hashlib from Nava import * HOST = '127.0.0.1' # Standard loopback interface address",
"loopback interface address (localhost) PORT = 65433 # Port to listen on (non-privileged",
"as s: s.bind((HOST, PORT)) s.listen() conn, addr = s.accept() with conn: print('Connected by',",
"socket, random,hashlib from Nava import * HOST = '127.0.0.1' # Standard loopback interface",
"with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() conn, addr = s.accept() with",
"while True: data = conn.recv(1024).decode('utf-8') if data: try: split = data.split(',') username =",
"split[6] # 11111111 hashcode = split[7] # hash of password sha3_513 f =",
"Nava import * HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT",
"split[5] # Mashhad zipcode = split[6] # 11111111 hashcode = split[7] # hash",
"= split[7] # hash of password sha3_513 f = open(f'Etc/Users Account/{username}','wb') f.write(f'{fullname},{gender},{birthday},{countryc},{city},{zipcode},{hashcode}'.encode()) f.close()",
"s.listen() conn, addr = s.accept() with conn: print('Connected by', addr) while True: data",
"= split[3] # yyyy/mm/dd countryc = split[4] # IR city = split[5] #",
"with conn: print('Connected by', addr) while True: data = conn.recv(1024).decode('utf-8') if data: try:",
"#!/usr/bin/env python3 import os import socket, random,hashlib from Nava import * HOST =",
"True: data = conn.recv(1024).decode('utf-8') if data: try: split = data.split(',') username = split[0]",
"os import socket, random,hashlib from Nava import * HOST = '127.0.0.1' # Standard",
"conn.recv(1024).decode('utf-8') if data: try: split = data.split(',') username = split[0] # manijamali2003 if",
"are > 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() conn, addr",
"data = conn.recv(1024).decode('utf-8') if data: try: split = data.split(',') username = split[0] #",
"PORT = 65433 # Port to listen on (non-privileged ports are > 1023)",
"# Port to listen on (non-privileged ports are > 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM)",
"# Mashhad zipcode = split[6] # 11111111 hashcode = split[7] # hash of",
"= split[0] # manijamali2003 if not os.path.isfile (f'Etc/Users Account/{username}'): fullname = split[1] #",
"* HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT = 65433",
"= split[6] # 11111111 hashcode = split[7] # hash of password sha3_513 f",
"open(f'Etc/Users Account/Public Keys/{username}.pem','wb') f.write(key.public) # you should create it f.close() conn.sendall(key.private) conn.sendall(key.public) else:",
"f = open(f'Etc/Users Account/{username}','wb') f.write(f'{fullname},{gender},{birthday},{countryc},{city},{zipcode},{hashcode}'.encode()) f.close() key = KeyCreator() f = open(f'Etc/Users Account/Public",
"= split[1] # <NAME> gender = split[2] # 0: Male, 1: Female birthday",
"PORT)) s.listen() conn, addr = s.accept() with conn: print('Connected by', addr) while True:",
"= open(f'Etc/Users Account/{username}','wb') f.write(f'{fullname},{gender},{birthday},{countryc},{city},{zipcode},{hashcode}'.encode()) f.close() key = KeyCreator() f = open(f'Etc/Users Account/Public Keys/{username}.pem','wb')",
"addr = s.accept() with conn: print('Connected by', addr) while True: data = conn.recv(1024).decode('utf-8')",
"s.bind((HOST, PORT)) s.listen() conn, addr = s.accept() with conn: print('Connected by', addr) while",
"# <NAME> gender = split[2] # 0: Male, 1: Female birthday = split[3]",
"> 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() conn, addr =",
"if data: try: split = data.split(',') username = split[0] # manijamali2003 if not",
"print('Connected by', addr) while True: data = conn.recv(1024).decode('utf-8') if data: try: split =",
"Port to listen on (non-privileged ports are > 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as",
"# yyyy/mm/dd countryc = split[4] # IR city = split[5] # Mashhad zipcode",
"zipcode = split[6] # 11111111 hashcode = split[7] # hash of password sha3_513",
"conn, addr = s.accept() with conn: print('Connected by', addr) while True: data =",
"65433 # Port to listen on (non-privileged ports are > 1023) with socket.socket(socket.AF_INET,",
"KeyCreator() f = open(f'Etc/Users Account/Public Keys/{username}.pem','wb') f.write(key.public) # you should create it f.close()",
"# manijamali2003 if not os.path.isfile (f'Etc/Users Account/{username}'): fullname = split[1] # <NAME> gender",
"1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() conn, addr = s.accept()",
"Mashhad zipcode = split[6] # 11111111 hashcode = split[7] # hash of password",
"python3 import os import socket, random,hashlib from Nava import * HOST = '127.0.0.1'",
"hash of password sha3_513 f = open(f'Etc/Users Account/{username}','wb') f.write(f'{fullname},{gender},{birthday},{countryc},{city},{zipcode},{hashcode}'.encode()) f.close() key = KeyCreator()",
"(non-privileged ports are > 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen()",
"Account/{username}'): fullname = split[1] # <NAME> gender = split[2] # 0: Male, 1:"
] |
[
"name='PresentationCover', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.URLField(verbose_name='image')), ('label', models.CharField(blank=True, max_length=50, verbose_name='label')),",
"on 2018-02-20 06:45 from __future__ import unicode_literals from django.db import migrations, models import",
"models.CharField(choices=[('DES', 'description'), ('FEA', 'features')], default='DES', max_length=3)), ('default', models.BooleanField(default=False)), ], options={ 'verbose_name': 'Presentation Cover',",
"__future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies",
"'verbose_name_plural': 'Presentation Covers', }, ), migrations.RemoveField( model_name='presentation', name='features_cover', ), migrations.DeleteModel( name='FeaturesCover', ), migrations.AddField(",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('landing', '0008_remove_featurescover_active'), ] operations",
"name='FeaturesCover', ), migrations.AddField( model_name='presentation', name='presentation_covers', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='landing.PresentationCover', verbose_name='presentation cover'), ), ]",
"'Presentation Covers', }, ), migrations.RemoveField( model_name='presentation', name='features_cover', ), migrations.DeleteModel( name='FeaturesCover', ), migrations.AddField( model_name='presentation',",
"-*- # Generated by Django 1.11.5 on 2018-02-20 06:45 from __future__ import unicode_literals",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('landing',",
"migrations.DeleteModel( name='FeaturesCover', ), migrations.AddField( model_name='presentation', name='presentation_covers', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='landing.PresentationCover', verbose_name='presentation cover'), ),",
"models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('label_en', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('section', models.CharField(choices=[('DES', 'description'), ('FEA',",
"# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-02-20 06:45",
"dependencies = [ ('landing', '0008_remove_featurescover_active'), ] operations = [ migrations.CreateModel( name='PresentationCover', fields=[ ('id',",
"= [ migrations.CreateModel( name='PresentationCover', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.URLField(verbose_name='image')), ('label',",
"Django 1.11.5 on 2018-02-20 06:45 from __future__ import unicode_literals from django.db import migrations,",
"}, ), migrations.RemoveField( model_name='presentation', name='features_cover', ), migrations.DeleteModel( name='FeaturesCover', ), migrations.AddField( model_name='presentation', name='presentation_covers', field=models.ForeignKey(blank=True,",
"('image', models.URLField(verbose_name='image')), ('label', models.CharField(blank=True, max_length=50, verbose_name='label')), ('label_it', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('label_en', models.CharField(blank=True,",
"('FEA', 'features')], default='DES', max_length=3)), ('default', models.BooleanField(default=False)), ], options={ 'verbose_name': 'Presentation Cover', 'verbose_name_plural': 'Presentation",
"class Migration(migrations.Migration): dependencies = [ ('landing', '0008_remove_featurescover_active'), ] operations = [ migrations.CreateModel( name='PresentationCover',",
"= [ ('landing', '0008_remove_featurescover_active'), ] operations = [ migrations.CreateModel( name='PresentationCover', fields=[ ('id', models.AutoField(auto_created=True,",
"from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('landing', '0008_remove_featurescover_active'), ]",
"null=True, verbose_name='label')), ('section', models.CharField(choices=[('DES', 'description'), ('FEA', 'features')], default='DES', max_length=3)), ('default', models.BooleanField(default=False)), ], options={",
"], options={ 'verbose_name': 'Presentation Cover', 'verbose_name_plural': 'Presentation Covers', }, ), migrations.RemoveField( model_name='presentation', name='features_cover',",
"'Presentation Cover', 'verbose_name_plural': 'Presentation Covers', }, ), migrations.RemoveField( model_name='presentation', name='features_cover', ), migrations.DeleteModel( name='FeaturesCover',",
"verbose_name='label')), ('label_it', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('label_en', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('section', models.CharField(choices=[('DES',",
"('landing', '0008_remove_featurescover_active'), ] operations = [ migrations.CreateModel( name='PresentationCover', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"by Django 1.11.5 on 2018-02-20 06:45 from __future__ import unicode_literals from django.db import",
"serialize=False, verbose_name='ID')), ('image', models.URLField(verbose_name='image')), ('label', models.CharField(blank=True, max_length=50, verbose_name='label')), ('label_it', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')),",
"unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [",
"Migration(migrations.Migration): dependencies = [ ('landing', '0008_remove_featurescover_active'), ] operations = [ migrations.CreateModel( name='PresentationCover', fields=[",
"Cover', 'verbose_name_plural': 'Presentation Covers', }, ), migrations.RemoveField( model_name='presentation', name='features_cover', ), migrations.DeleteModel( name='FeaturesCover', ),",
"name='features_cover', ), migrations.DeleteModel( name='FeaturesCover', ), migrations.AddField( model_name='presentation', name='presentation_covers', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='landing.PresentationCover', verbose_name='presentation",
"models.BooleanField(default=False)), ], options={ 'verbose_name': 'Presentation Cover', 'verbose_name_plural': 'Presentation Covers', }, ), migrations.RemoveField( model_name='presentation',",
"'description'), ('FEA', 'features')], default='DES', max_length=3)), ('default', models.BooleanField(default=False)), ], options={ 'verbose_name': 'Presentation Cover', 'verbose_name_plural':",
"verbose_name='label')), ('label_en', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('section', models.CharField(choices=[('DES', 'description'), ('FEA', 'features')], default='DES', max_length=3)),",
"models.CharField(blank=True, max_length=50, verbose_name='label')), ('label_it', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('label_en', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')),",
"1.11.5 on 2018-02-20 06:45 from __future__ import unicode_literals from django.db import migrations, models",
"), migrations.DeleteModel( name='FeaturesCover', ), migrations.AddField( model_name='presentation', name='presentation_covers', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='landing.PresentationCover', verbose_name='presentation cover'),",
"migrations.RemoveField( model_name='presentation', name='features_cover', ), migrations.DeleteModel( name='FeaturesCover', ), migrations.AddField( model_name='presentation', name='presentation_covers', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,",
"max_length=50, null=True, verbose_name='label')), ('label_en', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('section', models.CharField(choices=[('DES', 'description'), ('FEA', 'features')],",
"models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('landing', '0008_remove_featurescover_active'), ] operations =",
"('label_it', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('label_en', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('section', models.CharField(choices=[('DES', 'description'),",
"'features')], default='DES', max_length=3)), ('default', models.BooleanField(default=False)), ], options={ 'verbose_name': 'Presentation Cover', 'verbose_name_plural': 'Presentation Covers',",
"('default', models.BooleanField(default=False)), ], options={ 'verbose_name': 'Presentation Cover', 'verbose_name_plural': 'Presentation Covers', }, ), migrations.RemoveField(",
"] operations = [ migrations.CreateModel( name='PresentationCover', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image',",
"import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('landing', '0008_remove_featurescover_active'), ] operations = [",
"-*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-02-20 06:45 from",
"model_name='presentation', name='features_cover', ), migrations.DeleteModel( name='FeaturesCover', ), migrations.AddField( model_name='presentation', name='presentation_covers', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='landing.PresentationCover',",
"django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('landing', '0008_remove_featurescover_active'), ] operations = [ migrations.CreateModel(",
"options={ 'verbose_name': 'Presentation Cover', 'verbose_name_plural': 'Presentation Covers', }, ), migrations.RemoveField( model_name='presentation', name='features_cover', ),",
"('label_en', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('section', models.CharField(choices=[('DES', 'description'), ('FEA', 'features')], default='DES', max_length=3)), ('default',",
"primary_key=True, serialize=False, verbose_name='ID')), ('image', models.URLField(verbose_name='image')), ('label', models.CharField(blank=True, max_length=50, verbose_name='label')), ('label_it', models.CharField(blank=True, max_length=50, null=True,",
"2018-02-20 06:45 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion",
"operations = [ migrations.CreateModel( name='PresentationCover', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.URLField(verbose_name='image')),",
"'0008_remove_featurescover_active'), ] operations = [ migrations.CreateModel( name='PresentationCover', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"[ migrations.CreateModel( name='PresentationCover', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.URLField(verbose_name='image')), ('label', models.CharField(blank=True,",
"[ ('landing', '0008_remove_featurescover_active'), ] operations = [ migrations.CreateModel( name='PresentationCover', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"utf-8 -*- # Generated by Django 1.11.5 on 2018-02-20 06:45 from __future__ import",
"06:45 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.URLField(verbose_name='image')), ('label', models.CharField(blank=True, max_length=50, verbose_name='label')), ('label_it', models.CharField(blank=True,",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('landing', '0008_remove_featurescover_active'),",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.URLField(verbose_name='image')), ('label', models.CharField(blank=True, max_length=50, verbose_name='label')), ('label_it', models.CharField(blank=True, max_length=50,",
"models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('section', models.CharField(choices=[('DES', 'description'), ('FEA', 'features')], default='DES', max_length=3)), ('default', models.BooleanField(default=False)),",
"coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-02-20 06:45 from __future__",
"verbose_name='label')), ('section', models.CharField(choices=[('DES', 'description'), ('FEA', 'features')], default='DES', max_length=3)), ('default', models.BooleanField(default=False)), ], options={ 'verbose_name':",
"Covers', }, ), migrations.RemoveField( model_name='presentation', name='features_cover', ), migrations.DeleteModel( name='FeaturesCover', ), migrations.AddField( model_name='presentation', name='presentation_covers',",
"models.URLField(verbose_name='image')), ('label', models.CharField(blank=True, max_length=50, verbose_name='label')), ('label_it', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('label_en', models.CharField(blank=True, max_length=50,",
"max_length=3)), ('default', models.BooleanField(default=False)), ], options={ 'verbose_name': 'Presentation Cover', 'verbose_name_plural': 'Presentation Covers', }, ),",
"'verbose_name': 'Presentation Cover', 'verbose_name_plural': 'Presentation Covers', }, ), migrations.RemoveField( model_name='presentation', name='features_cover', ), migrations.DeleteModel(",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.URLField(verbose_name='image')), ('label', models.CharField(blank=True, max_length=50, verbose_name='label')), ('label_it',",
"verbose_name='ID')), ('image', models.URLField(verbose_name='image')), ('label', models.CharField(blank=True, max_length=50, verbose_name='label')), ('label_it', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('label_en',",
"import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies =",
"max_length=50, null=True, verbose_name='label')), ('section', models.CharField(choices=[('DES', 'description'), ('FEA', 'features')], default='DES', max_length=3)), ('default', models.BooleanField(default=False)), ],",
"null=True, verbose_name='label')), ('label_en', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('section', models.CharField(choices=[('DES', 'description'), ('FEA', 'features')], default='DES',",
"), migrations.RemoveField( model_name='presentation', name='features_cover', ), migrations.DeleteModel( name='FeaturesCover', ), migrations.AddField( model_name='presentation', name='presentation_covers', field=models.ForeignKey(blank=True, null=True,",
"('label', models.CharField(blank=True, max_length=50, verbose_name='label')), ('label_it', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('label_en', models.CharField(blank=True, max_length=50, null=True,",
"Generated by Django 1.11.5 on 2018-02-20 06:45 from __future__ import unicode_literals from django.db",
"('section', models.CharField(choices=[('DES', 'description'), ('FEA', 'features')], default='DES', max_length=3)), ('default', models.BooleanField(default=False)), ], options={ 'verbose_name': 'Presentation",
"default='DES', max_length=3)), ('default', models.BooleanField(default=False)), ], options={ 'verbose_name': 'Presentation Cover', 'verbose_name_plural': 'Presentation Covers', },",
"# Generated by Django 1.11.5 on 2018-02-20 06:45 from __future__ import unicode_literals from",
"migrations.CreateModel( name='PresentationCover', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.URLField(verbose_name='image')), ('label', models.CharField(blank=True, max_length=50,",
"max_length=50, verbose_name='label')), ('label_it', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('label_en', models.CharField(blank=True, max_length=50, null=True, verbose_name='label')), ('section',"
] |
[
"np.zeros((dattorro.dsp.num_in, args.fs), dtype=dattorro.dsp.dtype) audio[:, 0] = 1 out = dattorro.compute(audio) print(audio) print(out) spec",
"= 10**(-0.5) # -10 dB cur_G = dattorro.dsp.ui.p_Gain.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig =",
"at -60 dB because the minimum is at an extremely low -160 dB",
"def_Q.default dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10 dB cur_Q = dattorro.dsp.ui.p_Q.zone cur_G = dattorro.dsp.ui.p_Gain.zone",
"1, title=\"Frequency response (Q={}, F={} Hz)\".format(cur_Q, cur_F), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in",
"varying Q ####################################################### Q = np.linspace(def_Q.min, def_Q.max, 10) dattorro.dsp.ui.p_Center_Freq = 1e2 dattorro.dsp.ui.p_Gain =",
"an extremely low -160 dB G = np.logspace(-3, np.log10(def_Gain.max), 10) dattorro.dsp.ui.p_Q = 2",
"plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response (Q={}, F={} Hz)\".format(cur_Q, cur_F),",
"dest=\"faustfloat\", default=\"float\", help=\"The value of FAUSTFLOAT.\") parser.add_argument('-p', '--path', dest=\"faust_path\", default=\"\", help=\"The path to",
"# initialise the FAUST object and get the default parameters ####################################################### wrapper.FAUST_PATH =",
"the frequency response with varying center frequency ########################################################### F = np.logspace(np.log10(def_Freq.min), np.log10(def_Freq.max), 10)",
") for g in G: dattorro.dsp.ui.p_Gain = g out = dattorro.compute(audio) spec =",
"dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"Q={}\".format(q)) p.legend(loc=\"best\") ####################################################### # plot the frequency",
"print(audio) print(out) spec = np.fft.fft(out)[:, :args.fs/2] fig = plt.figure() p = fig.add_subplot( 1,",
"in dB FS\", xscale=\"log\" ) for q in Q: dattorro.dsp.ui.p_Q = q out",
"fig = plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response with the",
"import argparse import numpy as np import matplotlib.pyplot as plt from FAUSTPy import",
"p.legend(loc=\"best\") ########################################################### # plot the frequency response with varying center frequency ########################################################### F",
"f in F: dattorro.dsp.ui.p_Center_Freq = f out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2]",
"parser = argparse.ArgumentParser() parser.add_argument('-f', '--faustfloat', dest=\"faustfloat\", default=\"float\", help=\"The value of FAUSTFLOAT.\") parser.add_argument('-p', '--path',",
"parser.add_argument('-p', '--path', dest=\"faust_path\", default=\"\", help=\"The path to the FAUST compiler.\") parser.add_argument('-c', '--cflags', dest=\"cflags\",",
"\" \"(G={:.0f} dB FS, F={} Hz)\".format(20*np.log10(cur_G+1e-8), cur_F), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in",
"with varying center frequency ########################################################### F = np.logspace(np.log10(def_Freq.min), np.log10(def_Freq.max), 10) dattorro.dsp.ui.p_Q = def_Q.default",
"xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for f in",
"= fig.add_subplot( 1, 1, 1, title=\"Frequency response (Q={}, F={} Hz)\".format(cur_Q, cur_F), xlabel=\"Frequency in",
"center frequency ########################################################### F = np.logspace(np.log10(def_Freq.min), np.log10(def_Freq.max), 10) dattorro.dsp.ui.p_Q = def_Q.default dattorro.dsp.ui.p_Gain =",
"= np.fft.fft(out)[:, :args.fs/2] fig = plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency",
"# set up command line arguments ####################################################### parser = argparse.ArgumentParser() parser.add_argument('-f', '--faustfloat', dest=\"faustfloat\",",
"Q = np.linspace(def_Q.min, def_Q.max, 10) dattorro.dsp.ui.p_Center_Freq = 1e2 dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10",
"= argparse.ArgumentParser() parser.add_argument('-f', '--faustfloat', dest=\"faustfloat\", default=\"float\", help=\"The value of FAUSTFLOAT.\") parser.add_argument('-p', '--path', dest=\"faust_path\",",
"response with varying gain ####################################################### # start at -60 dB because the minimum",
"-10 dB cur_Q = dattorro.dsp.ui.p_Q.zone cur_G = dattorro.dsp.ui.p_Gain.zone fig = plt.figure() p =",
"= f out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"F={:.2f} Hz\".format(f)) p.legend(loc=\"best\")",
"10**(-0.5) # -10 dB cur_Q = dattorro.dsp.ui.p_Q.zone cur_G = dattorro.dsp.ui.p_Gain.zone fig = plt.figure()",
"q out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"Q={}\".format(q)) p.legend(loc=\"best\") ####################################################### #",
"Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for q in Q: dattorro.dsp.ui.p_Q",
"dattorro.dsp.ui.p_Center_Freq ####################################################### # plot the frequency response with the default settings ####################################################### audio",
"20*np.log10(cur_G+1e-8)), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for f",
"in dB FS\", xscale=\"log\" ) p.plot(20*np.log10(np.absolute(spec.T)+1e-8)) p.legend((\"Left channel\", \"Right channel\"), loc=\"best\") ####################################################### #",
"dest=\"faust_path\", default=\"\", help=\"The path to the FAUST compiler.\") parser.add_argument('-c', '--cflags', dest=\"cflags\", default=[], type=str.split,",
"= fig.add_subplot( 1, 1, 1, title=\"Frequency response \" \"(Q={}, G={:.0f} dB FS)\".format(cur_Q, 20*np.log10(cur_G+1e-8)),",
"(log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) p.plot(20*np.log10(np.absolute(spec.T)+1e-8)) p.legend((\"Left channel\", \"Right channel\"), loc=\"best\")",
"np.log10(def_Freq.max), 10) dattorro.dsp.ui.p_Q = def_Q.default dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10 dB cur_Q =",
"= 1 out = dattorro.compute(audio) print(audio) print(out) spec = np.fft.fft(out)[:, :args.fs/2] fig =",
"(Q={}, F={} Hz)\".format(cur_Q, cur_F), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\"",
"xscale=\"log\" ) p.plot(20*np.log10(np.absolute(spec.T)+1e-8)) p.legend((\"Left channel\", \"Right channel\"), loc=\"best\") ####################################################### # plot the frequency",
"1, 1, title=\"Frequency response \" \"(Q={}, G={:.0f} dB FS)\".format(cur_Q, 20*np.log10(cur_G+1e-8)), xlabel=\"Frequency in Hz",
"title=\"Frequency response (Q={}, F={} Hz)\".format(cur_Q, cur_F), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB",
"xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) p.plot(20*np.log10(np.absolute(spec.T)+1e-8)) p.legend((\"Left channel\",",
"10**(-0.5) # -10 dB cur_G = dattorro.dsp.ui.p_Gain.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure()",
"dB FS, F={} Hz)\".format(20*np.log10(cur_G+1e-8), cur_F), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\",",
"settings ####################################################### audio = np.zeros((dattorro.dsp.num_in, args.fs), dtype=dattorro.dsp.dtype) audio[:, 0] = 1 out =",
"FS)\".format( def_Q.zone, def_Freq.zone, 20*np.log10(def_Gain.zone+1e-8) ), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\",",
"the frequency response with varying gain ####################################################### # start at -60 dB because",
"####################################################### # plot the frequency response with varying gain ####################################################### # start at",
"extremely low -160 dB G = np.logspace(-3, np.log10(def_Gain.max), 10) dattorro.dsp.ui.p_Q = 2 cur_Q",
"1, title=\"Frequency response with the default settings\\n\" \"(Q={}, F={:.2f} Hz, G={:.0f} dB FS)\".format(",
"dattorro.dsp.ui.p_Q def_Gain = dattorro.dsp.ui.p_Gain def_Freq = dattorro.dsp.ui.p_Center_Freq ####################################################### # plot the frequency response",
"default=48000, type=int, help=\"The sampling frequency\") args = parser.parse_args() ####################################################### # initialise the FAUST",
"def_Q.zone, def_Freq.zone, 20*np.log10(def_Gain.zone+1e-8) ), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\"",
"= plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response \" \"(Q={}, G={:.0f}",
"frequency response with varying Q ####################################################### Q = np.linspace(def_Q.min, def_Q.max, 10) dattorro.dsp.ui.p_Center_Freq =",
"# -10 dB cur_Q = dattorro.dsp.ui.p_Q.zone cur_G = dattorro.dsp.ui.p_Gain.zone fig = plt.figure() p",
"plot the frequency response with varying gain ####################################################### # start at -60 dB",
"dB cur_Q = dattorro.dsp.ui.p_Q.zone cur_G = dattorro.dsp.ui.p_Gain.zone fig = plt.figure() p = fig.add_subplot(",
"= parser.parse_args() ####################################################### # initialise the FAUST object and get the default parameters",
"of FAUSTFLOAT.\") parser.add_argument('-p', '--path', dest=\"faust_path\", default=\"\", help=\"The path to the FAUST compiler.\") parser.add_argument('-c',",
"dtype=dattorro.dsp.dtype) audio[:, 0] = 1 out = dattorro.compute(audio) print(audio) print(out) spec = np.fft.fft(out)[:,",
"dB FS)\".format( def_Q.zone, def_Freq.zone, 20*np.log10(def_Gain.zone+1e-8) ), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB",
"= g out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"G={:.3g} dB FS\".format(20*np.log10(g+1e-8)))",
"parameters ####################################################### wrapper.FAUST_PATH = args.faust_path dattorro = FAUST(\"dattorro_notch_cut_regalia.dsp\", args.fs, args.faustfloat, extra_compile_args=args.cflags) def_Q =",
"low -160 dB G = np.logspace(-3, np.log10(def_Gain.max), 10) dattorro.dsp.ui.p_Q = 2 cur_Q =",
"2 cur_Q = dattorro.dsp.ui.p_Q.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure() p = fig.add_subplot(",
"dattorro.dsp.ui.p_Gain.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure() p = fig.add_subplot( 1, 1, 1,",
"response with the default settings ####################################################### audio = np.zeros((dattorro.dsp.num_in, args.fs), dtype=dattorro.dsp.dtype) audio[:, 0]",
"F={} Hz)\".format(20*np.log10(cur_G+1e-8), cur_F), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" )",
"\" \"(Q={}, G={:.0f} dB FS)\".format(cur_Q, 20*np.log10(cur_G+1e-8)), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB",
"response with the default settings\\n\" \"(Q={}, F={:.2f} Hz, G={:.0f} dB FS)\".format( def_Q.zone, def_Freq.zone,",
"the default parameters ####################################################### wrapper.FAUST_PATH = args.faust_path dattorro = FAUST(\"dattorro_notch_cut_regalia.dsp\", args.fs, args.faustfloat, extra_compile_args=args.cflags)",
"= def_Q.default dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10 dB cur_Q = dattorro.dsp.ui.p_Q.zone cur_G =",
"ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for f in F: dattorro.dsp.ui.p_Center_Freq = f",
"dest=\"cflags\", default=[], type=str.split, help=\"Extra compiler flags\") parser.add_argument('-s', '--fs', dest=\"fs\", default=48000, type=int, help=\"The sampling",
"= dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"G={:.3g} dB FS\".format(20*np.log10(g+1e-8))) p.legend(loc=\"best\") ########################################################### #",
"'--fs', dest=\"fs\", default=48000, type=int, help=\"The sampling frequency\") args = parser.parse_args() ####################################################### # initialise",
"label=\"Q={}\".format(q)) p.legend(loc=\"best\") ####################################################### # plot the frequency response with varying gain ####################################################### #",
"np import matplotlib.pyplot as plt from FAUSTPy import * ####################################################### # set up",
"xscale=\"log\" ) for g in G: dattorro.dsp.ui.p_Gain = g out = dattorro.compute(audio) spec",
"for f in F: dattorro.dsp.ui.p_Center_Freq = f out = dattorro.compute(audio) spec = np.fft.fft(out)[0,",
"= dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"Q={}\".format(q)) p.legend(loc=\"best\") ####################################################### # plot the",
"= fig.add_subplot( 1, 1, 1, title=\"Frequency response \" \"(G={:.0f} dB FS, F={} Hz)\".format(20*np.log10(cur_G+1e-8),",
"help=\"The path to the FAUST compiler.\") parser.add_argument('-c', '--cflags', dest=\"cflags\", default=[], type=str.split, help=\"Extra compiler",
"np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"G={:.3g} dB FS\".format(20*np.log10(g+1e-8))) p.legend(loc=\"best\") ########################################################### # plot the frequency response",
"0] = 1 out = dattorro.compute(audio) print(audio) print(out) spec = np.fft.fft(out)[:, :args.fs/2] fig",
"default=\"float\", help=\"The value of FAUSTFLOAT.\") parser.add_argument('-p', '--path', dest=\"faust_path\", default=\"\", help=\"The path to the",
"q in Q: dattorro.dsp.ui.p_Q = q out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2]",
"the minimum is at an extremely low -160 dB G = np.logspace(-3, np.log10(def_Gain.max),",
"1, 1, title=\"Frequency response with the default settings\\n\" \"(Q={}, F={:.2f} Hz, G={:.0f} dB",
"out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"F={:.2f} Hz\".format(f)) p.legend(loc=\"best\") ################ #",
"xscale=\"log\" ) for q in Q: dattorro.dsp.ui.p_Q = q out = dattorro.compute(audio) spec",
"cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency",
"= 2 cur_Q = dattorro.dsp.ui.p_Q.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure() p =",
"plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response with the default settings\\n\"",
"varying center frequency ########################################################### F = np.logspace(np.log10(def_Freq.min), np.log10(def_Freq.max), 10) dattorro.dsp.ui.p_Q = def_Q.default dattorro.dsp.ui.p_Gain",
"1, title=\"Frequency response \" \"(Q={}, G={:.0f} dB FS)\".format(cur_Q, 20*np.log10(cur_G+1e-8)), xlabel=\"Frequency in Hz (log)\",",
"1, title=\"Frequency response \" \"(G={:.0f} dB FS, F={} Hz)\".format(20*np.log10(cur_G+1e-8), cur_F), xlabel=\"Frequency in Hz",
"spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"Q={}\".format(q)) p.legend(loc=\"best\") ####################################################### # plot the frequency response",
"= args.faust_path dattorro = FAUST(\"dattorro_notch_cut_regalia.dsp\", args.fs, args.faustfloat, extra_compile_args=args.cflags) def_Q = dattorro.dsp.ui.p_Q def_Gain =",
"in dB FS\", xscale=\"log\" ) for f in F: dattorro.dsp.ui.p_Center_Freq = f out",
"dattorro = FAUST(\"dattorro_notch_cut_regalia.dsp\", args.fs, args.faustfloat, extra_compile_args=args.cflags) def_Q = dattorro.dsp.ui.p_Q def_Gain = dattorro.dsp.ui.p_Gain def_Freq",
"np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"F={:.2f} Hz\".format(f)) p.legend(loc=\"best\") ################ # show the plots ################ plt.show()",
"p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"Q={}\".format(q)) p.legend(loc=\"best\") ####################################################### # plot the frequency response with varying gain #######################################################",
"p = fig.add_subplot( 1, 1, 1, title=\"Frequency response \" \"(Q={}, G={:.0f} dB FS)\".format(cur_Q,",
"G={:.0f} dB FS)\".format(cur_Q, 20*np.log10(cur_G+1e-8)), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\"",
"= fig.add_subplot( 1, 1, 1, title=\"Frequency response with the default settings\\n\" \"(Q={}, F={:.2f}",
"FS)\".format(cur_Q, 20*np.log10(cur_G+1e-8)), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for",
"plt from FAUSTPy import * ####################################################### # set up command line arguments #######################################################",
"####################################################### wrapper.FAUST_PATH = args.faust_path dattorro = FAUST(\"dattorro_notch_cut_regalia.dsp\", args.fs, args.faustfloat, extra_compile_args=args.cflags) def_Q = dattorro.dsp.ui.p_Q",
"flags\") parser.add_argument('-s', '--fs', dest=\"fs\", default=48000, type=int, help=\"The sampling frequency\") args = parser.parse_args() #######################################################",
"the default settings ####################################################### audio = np.zeros((dattorro.dsp.num_in, args.fs), dtype=dattorro.dsp.dtype) audio[:, 0] = 1",
"Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for f in F: dattorro.dsp.ui.p_Center_Freq",
"(log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for f in F: dattorro.dsp.ui.p_Center_Freq =",
"FS\", xscale=\"log\" ) for f in F: dattorro.dsp.ui.p_Center_Freq = f out = dattorro.compute(audio)",
"in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for q in Q:",
"frequency response with the default settings ####################################################### audio = np.zeros((dattorro.dsp.num_in, args.fs), dtype=dattorro.dsp.dtype) audio[:,",
"ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for q in Q: dattorro.dsp.ui.p_Q = q",
"gain ####################################################### # start at -60 dB because the minimum is at an",
"########################################################### # plot the frequency response with varying center frequency ########################################################### F =",
":args.fs/2] fig = plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response with",
"= np.logspace(-3, np.log10(def_Gain.max), 10) dattorro.dsp.ui.p_Q = 2 cur_Q = dattorro.dsp.ui.p_Q.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone",
"value of FAUSTFLOAT.\") parser.add_argument('-p', '--path', dest=\"faust_path\", default=\"\", help=\"The path to the FAUST compiler.\")",
"import numpy as np import matplotlib.pyplot as plt from FAUSTPy import * #######################################################",
"= dattorro.dsp.ui.p_Q.zone cur_G = dattorro.dsp.ui.p_Gain.zone fig = plt.figure() p = fig.add_subplot( 1, 1,",
"fig.add_subplot( 1, 1, 1, title=\"Frequency response (Q={}, F={} Hz)\".format(cur_Q, cur_F), xlabel=\"Frequency in Hz",
"def_Freq = dattorro.dsp.ui.p_Center_Freq ####################################################### # plot the frequency response with the default settings",
"= np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"F={:.2f} Hz\".format(f)) p.legend(loc=\"best\") ################ # show the plots ################",
"FS\".format(20*np.log10(g+1e-8))) p.legend(loc=\"best\") ########################################################### # plot the frequency response with varying center frequency ###########################################################",
"is at an extremely low -160 dB G = np.logspace(-3, np.log10(def_Gain.max), 10) dattorro.dsp.ui.p_Q",
"FS, F={} Hz)\".format(20*np.log10(cur_G+1e-8), cur_F), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\"",
") p.plot(20*np.log10(np.absolute(spec.T)+1e-8)) p.legend((\"Left channel\", \"Right channel\"), loc=\"best\") ####################################################### # plot the frequency response",
"cur_F), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for q",
"\"Right channel\"), loc=\"best\") ####################################################### # plot the frequency response with varying Q #######################################################",
"20*np.log10(def_Gain.zone+1e-8) ), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) p.plot(20*np.log10(np.absolute(spec.T)+1e-8))",
"# plot the frequency response with varying center frequency ########################################################### F = np.logspace(np.log10(def_Freq.min),",
"xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for g in",
"spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"F={:.2f} Hz\".format(f)) p.legend(loc=\"best\") ################ # show the plots",
"for q in Q: dattorro.dsp.ui.p_Q = q out = dattorro.compute(audio) spec = np.fft.fft(out)[0,",
"dattorro.dsp.ui.p_Q = def_Q.default dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10 dB cur_Q = dattorro.dsp.ui.p_Q.zone cur_G",
"channel\", \"Right channel\"), loc=\"best\") ####################################################### # plot the frequency response with varying Q",
"type=str.split, help=\"Extra compiler flags\") parser.add_argument('-s', '--fs', dest=\"fs\", default=48000, type=int, help=\"The sampling frequency\") args",
"dB FS\".format(20*np.log10(g+1e-8))) p.legend(loc=\"best\") ########################################################### # plot the frequency response with varying center frequency",
"path to the FAUST compiler.\") parser.add_argument('-c', '--cflags', dest=\"cflags\", default=[], type=str.split, help=\"Extra compiler flags\")",
"command line arguments ####################################################### parser = argparse.ArgumentParser() parser.add_argument('-f', '--faustfloat', dest=\"faustfloat\", default=\"float\", help=\"The value",
"(log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for g in G: dattorro.dsp.ui.p_Gain =",
"1, 1, 1, title=\"Frequency response with the default settings\\n\" \"(Q={}, F={:.2f} Hz, G={:.0f}",
"args.faust_path dattorro = FAUST(\"dattorro_notch_cut_regalia.dsp\", args.fs, args.faustfloat, extra_compile_args=args.cflags) def_Q = dattorro.dsp.ui.p_Q def_Gain = dattorro.dsp.ui.p_Gain",
"args.fs, args.faustfloat, extra_compile_args=args.cflags) def_Q = dattorro.dsp.ui.p_Q def_Gain = dattorro.dsp.ui.p_Gain def_Freq = dattorro.dsp.ui.p_Center_Freq #######################################################",
"audio = np.zeros((dattorro.dsp.num_in, args.fs), dtype=dattorro.dsp.dtype) audio[:, 0] = 1 out = dattorro.compute(audio) print(audio)",
"g out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"G={:.3g} dB FS\".format(20*np.log10(g+1e-8))) p.legend(loc=\"best\")",
"up command line arguments ####################################################### parser = argparse.ArgumentParser() parser.add_argument('-f', '--faustfloat', dest=\"faustfloat\", default=\"float\", help=\"The",
"dattorro.dsp.ui.p_Q.zone cur_G = dattorro.dsp.ui.p_Gain.zone fig = plt.figure() p = fig.add_subplot( 1, 1, 1,",
"Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for g in G: dattorro.dsp.ui.p_Gain",
"dattorro.dsp.ui.p_Q = q out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"Q={}\".format(q)) p.legend(loc=\"best\")",
"np.fft.fft(out)[:, :args.fs/2] fig = plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response",
"g in G: dattorro.dsp.ui.p_Gain = g out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2]",
"cur_Q = dattorro.dsp.ui.p_Q.zone cur_G = dattorro.dsp.ui.p_Gain.zone fig = plt.figure() p = fig.add_subplot( 1,",
"dB cur_G = dattorro.dsp.ui.p_Gain.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure() p = fig.add_subplot(",
"extra_compile_args=args.cflags) def_Q = dattorro.dsp.ui.p_Q def_Gain = dattorro.dsp.ui.p_Gain def_Freq = dattorro.dsp.ui.p_Center_Freq ####################################################### # plot",
"parser.add_argument('-s', '--fs', dest=\"fs\", default=48000, type=int, help=\"The sampling frequency\") args = parser.parse_args() ####################################################### #",
"1, 1, title=\"Frequency response \" \"(G={:.0f} dB FS, F={} Hz)\".format(20*np.log10(cur_G+1e-8), cur_F), xlabel=\"Frequency in",
"G: dattorro.dsp.ui.p_Gain = g out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"G={:.3g}",
"plot the frequency response with the default settings ####################################################### audio = np.zeros((dattorro.dsp.num_in, args.fs),",
"as plt from FAUSTPy import * ####################################################### # set up command line arguments",
"FAUST compiler.\") parser.add_argument('-c', '--cflags', dest=\"cflags\", default=[], type=str.split, help=\"Extra compiler flags\") parser.add_argument('-s', '--fs', dest=\"fs\",",
"cur_G = dattorro.dsp.ui.p_Gain.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure() p = fig.add_subplot( 1,",
"= plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response with the default",
"with the default settings ####################################################### audio = np.zeros((dattorro.dsp.num_in, args.fs), dtype=dattorro.dsp.dtype) audio[:, 0] =",
"np.linspace(def_Q.min, def_Q.max, 10) dattorro.dsp.ui.p_Center_Freq = 1e2 dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10 dB cur_G",
"####################################################### # plot the frequency response with varying Q ####################################################### Q = np.linspace(def_Q.min,",
"in dB FS\", xscale=\"log\" ) for g in G: dattorro.dsp.ui.p_Gain = g out",
"= 10**(-0.5) # -10 dB cur_Q = dattorro.dsp.ui.p_Q.zone cur_G = dattorro.dsp.ui.p_Gain.zone fig =",
"default=\"\", help=\"The path to the FAUST compiler.\") parser.add_argument('-c', '--cflags', dest=\"cflags\", default=[], type=str.split, help=\"Extra",
"fig = plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response (Q={}, F={}",
"because the minimum is at an extremely low -160 dB G = np.logspace(-3,",
"* ####################################################### # set up command line arguments ####################################################### parser = argparse.ArgumentParser() parser.add_argument('-f',",
"in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for g in G:",
"dB FS)\".format(cur_Q, 20*np.log10(cur_G+1e-8)), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" )",
"np.logspace(np.log10(def_Freq.min), np.log10(def_Freq.max), 10) dattorro.dsp.ui.p_Q = def_Q.default dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10 dB cur_Q",
":args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"Q={}\".format(q)) p.legend(loc=\"best\") ####################################################### # plot the frequency response with varying gain",
"arguments ####################################################### parser = argparse.ArgumentParser() parser.add_argument('-f', '--faustfloat', dest=\"faustfloat\", default=\"float\", help=\"The value of FAUSTFLOAT.\")",
"\"(Q={}, G={:.0f} dB FS)\".format(cur_Q, 20*np.log10(cur_G+1e-8)), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\",",
"= dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response",
"F={} Hz)\".format(cur_Q, cur_F), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" )",
"), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) p.plot(20*np.log10(np.absolute(spec.T)+1e-8)) p.legend((\"Left",
"np.logspace(-3, np.log10(def_Gain.max), 10) dattorro.dsp.ui.p_Q = 2 cur_Q = dattorro.dsp.ui.p_Q.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig",
"10) dattorro.dsp.ui.p_Q = def_Q.default dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10 dB cur_Q = dattorro.dsp.ui.p_Q.zone",
"with varying Q ####################################################### Q = np.linspace(def_Q.min, def_Q.max, 10) dattorro.dsp.ui.p_Center_Freq = 1e2 dattorro.dsp.ui.p_Gain",
"with varying gain ####################################################### # start at -60 dB because the minimum is",
"dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10 dB cur_Q = dattorro.dsp.ui.p_Q.zone cur_G = dattorro.dsp.ui.p_Gain.zone fig",
"title=\"Frequency response \" \"(G={:.0f} dB FS, F={} Hz)\".format(20*np.log10(cur_G+1e-8), cur_F), xlabel=\"Frequency in Hz (log)\",",
"dattorro.dsp.ui.p_Center_Freq = f out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"F={:.2f} Hz\".format(f))",
"print(out) spec = np.fft.fft(out)[:, :args.fs/2] fig = plt.figure() p = fig.add_subplot( 1, 1,",
"= np.zeros((dattorro.dsp.num_in, args.fs), dtype=dattorro.dsp.dtype) audio[:, 0] = 1 out = dattorro.compute(audio) print(audio) print(out)",
"####################################################### # set up command line arguments ####################################################### parser = argparse.ArgumentParser() parser.add_argument('-f', '--faustfloat',",
"response \" \"(G={:.0f} dB FS, F={} Hz)\".format(20*np.log10(cur_G+1e-8), cur_F), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude",
"in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for f in F:",
"####################################################### # plot the frequency response with the default settings ####################################################### audio =",
"np.log10(def_Gain.max), 10) dattorro.dsp.ui.p_Q = 2 cur_Q = dattorro.dsp.ui.p_Q.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig =",
"the FAUST compiler.\") parser.add_argument('-c', '--cflags', dest=\"cflags\", default=[], type=str.split, help=\"Extra compiler flags\") parser.add_argument('-s', '--fs',",
"dattorro.compute(audio) print(audio) print(out) spec = np.fft.fft(out)[:, :args.fs/2] fig = plt.figure() p = fig.add_subplot(",
"ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) p.plot(20*np.log10(np.absolute(spec.T)+1e-8)) p.legend((\"Left channel\", \"Right channel\"), loc=\"best\") #######################################################",
"dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response \"",
"Q: dattorro.dsp.ui.p_Q = q out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"Q={}\".format(q))",
"-10 dB cur_G = dattorro.dsp.ui.p_Gain.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure() p =",
"fig.add_subplot( 1, 1, 1, title=\"Frequency response \" \"(Q={}, G={:.0f} dB FS)\".format(cur_Q, 20*np.log10(cur_G+1e-8)), xlabel=\"Frequency",
"FAUSTPy import * ####################################################### # set up command line arguments ####################################################### parser =",
"help=\"The sampling frequency\") args = parser.parse_args() ####################################################### # initialise the FAUST object and",
"get the default parameters ####################################################### wrapper.FAUST_PATH = args.faust_path dattorro = FAUST(\"dattorro_notch_cut_regalia.dsp\", args.fs, args.faustfloat,",
"= FAUST(\"dattorro_notch_cut_regalia.dsp\", args.fs, args.faustfloat, extra_compile_args=args.cflags) def_Q = dattorro.dsp.ui.p_Q def_Gain = dattorro.dsp.ui.p_Gain def_Freq =",
"= 1e2 dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10 dB cur_G = dattorro.dsp.ui.p_Gain.zone cur_F =",
"for g in G: dattorro.dsp.ui.p_Gain = g out = dattorro.compute(audio) spec = np.fft.fft(out)[0,",
"line arguments ####################################################### parser = argparse.ArgumentParser() parser.add_argument('-f', '--faustfloat', dest=\"faustfloat\", default=\"float\", help=\"The value of",
"= plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response \" \"(G={:.0f} dB",
"compiler flags\") parser.add_argument('-s', '--fs', dest=\"fs\", default=48000, type=int, help=\"The sampling frequency\") args = parser.parse_args()",
"in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) p.plot(20*np.log10(np.absolute(spec.T)+1e-8)) p.legend((\"Left channel\", \"Right",
"FAUSTFLOAT.\") parser.add_argument('-p', '--path', dest=\"faust_path\", default=\"\", help=\"The path to the FAUST compiler.\") parser.add_argument('-c', '--cflags',",
"Q ####################################################### Q = np.linspace(def_Q.min, def_Q.max, 10) dattorro.dsp.ui.p_Center_Freq = 1e2 dattorro.dsp.ui.p_Gain = 10**(-0.5)",
"# -10 dB cur_G = dattorro.dsp.ui.p_Gain.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure() p",
"p = fig.add_subplot( 1, 1, 1, title=\"Frequency response \" \"(G={:.0f} dB FS, F={}",
"ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for g in G: dattorro.dsp.ui.p_Gain = g",
"default settings ####################################################### audio = np.zeros((dattorro.dsp.num_in, args.fs), dtype=dattorro.dsp.dtype) audio[:, 0] = 1 out",
"minimum is at an extremely low -160 dB G = np.logspace(-3, np.log10(def_Gain.max), 10)",
"type=int, help=\"The sampling frequency\") args = parser.parse_args() ####################################################### # initialise the FAUST object",
"1e2 dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10 dB cur_G = dattorro.dsp.ui.p_Gain.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone",
"frequency\") args = parser.parse_args() ####################################################### # initialise the FAUST object and get the",
"FS\", xscale=\"log\" ) for g in G: dattorro.dsp.ui.p_Gain = g out = dattorro.compute(audio)",
"compiler.\") parser.add_argument('-c', '--cflags', dest=\"cflags\", default=[], type=str.split, help=\"Extra compiler flags\") parser.add_argument('-s', '--fs', dest=\"fs\", default=48000,",
"dB FS\", xscale=\"log\" ) for f in F: dattorro.dsp.ui.p_Center_Freq = f out =",
"dB FS\", xscale=\"log\" ) for q in Q: dattorro.dsp.ui.p_Q = q out =",
"parser.add_argument('-c', '--cflags', dest=\"cflags\", default=[], type=str.split, help=\"Extra compiler flags\") parser.add_argument('-s', '--fs', dest=\"fs\", default=48000, type=int,",
"fig.add_subplot( 1, 1, 1, title=\"Frequency response \" \"(G={:.0f} dB FS, F={} Hz)\".format(20*np.log10(cur_G+1e-8), cur_F),",
"\"(Q={}, F={:.2f} Hz, G={:.0f} dB FS)\".format( def_Q.zone, def_Freq.zone, 20*np.log10(def_Gain.zone+1e-8) ), xlabel=\"Frequency in Hz",
"Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) p.plot(20*np.log10(np.absolute(spec.T)+1e-8)) p.legend((\"Left channel\", \"Right channel\"),",
"= dattorro.dsp.ui.p_Gain def_Freq = dattorro.dsp.ui.p_Center_Freq ####################################################### # plot the frequency response with the",
"1 out = dattorro.compute(audio) print(audio) print(out) spec = np.fft.fft(out)[:, :args.fs/2] fig = plt.figure()",
"args.faustfloat, extra_compile_args=args.cflags) def_Q = dattorro.dsp.ui.p_Q def_Gain = dattorro.dsp.ui.p_Gain def_Freq = dattorro.dsp.ui.p_Center_Freq ####################################################### #",
"def_Q = dattorro.dsp.ui.p_Q def_Gain = dattorro.dsp.ui.p_Gain def_Freq = dattorro.dsp.ui.p_Center_Freq ####################################################### # plot the",
"1, 1, 1, title=\"Frequency response \" \"(G={:.0f} dB FS, F={} Hz)\".format(20*np.log10(cur_G+1e-8), cur_F), xlabel=\"Frequency",
"help=\"Extra compiler flags\") parser.add_argument('-s', '--fs', dest=\"fs\", default=48000, type=int, help=\"The sampling frequency\") args =",
"wrapper.FAUST_PATH = args.faust_path dattorro = FAUST(\"dattorro_notch_cut_regalia.dsp\", args.fs, args.faustfloat, extra_compile_args=args.cflags) def_Q = dattorro.dsp.ui.p_Q def_Gain",
"p.legend(loc=\"best\") ####################################################### # plot the frequency response with varying gain ####################################################### # start",
"dB G = np.logspace(-3, np.log10(def_Gain.max), 10) dattorro.dsp.ui.p_Q = 2 cur_Q = dattorro.dsp.ui.p_Q.zone cur_F",
"-60 dB because the minimum is at an extremely low -160 dB G",
"= plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response (Q={}, F={} Hz)\".format(cur_Q,",
"fig.add_subplot( 1, 1, 1, title=\"Frequency response with the default settings\\n\" \"(Q={}, F={:.2f} Hz,",
"audio[:, 0] = 1 out = dattorro.compute(audio) print(audio) print(out) spec = np.fft.fft(out)[:, :args.fs/2]",
"out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"G={:.3g} dB FS\".format(20*np.log10(g+1e-8))) p.legend(loc=\"best\") ###########################################################",
"Hz)\".format(20*np.log10(cur_G+1e-8), cur_F), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for",
"G = np.logspace(-3, np.log10(def_Gain.max), 10) dattorro.dsp.ui.p_Q = 2 cur_Q = dattorro.dsp.ui.p_Q.zone cur_F =",
"dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"G={:.3g} dB FS\".format(20*np.log10(g+1e-8))) p.legend(loc=\"best\") ########################################################### # plot",
"channel\"), loc=\"best\") ####################################################### # plot the frequency response with varying Q ####################################################### Q",
"\"(G={:.0f} dB FS, F={} Hz)\".format(20*np.log10(cur_G+1e-8), cur_F), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB",
"dattorro.dsp.ui.p_Q.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure() p = fig.add_subplot( 1, 1, 1,",
"response with varying Q ####################################################### Q = np.linspace(def_Q.min, def_Q.max, 10) dattorro.dsp.ui.p_Center_Freq = 1e2",
"p = fig.add_subplot( 1, 1, 1, title=\"Frequency response with the default settings\\n\" \"(Q={},",
"1, 1, 1, title=\"Frequency response (Q={}, F={} Hz)\".format(cur_Q, cur_F), xlabel=\"Frequency in Hz (log)\",",
"set up command line arguments ####################################################### parser = argparse.ArgumentParser() parser.add_argument('-f', '--faustfloat', dest=\"faustfloat\", default=\"float\",",
"'--cflags', dest=\"cflags\", default=[], type=str.split, help=\"Extra compiler flags\") parser.add_argument('-s', '--fs', dest=\"fs\", default=48000, type=int, help=\"The",
"import * ####################################################### # set up command line arguments ####################################################### parser = argparse.ArgumentParser()",
"matplotlib.pyplot as plt from FAUSTPy import * ####################################################### # set up command line",
"response \" \"(Q={}, G={:.0f} dB FS)\".format(cur_Q, 20*np.log10(cur_G+1e-8)), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in",
"spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"G={:.3g} dB FS\".format(20*np.log10(g+1e-8))) p.legend(loc=\"best\") ########################################################### # plot the",
"dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"F={:.2f} Hz\".format(f)) p.legend(loc=\"best\") ################ # show the",
":args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"F={:.2f} Hz\".format(f)) p.legend(loc=\"best\") ################ # show the plots ################ plt.show() print(\"everything",
"(log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for q in Q: dattorro.dsp.ui.p_Q =",
") for f in F: dattorro.dsp.ui.p_Center_Freq = f out = dattorro.compute(audio) spec =",
"cur_Q = dattorro.dsp.ui.p_Q.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure() p = fig.add_subplot( 1,",
"title=\"Frequency response \" \"(Q={}, G={:.0f} dB FS)\".format(cur_Q, 20*np.log10(cur_G+1e-8)), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude",
"####################################################### parser = argparse.ArgumentParser() parser.add_argument('-f', '--faustfloat', dest=\"faustfloat\", default=\"float\", help=\"The value of FAUSTFLOAT.\") parser.add_argument('-p',",
"the frequency response with the default settings ####################################################### audio = np.zeros((dattorro.dsp.num_in, args.fs), dtype=dattorro.dsp.dtype)",
"default=[], type=str.split, help=\"Extra compiler flags\") parser.add_argument('-s', '--fs', dest=\"fs\", default=48000, type=int, help=\"The sampling frequency\")",
"at an extremely low -160 dB G = np.logspace(-3, np.log10(def_Gain.max), 10) dattorro.dsp.ui.p_Q =",
"p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"G={:.3g} dB FS\".format(20*np.log10(g+1e-8))) p.legend(loc=\"best\") ########################################################### # plot the frequency response with varying",
"plot the frequency response with varying Q ####################################################### Q = np.linspace(def_Q.min, def_Q.max, 10)",
"# plot the frequency response with the default settings ####################################################### audio = np.zeros((dattorro.dsp.num_in,",
") for q in Q: dattorro.dsp.ui.p_Q = q out = dattorro.compute(audio) spec =",
"# plot the frequency response with varying gain ####################################################### # start at -60",
"in F: dattorro.dsp.ui.p_Center_Freq = f out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8),",
"default parameters ####################################################### wrapper.FAUST_PATH = args.faust_path dattorro = FAUST(\"dattorro_notch_cut_regalia.dsp\", args.fs, args.faustfloat, extra_compile_args=args.cflags) def_Q",
"10) dattorro.dsp.ui.p_Center_Freq = 1e2 dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10 dB cur_G = dattorro.dsp.ui.p_Gain.zone",
"to the FAUST compiler.\") parser.add_argument('-c', '--cflags', dest=\"cflags\", default=[], type=str.split, help=\"Extra compiler flags\") parser.add_argument('-s',",
"and get the default parameters ####################################################### wrapper.FAUST_PATH = args.faust_path dattorro = FAUST(\"dattorro_notch_cut_regalia.dsp\", args.fs,",
"= np.logspace(np.log10(def_Freq.min), np.log10(def_Freq.max), 10) dattorro.dsp.ui.p_Q = def_Q.default dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10 dB",
"the default settings\\n\" \"(Q={}, F={:.2f} Hz, G={:.0f} dB FS)\".format( def_Q.zone, def_Freq.zone, 20*np.log10(def_Gain.zone+1e-8) ),",
"F={:.2f} Hz, G={:.0f} dB FS)\".format( def_Q.zone, def_Freq.zone, 20*np.log10(def_Gain.zone+1e-8) ), xlabel=\"Frequency in Hz (log)\",",
"def_Gain = dattorro.dsp.ui.p_Gain def_Freq = dattorro.dsp.ui.p_Center_Freq ####################################################### # plot the frequency response with",
"= dattorro.dsp.ui.p_Gain.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure() p = fig.add_subplot( 1, 1,",
"initialise the FAUST object and get the default parameters ####################################################### wrapper.FAUST_PATH = args.faust_path",
"the frequency response with varying Q ####################################################### Q = np.linspace(def_Q.min, def_Q.max, 10) dattorro.dsp.ui.p_Center_Freq",
"spec = np.fft.fft(out)[:, :args.fs/2] fig = plt.figure() p = fig.add_subplot( 1, 1, 1,",
"= np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"G={:.3g} dB FS\".format(20*np.log10(g+1e-8))) p.legend(loc=\"best\") ########################################################### # plot the frequency",
"frequency ########################################################### F = np.logspace(np.log10(def_Freq.min), np.log10(def_Freq.max), 10) dattorro.dsp.ui.p_Q = def_Q.default dattorro.dsp.ui.p_Gain = 10**(-0.5)",
"# plot the frequency response with varying Q ####################################################### Q = np.linspace(def_Q.min, def_Q.max,",
"with the default settings\\n\" \"(Q={}, F={:.2f} Hz, G={:.0f} dB FS)\".format( def_Q.zone, def_Freq.zone, 20*np.log10(def_Gain.zone+1e-8)",
"title=\"Frequency response with the default settings\\n\" \"(Q={}, F={:.2f} Hz, G={:.0f} dB FS)\".format( def_Q.zone,",
":args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"G={:.3g} dB FS\".format(20*np.log10(g+1e-8))) p.legend(loc=\"best\") ########################################################### # plot the frequency response with",
"'--path', dest=\"faust_path\", default=\"\", help=\"The path to the FAUST compiler.\") parser.add_argument('-c', '--cflags', dest=\"cflags\", default=[],",
"= dattorro.dsp.ui.p_Center_Freq ####################################################### # plot the frequency response with the default settings #######################################################",
"plot the frequency response with varying center frequency ########################################################### F = np.logspace(np.log10(def_Freq.min), np.log10(def_Freq.max),",
"numpy as np import matplotlib.pyplot as plt from FAUSTPy import * ####################################################### #",
"frequency response with varying center frequency ########################################################### F = np.logspace(np.log10(def_Freq.min), np.log10(def_Freq.max), 10) dattorro.dsp.ui.p_Q",
"# start at -60 dB because the minimum is at an extremely low",
"= np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"Q={}\".format(q)) p.legend(loc=\"best\") ####################################################### # plot the frequency response with",
"response with varying center frequency ########################################################### F = np.logspace(np.log10(def_Freq.min), np.log10(def_Freq.max), 10) dattorro.dsp.ui.p_Q =",
"argparse import numpy as np import matplotlib.pyplot as plt from FAUSTPy import *",
"dB because the minimum is at an extremely low -160 dB G =",
"argparse.ArgumentParser() parser.add_argument('-f', '--faustfloat', dest=\"faustfloat\", default=\"float\", help=\"The value of FAUSTFLOAT.\") parser.add_argument('-p', '--path', dest=\"faust_path\", default=\"\",",
"plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response \" \"(G={:.0f} dB FS,",
"cur_G = dattorro.dsp.ui.p_Gain.zone fig = plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency",
"= q out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"Q={}\".format(q)) p.legend(loc=\"best\") #######################################################",
"def_Freq.zone, 20*np.log10(def_Gain.zone+1e-8) ), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" )",
"= dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"F={:.2f} Hz\".format(f)) p.legend(loc=\"best\") ################ # show",
"frequency response with varying gain ####################################################### # start at -60 dB because the",
"p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"F={:.2f} Hz\".format(f)) p.legend(loc=\"best\") ################ # show the plots ################ plt.show() print(\"everything passes!\")",
"out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"Q={}\".format(q)) p.legend(loc=\"best\") ####################################################### # plot",
"FS\", xscale=\"log\" ) p.plot(20*np.log10(np.absolute(spec.T)+1e-8)) p.legend((\"Left channel\", \"Right channel\"), loc=\"best\") ####################################################### # plot the",
"f out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"F={:.2f} Hz\".format(f)) p.legend(loc=\"best\") ################",
"plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response \" \"(Q={}, G={:.0f} dB",
"object and get the default parameters ####################################################### wrapper.FAUST_PATH = args.faust_path dattorro = FAUST(\"dattorro_notch_cut_regalia.dsp\",",
"cur_F), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for g",
"in G: dattorro.dsp.ui.p_Gain = g out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8),",
"1, 1, title=\"Frequency response (Q={}, F={} Hz)\".format(cur_Q, cur_F), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude",
"start at -60 dB because the minimum is at an extremely low -160",
"xscale=\"log\" ) for f in F: dattorro.dsp.ui.p_Center_Freq = f out = dattorro.compute(audio) spec",
"########################################################### F = np.logspace(np.log10(def_Freq.min), np.log10(def_Freq.max), 10) dattorro.dsp.ui.p_Q = def_Q.default dattorro.dsp.ui.p_Gain = 10**(-0.5) #",
"####################################################### # initialise the FAUST object and get the default parameters ####################################################### wrapper.FAUST_PATH",
"xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for q in",
"sampling frequency\") args = parser.parse_args() ####################################################### # initialise the FAUST object and get",
"1, 1, 1, title=\"Frequency response \" \"(Q={}, G={:.0f} dB FS)\".format(cur_Q, 20*np.log10(cur_G+1e-8)), xlabel=\"Frequency in",
"help=\"The value of FAUSTFLOAT.\") parser.add_argument('-p', '--path', dest=\"faust_path\", default=\"\", help=\"The path to the FAUST",
"####################################################### # start at -60 dB because the minimum is at an extremely",
"= dattorro.dsp.ui.p_Q.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure() p = fig.add_subplot( 1, 1,",
"dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10 dB cur_G = dattorro.dsp.ui.p_Gain.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig",
"def_Q.max, 10) dattorro.dsp.ui.p_Center_Freq = 1e2 dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10 dB cur_G =",
"varying gain ####################################################### # start at -60 dB because the minimum is at",
"-160 dB G = np.logspace(-3, np.log10(def_Gain.max), 10) dattorro.dsp.ui.p_Q = 2 cur_Q = dattorro.dsp.ui.p_Q.zone",
"args.fs), dtype=dattorro.dsp.dtype) audio[:, 0] = 1 out = dattorro.compute(audio) print(audio) print(out) spec =",
"out = dattorro.compute(audio) print(audio) print(out) spec = np.fft.fft(out)[:, :args.fs/2] fig = plt.figure() p",
"dB FS\", xscale=\"log\" ) p.plot(20*np.log10(np.absolute(spec.T)+1e-8)) p.legend((\"Left channel\", \"Right channel\"), loc=\"best\") ####################################################### # plot",
"from FAUSTPy import * ####################################################### # set up command line arguments ####################################################### parser",
"response (Q={}, F={} Hz)\".format(cur_Q, cur_F), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\",",
"p.legend((\"Left channel\", \"Right channel\"), loc=\"best\") ####################################################### # plot the frequency response with varying",
"dattorro.dsp.ui.p_Gain.zone fig = plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response \"",
"FS\", xscale=\"log\" ) for q in Q: dattorro.dsp.ui.p_Q = q out = dattorro.compute(audio)",
"= dattorro.compute(audio) print(audio) print(out) spec = np.fft.fft(out)[:, :args.fs/2] fig = plt.figure() p =",
"dattorro.dsp.ui.p_Q = 2 cur_Q = dattorro.dsp.ui.p_Q.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure() p",
"FAUST(\"dattorro_notch_cut_regalia.dsp\", args.fs, args.faustfloat, extra_compile_args=args.cflags) def_Q = dattorro.dsp.ui.p_Q def_Gain = dattorro.dsp.ui.p_Gain def_Freq = dattorro.dsp.ui.p_Center_Freq",
"np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"Q={}\".format(q)) p.legend(loc=\"best\") ####################################################### # plot the frequency response with varying",
"Hz, G={:.0f} dB FS)\".format( def_Q.zone, def_Freq.zone, 20*np.log10(def_Gain.zone+1e-8) ), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude",
"import matplotlib.pyplot as plt from FAUSTPy import * ####################################################### # set up command",
"####################################################### Q = np.linspace(def_Q.min, def_Q.max, 10) dattorro.dsp.ui.p_Center_Freq = 1e2 dattorro.dsp.ui.p_Gain = 10**(-0.5) #",
"parser.parse_args() ####################################################### # initialise the FAUST object and get the default parameters #######################################################",
"p.plot(20*np.log10(np.absolute(spec.T)+1e-8)) p.legend((\"Left channel\", \"Right channel\"), loc=\"best\") ####################################################### # plot the frequency response with",
"as np import matplotlib.pyplot as plt from FAUSTPy import * ####################################################### # set",
"10) dattorro.dsp.ui.p_Q = 2 cur_Q = dattorro.dsp.ui.p_Q.zone cur_F = dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure()",
"= np.linspace(def_Q.min, def_Q.max, 10) dattorro.dsp.ui.p_Center_Freq = 1e2 dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10 dB",
"settings\\n\" \"(Q={}, F={:.2f} Hz, G={:.0f} dB FS)\".format( def_Q.zone, def_Freq.zone, 20*np.log10(def_Gain.zone+1e-8) ), xlabel=\"Frequency in",
"the FAUST object and get the default parameters ####################################################### wrapper.FAUST_PATH = args.faust_path dattorro",
"loc=\"best\") ####################################################### # plot the frequency response with varying Q ####################################################### Q =",
"dattorro.dsp.ui.p_Center_Freq.zone fig = plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response (Q={},",
"= dattorro.dsp.ui.p_Gain.zone fig = plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response",
"dattorro.dsp.ui.p_Center_Freq = 1e2 dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10 dB cur_G = dattorro.dsp.ui.p_Gain.zone cur_F",
"parser.add_argument('-f', '--faustfloat', dest=\"faustfloat\", default=\"float\", help=\"The value of FAUSTFLOAT.\") parser.add_argument('-p', '--path', dest=\"faust_path\", default=\"\", help=\"The",
"fig = plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response \" \"(G={:.0f}",
"dB FS\", xscale=\"log\" ) for g in G: dattorro.dsp.ui.p_Gain = g out =",
"FAUST object and get the default parameters ####################################################### wrapper.FAUST_PATH = args.faust_path dattorro =",
"dest=\"fs\", default=48000, type=int, help=\"The sampling frequency\") args = parser.parse_args() ####################################################### # initialise the",
"default settings\\n\" \"(Q={}, F={:.2f} Hz, G={:.0f} dB FS)\".format( def_Q.zone, def_Freq.zone, 20*np.log10(def_Gain.zone+1e-8) ), xlabel=\"Frequency",
"G={:.0f} dB FS)\".format( def_Q.zone, def_Freq.zone, 20*np.log10(def_Gain.zone+1e-8) ), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in",
"= dattorro.dsp.ui.p_Q def_Gain = dattorro.dsp.ui.p_Gain def_Freq = dattorro.dsp.ui.p_Center_Freq ####################################################### # plot the frequency",
"Hz)\".format(cur_Q, cur_F), xlabel=\"Frequency in Hz (log)\", ylabel=\"Magnitude in dB FS\", xscale=\"log\" ) for",
"'--faustfloat', dest=\"faustfloat\", default=\"float\", help=\"The value of FAUSTFLOAT.\") parser.add_argument('-p', '--path', dest=\"faust_path\", default=\"\", help=\"The path",
"args = parser.parse_args() ####################################################### # initialise the FAUST object and get the default",
"fig = plt.figure() p = fig.add_subplot( 1, 1, 1, title=\"Frequency response \" \"(Q={},",
"label=\"G={:.3g} dB FS\".format(20*np.log10(g+1e-8))) p.legend(loc=\"best\") ########################################################### # plot the frequency response with varying center",
"####################################################### audio = np.zeros((dattorro.dsp.num_in, args.fs), dtype=dattorro.dsp.dtype) audio[:, 0] = 1 out = dattorro.compute(audio)",
"in Q: dattorro.dsp.ui.p_Q = q out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8),",
"p = fig.add_subplot( 1, 1, 1, title=\"Frequency response (Q={}, F={} Hz)\".format(cur_Q, cur_F), xlabel=\"Frequency",
"F: dattorro.dsp.ui.p_Center_Freq = f out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"F={:.2f}",
"F = np.logspace(np.log10(def_Freq.min), np.log10(def_Freq.max), 10) dattorro.dsp.ui.p_Q = def_Q.default dattorro.dsp.ui.p_Gain = 10**(-0.5) # -10",
"dattorro.dsp.ui.p_Gain def_Freq = dattorro.dsp.ui.p_Center_Freq ####################################################### # plot the frequency response with the default",
"dattorro.dsp.ui.p_Gain = g out = dattorro.compute(audio) spec = np.fft.fft(out)[0, :args.fs/2] p.plot(20*np.log10(np.absolute(spec.T)+1e-8), label=\"G={:.3g} dB"
] |
[
"from .core import BaseRunner from .solo import SingleThreadASGIRunner, SingleThreadRunner, SingleThreadWSGIRunner from .threadpool import",
"import BaseRunner from .solo import SingleThreadASGIRunner, SingleThreadRunner, SingleThreadWSGIRunner from .threadpool import ThreadPoolASGIRunner, ThreadPoolRunner,",
"BaseRunner from .solo import SingleThreadASGIRunner, SingleThreadRunner, SingleThreadWSGIRunner from .threadpool import ThreadPoolASGIRunner, ThreadPoolRunner, ThreadPoolWSGIRunner",
".core import BaseRunner from .solo import SingleThreadASGIRunner, SingleThreadRunner, SingleThreadWSGIRunner from .threadpool import ThreadPoolASGIRunner,",
"<gh_stars>100-1000 from .core import BaseRunner from .solo import SingleThreadASGIRunner, SingleThreadRunner, SingleThreadWSGIRunner from .threadpool"
] |
[
"long_description=open(\"README.md\", \"r\").read(), long_description_content_type=\"text/markdown\", include_package_data=True, exclude_package_date={'': ['.gitignore']}, keywords='tcp, tunnel, tcp-tunnel, tcptunnel', license='MIT License', url='https://github.com/sqxccdy/tcp-tunnel.git',",
"'tcp_tunnel.*',]), author='<NAME>', author_email='<EMAIL>', long_description=open(\"README.md\", \"r\").read(), long_description_content_type=\"text/markdown\", include_package_data=True, exclude_package_date={'': ['.gitignore']}, keywords='tcp, tunnel, tcp-tunnel, tcptunnel',",
"OS Independent', 'Natural Language :: Chinese (Simplified)', 'Programming Language :: Python', 'Programming Language",
"(Simplified)', 'Programming Language :: Python', 'Programming Language :: Python :: 3.8', 'Programming Language",
"['.gitignore']}, keywords='tcp, tunnel, tcp-tunnel, tcptunnel', license='MIT License', url='https://github.com/sqxccdy/tcp-tunnel.git', entry_points={ 'console_scripts': [ 'aiomq_server=aiomq.server:run' ]",
"tcp-tunnel, tcptunnel', license='MIT License', url='https://github.com/sqxccdy/tcp-tunnel.git', entry_points={ 'console_scripts': [ 'aiomq_server=aiomq.server:run' ] }, install_requires=[], classifiers=[",
"] }, install_requires=[], classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience ::",
"'Natural Language :: Chinese (Simplified)', 'Programming Language :: Python', 'Programming Language :: Python",
"py2applet Usage: python setup.py py2app \"\"\" try: from setuptools import setup except ImportError:",
"setup except ImportError: from distutils.core import setup from setuptools import setup, find_packages import",
"Language :: Chinese (Simplified)', 'Programming Language :: Python', 'Programming Language :: Python ::",
"Language :: Python', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python",
"setup.py script generated by py2applet Usage: python setup.py py2app \"\"\" try: from setuptools",
"'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.7', 'Programming",
"is a setup.py script generated by py2applet Usage: python setup.py py2app \"\"\" try:",
"keywords='tcp, tunnel, tcp-tunnel, tcptunnel', license='MIT License', url='https://github.com/sqxccdy/tcp-tunnel.git', entry_points={ 'console_scripts': [ 'aiomq_server=aiomq.server:run' ] },",
"script generated by py2applet Usage: python setup.py py2app \"\"\" try: from setuptools import",
":: Python :: 3.8', 'Programming Language :: Python :: 3.7', 'Programming Language ::",
"\"\"\" try: from setuptools import setup except ImportError: from distutils.core import setup from",
"or Lesser General Public License (LGPL)', 'Operating System :: OS Independent', 'Natural Language",
":: 3.7', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development ::",
"setuptools import setup except ImportError: from distutils.core import setup from setuptools import setup,",
"- Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library",
"ImportError: from distutils.core import setup from setuptools import setup, find_packages import tcp_tunnel setup(name=\"tcp-tunnel\",",
"long_description_content_type=\"text/markdown\", include_package_data=True, exclude_package_date={'': ['.gitignore']}, keywords='tcp, tunnel, tcp-tunnel, tcptunnel', license='MIT License', url='https://github.com/sqxccdy/tcp-tunnel.git', entry_points={ 'console_scripts':",
":: Python :: 3.7', 'Programming Language :: Python :: 3.6', 'Topic :: Software",
"3.7', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Libraries',",
"Python', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.7',",
"python setup.py py2app \"\"\" try: from setuptools import setup except ImportError: from distutils.core",
"Python :: 3.6', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities', ],",
"tcp_tunnel setup(name=\"tcp-tunnel\", version=tcp_tunnel.VERSION, packages=find_packages(include=['tcp_tunnel', 'tcp_tunnel.*',]), author='<NAME>', author_email='<EMAIL>', long_description=open(\"README.md\", \"r\").read(), long_description_content_type=\"text/markdown\", include_package_data=True, exclude_package_date={'': ['.gitignore']},",
"classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License ::",
"Chinese (Simplified)', 'Programming Language :: Python', 'Programming Language :: Python :: 3.8', 'Programming",
"License', url='https://github.com/sqxccdy/tcp-tunnel.git', entry_points={ 'console_scripts': [ 'aiomq_server=aiomq.server:run' ] }, install_requires=[], classifiers=[ 'Development Status ::",
"Language :: Python :: 3.6', 'Topic :: Software Development :: Libraries', 'Topic ::",
"by py2applet Usage: python setup.py py2app \"\"\" try: from setuptools import setup except",
"except ImportError: from distutils.core import setup from setuptools import setup, find_packages import tcp_tunnel",
"Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved",
"Audience :: Developers', 'License :: OSI Approved :: GNU Library or Lesser General",
"setup.py py2app \"\"\" try: from setuptools import setup except ImportError: from distutils.core import",
"setup from setuptools import setup, find_packages import tcp_tunnel setup(name=\"tcp-tunnel\", version=tcp_tunnel.VERSION, packages=find_packages(include=['tcp_tunnel', 'tcp_tunnel.*',]), author='<NAME>',",
"'console_scripts': [ 'aiomq_server=aiomq.server:run' ] }, install_requires=[], classifiers=[ 'Development Status :: 1 - Planning',",
"tcptunnel', license='MIT License', url='https://github.com/sqxccdy/tcp-tunnel.git', entry_points={ 'console_scripts': [ 'aiomq_server=aiomq.server:run' ] }, install_requires=[], classifiers=[ 'Development",
"GNU Library or Lesser General Public License (LGPL)', 'Operating System :: OS Independent',",
"<gh_stars>1-10 \"\"\" This is a setup.py script generated by py2applet Usage: python setup.py",
":: 3.8', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python ::",
"setup, find_packages import tcp_tunnel setup(name=\"tcp-tunnel\", version=tcp_tunnel.VERSION, packages=find_packages(include=['tcp_tunnel', 'tcp_tunnel.*',]), author='<NAME>', author_email='<EMAIL>', long_description=open(\"README.md\", \"r\").read(), long_description_content_type=\"text/markdown\",",
"include_package_data=True, exclude_package_date={'': ['.gitignore']}, keywords='tcp, tunnel, tcp-tunnel, tcptunnel', license='MIT License', url='https://github.com/sqxccdy/tcp-tunnel.git', entry_points={ 'console_scripts': [",
"license='MIT License', url='https://github.com/sqxccdy/tcp-tunnel.git', entry_points={ 'console_scripts': [ 'aiomq_server=aiomq.server:run' ] }, install_requires=[], classifiers=[ 'Development Status",
":: GNU Library or Lesser General Public License (LGPL)', 'Operating System :: OS",
"Python :: 3.8', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python",
"import tcp_tunnel setup(name=\"tcp-tunnel\", version=tcp_tunnel.VERSION, packages=find_packages(include=['tcp_tunnel', 'tcp_tunnel.*',]), author='<NAME>', author_email='<EMAIL>', long_description=open(\"README.md\", \"r\").read(), long_description_content_type=\"text/markdown\", include_package_data=True, exclude_package_date={'':",
"generated by py2applet Usage: python setup.py py2app \"\"\" try: from setuptools import setup",
"System :: OS Independent', 'Natural Language :: Chinese (Simplified)', 'Programming Language :: Python',",
":: Python :: 3.6', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities',",
"'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',",
"find_packages import tcp_tunnel setup(name=\"tcp-tunnel\", version=tcp_tunnel.VERSION, packages=find_packages(include=['tcp_tunnel', 'tcp_tunnel.*',]), author='<NAME>', author_email='<EMAIL>', long_description=open(\"README.md\", \"r\").read(), long_description_content_type=\"text/markdown\", include_package_data=True,",
"packages=find_packages(include=['tcp_tunnel', 'tcp_tunnel.*',]), author='<NAME>', author_email='<EMAIL>', long_description=open(\"README.md\", \"r\").read(), long_description_content_type=\"text/markdown\", include_package_data=True, exclude_package_date={'': ['.gitignore']}, keywords='tcp, tunnel, tcp-tunnel,",
"Public License (LGPL)', 'Operating System :: OS Independent', 'Natural Language :: Chinese (Simplified)',",
"from distutils.core import setup from setuptools import setup, find_packages import tcp_tunnel setup(name=\"tcp-tunnel\", version=tcp_tunnel.VERSION,",
"\"\"\" This is a setup.py script generated by py2applet Usage: python setup.py py2app",
"(LGPL)', 'Operating System :: OS Independent', 'Natural Language :: Chinese (Simplified)', 'Programming Language",
"General Public License (LGPL)', 'Operating System :: OS Independent', 'Natural Language :: Chinese",
"'aiomq_server=aiomq.server:run' ] }, install_requires=[], classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience",
"setuptools import setup, find_packages import tcp_tunnel setup(name=\"tcp-tunnel\", version=tcp_tunnel.VERSION, packages=find_packages(include=['tcp_tunnel', 'tcp_tunnel.*',]), author='<NAME>', author_email='<EMAIL>', long_description=open(\"README.md\",",
"'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Libraries', 'Topic",
"import setup except ImportError: from distutils.core import setup from setuptools import setup, find_packages",
"'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.6', 'Topic",
"Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library or",
"3.8', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.6',",
"License (LGPL)', 'Operating System :: OS Independent', 'Natural Language :: Chinese (Simplified)', 'Programming",
"import setup, find_packages import tcp_tunnel setup(name=\"tcp-tunnel\", version=tcp_tunnel.VERSION, packages=find_packages(include=['tcp_tunnel', 'tcp_tunnel.*',]), author='<NAME>', author_email='<EMAIL>', long_description=open(\"README.md\", \"r\").read(),",
"'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI",
"version=tcp_tunnel.VERSION, packages=find_packages(include=['tcp_tunnel', 'tcp_tunnel.*',]), author='<NAME>', author_email='<EMAIL>', long_description=open(\"README.md\", \"r\").read(), long_description_content_type=\"text/markdown\", include_package_data=True, exclude_package_date={'': ['.gitignore']}, keywords='tcp, tunnel,",
"Independent', 'Natural Language :: Chinese (Simplified)', 'Programming Language :: Python', 'Programming Language ::",
"entry_points={ 'console_scripts': [ 'aiomq_server=aiomq.server:run' ] }, install_requires=[], classifiers=[ 'Development Status :: 1 -",
"from setuptools import setup, find_packages import tcp_tunnel setup(name=\"tcp-tunnel\", version=tcp_tunnel.VERSION, packages=find_packages(include=['tcp_tunnel', 'tcp_tunnel.*',]), author='<NAME>', author_email='<EMAIL>',",
"'Operating System :: OS Independent', 'Natural Language :: Chinese (Simplified)', 'Programming Language ::",
"exclude_package_date={'': ['.gitignore']}, keywords='tcp, tunnel, tcp-tunnel, tcptunnel', license='MIT License', url='https://github.com/sqxccdy/tcp-tunnel.git', entry_points={ 'console_scripts': [ 'aiomq_server=aiomq.server:run'",
"}, install_requires=[], classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers',",
"setup(name=\"tcp-tunnel\", version=tcp_tunnel.VERSION, packages=find_packages(include=['tcp_tunnel', 'tcp_tunnel.*',]), author='<NAME>', author_email='<EMAIL>', long_description=open(\"README.md\", \"r\").read(), long_description_content_type=\"text/markdown\", include_package_data=True, exclude_package_date={'': ['.gitignore']}, keywords='tcp,",
"url='https://github.com/sqxccdy/tcp-tunnel.git', entry_points={ 'console_scripts': [ 'aiomq_server=aiomq.server:run' ] }, install_requires=[], classifiers=[ 'Development Status :: 1",
"[ 'aiomq_server=aiomq.server:run' ] }, install_requires=[], classifiers=[ 'Development Status :: 1 - Planning', 'Intended",
"\"r\").read(), long_description_content_type=\"text/markdown\", include_package_data=True, exclude_package_date={'': ['.gitignore']}, keywords='tcp, tunnel, tcp-tunnel, tcptunnel', license='MIT License', url='https://github.com/sqxccdy/tcp-tunnel.git', entry_points={",
"a setup.py script generated by py2applet Usage: python setup.py py2app \"\"\" try: from",
"This is a setup.py script generated by py2applet Usage: python setup.py py2app \"\"\"",
":: Python', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python ::",
"Library or Lesser General Public License (LGPL)', 'Operating System :: OS Independent', 'Natural",
"distutils.core import setup from setuptools import setup, find_packages import tcp_tunnel setup(name=\"tcp-tunnel\", version=tcp_tunnel.VERSION, packages=find_packages(include=['tcp_tunnel',",
"import setup from setuptools import setup, find_packages import tcp_tunnel setup(name=\"tcp-tunnel\", version=tcp_tunnel.VERSION, packages=find_packages(include=['tcp_tunnel', 'tcp_tunnel.*',]),",
"tunnel, tcp-tunnel, tcptunnel', license='MIT License', url='https://github.com/sqxccdy/tcp-tunnel.git', entry_points={ 'console_scripts': [ 'aiomq_server=aiomq.server:run' ] }, install_requires=[],",
":: 3.6', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities', ], )",
"OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Operating System",
"Language :: Python :: 3.8', 'Programming Language :: Python :: 3.7', 'Programming Language",
"author_email='<EMAIL>', long_description=open(\"README.md\", \"r\").read(), long_description_content_type=\"text/markdown\", include_package_data=True, exclude_package_date={'': ['.gitignore']}, keywords='tcp, tunnel, tcp-tunnel, tcptunnel', license='MIT License',",
":: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved ::",
"'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library or Lesser",
"try: from setuptools import setup except ImportError: from distutils.core import setup from setuptools",
"Developers', 'License :: OSI Approved :: GNU Library or Lesser General Public License",
":: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Operating",
"author='<NAME>', author_email='<EMAIL>', long_description=open(\"README.md\", \"r\").read(), long_description_content_type=\"text/markdown\", include_package_data=True, exclude_package_date={'': ['.gitignore']}, keywords='tcp, tunnel, tcp-tunnel, tcptunnel', license='MIT",
"install_requires=[], classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License",
"1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU",
":: Developers', 'License :: OSI Approved :: GNU Library or Lesser General Public",
"Approved :: GNU Library or Lesser General Public License (LGPL)', 'Operating System ::",
"py2app \"\"\" try: from setuptools import setup except ImportError: from distutils.core import setup",
"Lesser General Public License (LGPL)', 'Operating System :: OS Independent', 'Natural Language ::",
"'Programming Language :: Python', 'Programming Language :: Python :: 3.8', 'Programming Language ::",
"Usage: python setup.py py2app \"\"\" try: from setuptools import setup except ImportError: from",
"Language :: Python :: 3.7', 'Programming Language :: Python :: 3.6', 'Topic ::",
"Python :: 3.7', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development",
"from setuptools import setup except ImportError: from distutils.core import setup from setuptools import",
":: Chinese (Simplified)', 'Programming Language :: Python', 'Programming Language :: Python :: 3.8',",
":: OS Independent', 'Natural Language :: Chinese (Simplified)', 'Programming Language :: Python', 'Programming"
] |
[
"import FlaskForm from . import SubmitField class ActionTable(FlaskForm): activate = SubmitField('Activate') deactivate =",
"<filename>pertemuan_8/7_HTTP_API_With_Sensor/app/forms/_action.py from . import FlaskForm from . import SubmitField class ActionTable(FlaskForm): activate =",
". import FlaskForm from . import SubmitField class ActionTable(FlaskForm): activate = SubmitField('Activate') deactivate",
"import SubmitField class ActionTable(FlaskForm): activate = SubmitField('Activate') deactivate = SubmitField('Deactivate') delete = SubmitField('Delete')",
"FlaskForm from . import SubmitField class ActionTable(FlaskForm): activate = SubmitField('Activate') deactivate = SubmitField('Deactivate')",
"from . import FlaskForm from . import SubmitField class ActionTable(FlaskForm): activate = SubmitField('Activate')",
". import SubmitField class ActionTable(FlaskForm): activate = SubmitField('Activate') deactivate = SubmitField('Deactivate') delete =",
"from . import SubmitField class ActionTable(FlaskForm): activate = SubmitField('Activate') deactivate = SubmitField('Deactivate') delete"
] |
[
"= splitext(f) if ext == '.scss' and name[0] != '_': print(\"[sass] \" +",
"if __name__ == '__main__': try: arg = sys.argv[1] except IndexError: arg = None",
"\" {\\n\" files_and_extensions = [(f, splitext(f)[1][1:]) for f in files] for image, ext",
"http.server.SimpleHTTPRequestHandler httpd = TemporaryTCPServer((\"\", port), handler) print(\"[serve] serving on port \" + str(port))",
"splitext(basename(f)) if ext in ['.svg']: vectors += [f] if ext in ['.png']: rasters",
"+ \" {\\n\" files_and_extensions = [(f, splitext(f)[1][1:]) for f in files] for image,",
"import sys import http.server import socketserver import socket import shutil from base64 import",
"= '.image-' + name + \" {\\n\" files_and_extensions = [(f, splitext(f)[1][1:]) for f",
"+ ext + '+xml;charset=US-ASCII,' + data def image_data(image_filename): _, ext = splitext(image_filename) if",
"images_in_dir(images_dir): name, _ = splitext(basename(image)) images[name] += [image] return dict(images) def images_to_css(images_dir): images",
"clean(): shutil.rmtree(build_dir) shutil.rmtree(dest_dir) def build(): copy_tree(source_dir, build_dir, update=1) make_fallback_images(images_dir) print('[create] _images.scss ', end='')",
"name, ext = splitext(basename(f)) if ext in ['.svg']: vectors += [f] if ext",
"ext == '.svg': return xml_data(image_filename, ext) else: return raster_data(image_filename, ext) if __name__ ==",
"(dirpath, dirnames, filenames) in os.walk(css_source_dir): for f in filenames: name, ext = splitext(f)",
"+= 'background-image: url(' + data + \");\\n\" for svg, ext in [(f, ext)",
"def image_data(image_filename): _, ext = splitext(image_filename) if ext == '.svg': return xml_data(image_filename, ext)",
"\"), linear-gradient(transparent, transparent);\\n\" css += \"}\\n\" csseses += [css] return \"\\n\".join(csseses) def save_images_css(images_dir,",
"\"\\n\".join(csseses) def save_images_css(images_dir, css_file): with open(css_file, 'w') as f: f.write(images_to_css(images_dir)) def raster_data(image_filename, ext):",
"[image] return dict(images) def images_to_css(images_dir): images = find_built_images(images_dir) csseses = [] for name,",
"data = xml_data(join(images_dir, svg), ext) css += 'background-image: url(' + data + \"),",
"check = True) print(\"[ok]\") def images_in_dir(dir): vectors = [] rasters = [] dumb_rasters",
"dest_dir = 'built_static' css_dir = join(build_dir, 'css') images_dir = join(build_dir, 'images') class TemporaryTCPServer(socketserver.TCPServer):",
"splitext(f)[1][1:]) for f in files] for image, ext in [(f, ext) for f,",
"1) self.socket.bind(self.server_address) def serve(port): os.chdir(dest_dir) handler = http.server.SimpleHTTPRequestHandler httpd = TemporaryTCPServer((\"\", port), handler)",
"f), join(css_dest_dir, f), update=1) print(\"[ok]\") break def make_fallback_images(images_dir): images = find_built_images(images_dir) for image,",
"make_fallback_images(images_dir): images = find_built_images(images_dir) for image, files in images.items(): f = files[0] pngimage",
"'clean': clean() elif arg == 'serve': try: port = int(sys.argv[2]) except IndexError: port",
"= [] dumb_rasters = [] lossy = [] for (dirpath, dirnames, filenames) in",
"f, ext in files_and_extensions if ext == 'svg']: data = xml_data(join(images_dir, svg), ext)",
"with open(css_file, 'w') as f: f.write(images_to_css(images_dir)) def raster_data(image_filename, ext): with open(image_filename, 'rb') as",
"port \" + str(port)) httpd.serve_forever() def clean(): shutil.rmtree(build_dir) shutil.rmtree(dest_dir) def build(): copy_tree(source_dir, build_dir,",
"8000 build() serve(port) else: print('please use \"build\", \"clean\" or \"serve\" as a first",
"ext in files_and_extensions if ext != 'svg']: data = raster_data(join(images_dir, image), ext) css",
"'build': build() elif arg == 'clean': clean() elif arg == 'serve': try: port",
"dumb_rasters = [] lossy = [] for (dirpath, dirnames, filenames) in os.walk(dir): for",
"f), join(css_dest_dir, name + '.css') ], check = True) print(\"[ok]\") elif ext ==",
"ext in ['.svg']: vectors += [f] if ext in ['.png']: rasters += [f]",
"+ dumb_rasters + lossy def find_built_images(images_dir): images = defaultdict(list) for image in images_in_dir(images_dir):",
"def clean(): shutil.rmtree(build_dir) shutil.rmtree(dest_dir) def build(): copy_tree(source_dir, build_dir, update=1) make_fallback_images(images_dir) print('[create] _images.scss ',",
"+ f + ' ', end='') run([ 'sass', join(css_source_dir, f), join(css_dest_dir, name +",
"= True) print(\"[ok]\") elif ext == '.css': print(\"[copy] \" + f + '",
"serve(port): os.chdir(dest_dir) handler = http.server.SimpleHTTPRequestHandler httpd = TemporaryTCPServer((\"\", port), handler) print(\"[serve] serving on",
"svg), ext) css += 'background-image: url(' + data + \"), linear-gradient(transparent, transparent);\\n\" css",
"svg, ext in [(f, ext) for f, ext in files_and_extensions if ext ==",
"= raster_data(join(images_dir, image), ext) css += 'background-image: url(' + data + \");\\n\" for",
"+ \"), linear-gradient(transparent, transparent);\\n\" css += \"}\\n\" csseses += [css] return \"\\n\".join(csseses) def",
"dumb_rasters + lossy def find_built_images(images_dir): images = defaultdict(list) for image in images_in_dir(images_dir): name,",
"ext + '+xml;charset=US-ASCII,' + data def image_data(image_filename): _, ext = splitext(image_filename) if ext",
"filenames: name, ext = splitext(basename(f)) if ext in ['.svg']: vectors += [f] if",
"ext == '.css': print(\"[copy] \" + f + ' ', end='') copy_file(join(css_source_dir, f),",
"check = True) print(\"[ok]\") elif ext == '.css': print(\"[copy] \" + f +",
"rasters += [f] if ext in ['.gif']: dumb_rasters += [f] if ext in",
"= [] rasters = [] dumb_rasters = [] lossy = [] for (dirpath,",
"open(css_file, 'w') as f: f.write(images_to_css(images_dir)) def raster_data(image_filename, ext): with open(image_filename, 'rb') as f:",
"+ ' ', end='') run([ 'convert', '-background', 'none', join(images_dir, f), join(images_dir, pngimage) ],",
"if ext != 'svg']: data = raster_data(join(images_dir, image), ext) css += 'background-image: url('",
"+= 'background-image: url(' + data + \"), linear-gradient(transparent, transparent);\\n\" css += \"}\\n\" csseses",
"== 'build': build() elif arg == 'clean': clean() elif arg == 'serve': try:",
"open(image_filename, 'r') as f: data = quote(f.read()) return 'data:image/' + ext + '+xml;charset=US-ASCII,'",
"def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) def serve(port): os.chdir(dest_dir) handler = http.server.SimpleHTTPRequestHandler httpd",
"\" + pngimage + ' ', end='') run([ 'convert', '-background', 'none', join(images_dir, f),",
"image in images_in_dir(images_dir): name, _ = splitext(basename(image)) images[name] += [image] return dict(images) def",
"b64encode from urllib.parse import quote from os.path import basename, splitext, join, isfile from",
"f in files] for image, ext in [(f, ext) for f, ext in",
"in files_and_extensions if ext != 'svg']: data = raster_data(join(images_dir, image), ext) css +=",
"data = b64encode(f.read()).decode('utf-8') return 'data:image/' + ext + ';base64,' + data def xml_data(image_filename,",
"_, ext = splitext(image_filename) if ext == '.svg': return xml_data(image_filename, ext) else: return",
"copy_file(join(css_source_dir, f), join(css_dest_dir, f), update=1) print(\"[ok]\") break def make_fallback_images(images_dir): images = find_built_images(images_dir) for",
"join(images_dir, pngimage) ], check = True) print(\"[ok]\") def images_in_dir(dir): vectors = [] rasters",
"[f] if ext in ['.jpg', '.jpeg']: lossy += [f] break return vectors +",
"{\\n\" files_and_extensions = [(f, splitext(f)[1][1:]) for f in files] for image, ext in",
"= find_built_images(images_dir) csseses = [] for name, files in images.items(): css = '.image-'",
"clean() elif arg == 'serve': try: port = int(sys.argv[2]) except IndexError: port =",
"ext = splitext(image_filename) if ext == '.svg': return xml_data(image_filename, ext) else: return raster_data(image_filename,",
"f = files[0] pngimage = image + '.png' if pngimage not in files:",
"data + \");\\n\" for svg, ext in [(f, ext) for f, ext in",
"with open(image_filename, 'rb') as f: data = b64encode(f.read()).decode('utf-8') return 'data:image/' + ext +",
"copy_tree(source_dir, build_dir, update=1) make_fallback_images(images_dir) print('[create] _images.scss ', end='') save_images_css(images_dir, join(css_dir, '_images.scss')) print('[ok]') run_sass(css_dir,",
"f.write(images_to_css(images_dir)) def raster_data(image_filename, ext): with open(image_filename, 'rb') as f: data = b64encode(f.read()).decode('utf-8') return",
"import basename, splitext, join, isfile from collections import defaultdict from subprocess import run",
"pngimage not in files: print(\"[create] \" + pngimage + ' ', end='') run([",
"_ = splitext(basename(image)) images[name] += [image] return dict(images) def images_to_css(images_dir): images = find_built_images(images_dir)",
"import copy_file build_dir = 'build' source_dir = 'source' dest_dir = 'built_static' css_dir =",
"if ext in ['.gif']: dumb_rasters += [f] if ext in ['.jpg', '.jpeg']: lossy",
"data def xml_data(image_filename, ext): with open(image_filename, 'r') as f: data = quote(f.read()) return",
"pngimage) ], check = True) print(\"[ok]\") def images_in_dir(dir): vectors = [] rasters =",
"'r') as f: data = quote(f.read()) return 'data:image/' + ext + '+xml;charset=US-ASCII,' +",
"for (dirpath, dirnames, filenames) in os.walk(dir): for f in filenames: name, ext =",
"if arg == 'build': build() elif arg == 'clean': clean() elif arg ==",
"base64 import b64encode from urllib.parse import quote from os.path import basename, splitext, join,",
"from distutils.file_util import copy_file build_dir = 'build' source_dir = 'source' dest_dir = 'built_static'",
"', end='') run([ 'convert', '-background', 'none', join(images_dir, f), join(images_dir, pngimage) ], check =",
"css_file): with open(css_file, 'w') as f: f.write(images_to_css(images_dir)) def raster_data(image_filename, ext): with open(image_filename, 'rb')",
"in files] for image, ext in [(f, ext) for f, ext in files_and_extensions",
"sys import http.server import socketserver import socket import shutil from base64 import b64encode",
"if ext == '.svg': return xml_data(image_filename, ext) else: return raster_data(image_filename, ext) if __name__",
"join(css_dir, '_images.scss')) print('[ok]') run_sass(css_dir, join(dest_dir, 'css')) print('[update] asis ', end='') copy_tree(join(source_dir, 'asis'), join(dest_dir,",
"source_dir = 'source' dest_dir = 'built_static' css_dir = join(build_dir, 'css') images_dir = join(build_dir,",
"files_and_extensions if ext == 'svg']: data = xml_data(join(images_dir, svg), ext) css += 'background-image:",
"join(css_dest_dir, name + '.css') ], check = True) print(\"[ok]\") elif ext == '.css':",
"'_': print(\"[sass] \" + f + ' ', end='') run([ 'sass', join(css_source_dir, f),",
"files: print(\"[create] \" + pngimage + ' ', end='') run([ 'convert', '-background', 'none',",
"print(\"[serve] serving on port \" + str(port)) httpd.serve_forever() def clean(): shutil.rmtree(build_dir) shutil.rmtree(dest_dir) def",
"handler = http.server.SimpleHTTPRequestHandler httpd = TemporaryTCPServer((\"\", port), handler) print(\"[serve] serving on port \"",
"== '.css': print(\"[copy] \" + f + ' ', end='') copy_file(join(css_source_dir, f), join(css_dest_dir,",
"'asis'), update=1) print('[ok]') def run_sass(css_source_dir, css_dest_dir): os.makedirs(css_dest_dir, exist_ok=True) for (dirpath, dirnames, filenames) in",
"images.items(): f = files[0] pngimage = image + '.png' if pngimage not in",
"run from distutils.dir_util import copy_tree from distutils.file_util import copy_file build_dir = 'build' source_dir",
"basename, splitext, join, isfile from collections import defaultdict from subprocess import run from",
"f in filenames: name, ext = splitext(f) if ext == '.scss' and name[0]",
"ext != 'svg']: data = raster_data(join(images_dir, image), ext) css += 'background-image: url(' +",
"+ ';base64,' + data def xml_data(image_filename, ext): with open(image_filename, 'r') as f: data",
"'svg']: data = raster_data(join(images_dir, image), ext) css += 'background-image: url(' + data +",
"= defaultdict(list) for image in images_in_dir(images_dir): name, _ = splitext(basename(image)) images[name] += [image]",
"os.chdir(dest_dir) handler = http.server.SimpleHTTPRequestHandler httpd = TemporaryTCPServer((\"\", port), handler) print(\"[serve] serving on port",
"\" + f + ' ', end='') run([ 'sass', join(css_source_dir, f), join(css_dest_dir, name",
"\");\\n\" for svg, ext in [(f, ext) for f, ext in files_and_extensions if",
"exist_ok=True) for (dirpath, dirnames, filenames) in os.walk(css_source_dir): for f in filenames: name, ext",
"'none', join(images_dir, f), join(images_dir, pngimage) ], check = True) print(\"[ok]\") def images_in_dir(dir): vectors",
"= None if arg == 'build': build() elif arg == 'clean': clean() elif",
"def find_built_images(images_dir): images = defaultdict(list) for image in images_in_dir(images_dir): name, _ = splitext(basename(image))",
"= b64encode(f.read()).decode('utf-8') return 'data:image/' + ext + ';base64,' + data def xml_data(image_filename, ext):",
"open(image_filename, 'rb') as f: data = b64encode(f.read()).decode('utf-8') return 'data:image/' + ext + ';base64,'",
"print('[ok]') def run_sass(css_source_dir, css_dest_dir): os.makedirs(css_dest_dir, exist_ok=True) for (dirpath, dirnames, filenames) in os.walk(css_source_dir): for",
"join(css_source_dir, f), join(css_dest_dir, name + '.css') ], check = True) print(\"[ok]\") elif ext",
"images = defaultdict(list) for image in images_in_dir(images_dir): name, _ = splitext(basename(image)) images[name] +=",
"= files[0] pngimage = image + '.png' if pngimage not in files: print(\"[create]",
"images_dir = join(build_dir, 'images') class TemporaryTCPServer(socketserver.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) def",
"'asis'), join(dest_dir, 'asis'), update=1) print('[ok]') def run_sass(css_source_dir, css_dest_dir): os.makedirs(css_dest_dir, exist_ok=True) for (dirpath, dirnames,",
"images.items(): css = '.image-' + name + \" {\\n\" files_and_extensions = [(f, splitext(f)[1][1:])",
"f: data = quote(f.read()) return 'data:image/' + ext + '+xml;charset=US-ASCII,' + data def",
"[f] if ext in ['.gif']: dumb_rasters += [f] if ext in ['.jpg', '.jpeg']:",
"'__main__': try: arg = sys.argv[1] except IndexError: arg = None if arg ==",
"return 'data:image/' + ext + ';base64,' + data def xml_data(image_filename, ext): with open(image_filename,",
"try: arg = sys.argv[1] except IndexError: arg = None if arg == 'build':",
"ext = splitext(basename(f)) if ext in ['.svg']: vectors += [f] if ext in",
"vectors + rasters + dumb_rasters + lossy def find_built_images(images_dir): images = defaultdict(list) for",
"raster_data(join(images_dir, image), ext) css += 'background-image: url(' + data + \");\\n\" for svg,",
"'css')) print('[update] asis ', end='') copy_tree(join(source_dir, 'asis'), join(dest_dir, 'asis'), update=1) print('[ok]') def run_sass(css_source_dir,",
"def build(): copy_tree(source_dir, build_dir, update=1) make_fallback_images(images_dir) print('[create] _images.scss ', end='') save_images_css(images_dir, join(css_dir, '_images.scss'))",
"break def make_fallback_images(images_dir): images = find_built_images(images_dir) for image, files in images.items(): f =",
"+ data def image_data(image_filename): _, ext = splitext(image_filename) if ext == '.svg': return",
"= join(build_dir, 'css') images_dir = join(build_dir, 'images') class TemporaryTCPServer(socketserver.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,",
"'images') class TemporaryTCPServer(socketserver.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) def serve(port): os.chdir(dest_dir) handler",
"data = quote(f.read()) return 'data:image/' + ext + '+xml;charset=US-ASCII,' + data def image_data(image_filename):",
"print(\"[create] \" + pngimage + ' ', end='') run([ 'convert', '-background', 'none', join(images_dir,",
"[f] break return vectors + rasters + dumb_rasters + lossy def find_built_images(images_dir): images",
"shutil.rmtree(build_dir) shutil.rmtree(dest_dir) def build(): copy_tree(source_dir, build_dir, update=1) make_fallback_images(images_dir) print('[create] _images.scss ', end='') save_images_css(images_dir,",
"in os.walk(css_source_dir): for f in filenames: name, ext = splitext(f) if ext ==",
"make_fallback_images(images_dir) print('[create] _images.scss ', end='') save_images_css(images_dir, join(css_dir, '_images.scss')) print('[ok]') run_sass(css_dir, join(dest_dir, 'css')) print('[update]",
"elif arg == 'serve': try: port = int(sys.argv[2]) except IndexError: port = 8000",
"dumb_rasters += [f] if ext in ['.jpg', '.jpeg']: lossy += [f] break return",
"print(\"[sass] \" + f + ' ', end='') run([ 'sass', join(css_source_dir, f), join(css_dest_dir,",
"css += \"}\\n\" csseses += [css] return \"\\n\".join(csseses) def save_images_css(images_dir, css_file): with open(css_file,",
"join(build_dir, 'css') images_dir = join(build_dir, 'images') class TemporaryTCPServer(socketserver.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)",
"import run from distutils.dir_util import copy_tree from distutils.file_util import copy_file build_dir = 'build'",
"+ data + \");\\n\" for svg, ext in [(f, ext) for f, ext",
"' ', end='') run([ 'convert', '-background', 'none', join(images_dir, f), join(images_dir, pngimage) ], check",
"name, ext = splitext(f) if ext == '.scss' and name[0] != '_': print(\"[sass]",
"ext) for f, ext in files_and_extensions if ext == 'svg']: data = xml_data(join(images_dir,",
"asis ', end='') copy_tree(join(source_dir, 'asis'), join(dest_dir, 'asis'), update=1) print('[ok]') def run_sass(css_source_dir, css_dest_dir): os.makedirs(css_dest_dir,",
"httpd = TemporaryTCPServer((\"\", port), handler) print(\"[serve] serving on port \" + str(port)) httpd.serve_forever()",
"__name__ == '__main__': try: arg = sys.argv[1] except IndexError: arg = None if",
"return 'data:image/' + ext + '+xml;charset=US-ASCII,' + data def image_data(image_filename): _, ext =",
"f + ' ', end='') run([ 'sass', join(css_source_dir, f), join(css_dest_dir, name + '.css')",
"data = raster_data(join(images_dir, image), ext) css += 'background-image: url(' + data + \");\\n\"",
"'background-image: url(' + data + \");\\n\" for svg, ext in [(f, ext) for",
"arg = sys.argv[1] except IndexError: arg = None if arg == 'build': build()",
"ext in ['.gif']: dumb_rasters += [f] if ext in ['.jpg', '.jpeg']: lossy +=",
"'background-image: url(' + data + \"), linear-gradient(transparent, transparent);\\n\" css += \"}\\n\" csseses +=",
"f + ' ', end='') copy_file(join(css_source_dir, f), join(css_dest_dir, f), update=1) print(\"[ok]\") break def",
"None if arg == 'build': build() elif arg == 'clean': clean() elif arg",
"+= \"}\\n\" csseses += [css] return \"\\n\".join(csseses) def save_images_css(images_dir, css_file): with open(css_file, 'w')",
"css_dest_dir): os.makedirs(css_dest_dir, exist_ok=True) for (dirpath, dirnames, filenames) in os.walk(css_source_dir): for f in filenames:",
"as f: f.write(images_to_css(images_dir)) def raster_data(image_filename, ext): with open(image_filename, 'rb') as f: data =",
"IndexError: port = 8000 build() serve(port) else: print('please use \"build\", \"clean\" or \"serve\"",
"xml_data(join(images_dir, svg), ext) css += 'background-image: url(' + data + \"), linear-gradient(transparent, transparent);\\n\"",
"[] for name, files in images.items(): css = '.image-' + name + \"",
"+= [f] if ext in ['.png']: rasters += [f] if ext in ['.gif']:",
"'.css': print(\"[copy] \" + f + ' ', end='') copy_file(join(css_source_dir, f), join(css_dest_dir, f),",
"splitext, join, isfile from collections import defaultdict from subprocess import run from distutils.dir_util",
"[] rasters = [] dumb_rasters = [] lossy = [] for (dirpath, dirnames,",
"for svg, ext in [(f, ext) for f, ext in files_and_extensions if ext",
"filenames) in os.walk(css_source_dir): for f in filenames: name, ext = splitext(f) if ext",
"if ext == '.scss' and name[0] != '_': print(\"[sass] \" + f +",
"files] for image, ext in [(f, ext) for f, ext in files_and_extensions if",
"= [(f, splitext(f)[1][1:]) for f in files] for image, ext in [(f, ext)",
"ext): with open(image_filename, 'r') as f: data = quote(f.read()) return 'data:image/' + ext",
"[css] return \"\\n\".join(csseses) def save_images_css(images_dir, css_file): with open(css_file, 'w') as f: f.write(images_to_css(images_dir)) def",
"', end='') copy_tree(join(source_dir, 'asis'), join(dest_dir, 'asis'), update=1) print('[ok]') def run_sass(css_source_dir, css_dest_dir): os.makedirs(css_dest_dir, exist_ok=True)",
"with open(image_filename, 'r') as f: data = quote(f.read()) return 'data:image/' + ext +",
"= 8000 build() serve(port) else: print('please use \"build\", \"clean\" or \"serve\" as a",
"', end='') run([ 'sass', join(css_source_dir, f), join(css_dest_dir, name + '.css') ], check =",
"image, files in images.items(): f = files[0] pngimage = image + '.png' if",
"= splitext(image_filename) if ext == '.svg': return xml_data(image_filename, ext) else: return raster_data(image_filename, ext)",
"arg == 'build': build() elif arg == 'clean': clean() elif arg == 'serve':",
"in ['.png']: rasters += [f] if ext in ['.gif']: dumb_rasters += [f] if",
"find_built_images(images_dir): images = defaultdict(list) for image in images_in_dir(images_dir): name, _ = splitext(basename(image)) images[name]",
"port = 8000 build() serve(port) else: print('please use \"build\", \"clean\" or \"serve\" as",
"+ \");\\n\" for svg, ext in [(f, ext) for f, ext in files_and_extensions",
"== 'clean': clean() elif arg == 'serve': try: port = int(sys.argv[2]) except IndexError:",
"from os.path import basename, splitext, join, isfile from collections import defaultdict from subprocess",
"= int(sys.argv[2]) except IndexError: port = 8000 build() serve(port) else: print('please use \"build\",",
"+ lossy def find_built_images(images_dir): images = defaultdict(list) for image in images_in_dir(images_dir): name, _",
"return raster_data(image_filename, ext) if __name__ == '__main__': try: arg = sys.argv[1] except IndexError:",
"quote from os.path import basename, splitext, join, isfile from collections import defaultdict from",
"[] lossy = [] for (dirpath, dirnames, filenames) in os.walk(dir): for f in",
"end='') copy_tree(join(source_dir, 'asis'), join(dest_dir, 'asis'), update=1) print('[ok]') def run_sass(css_source_dir, css_dest_dir): os.makedirs(css_dest_dir, exist_ok=True) for",
"update=1) print('[ok]') def run_sass(css_source_dir, css_dest_dir): os.makedirs(css_dest_dir, exist_ok=True) for (dirpath, dirnames, filenames) in os.walk(css_source_dir):",
"for f in files] for image, ext in [(f, ext) for f, ext",
"css = '.image-' + name + \" {\\n\" files_and_extensions = [(f, splitext(f)[1][1:]) for",
"rasters = [] dumb_rasters = [] lossy = [] for (dirpath, dirnames, filenames)",
"def save_images_css(images_dir, css_file): with open(css_file, 'w') as f: f.write(images_to_css(images_dir)) def raster_data(image_filename, ext): with",
"run_sass(css_source_dir, css_dest_dir): os.makedirs(css_dest_dir, exist_ok=True) for (dirpath, dirnames, filenames) in os.walk(css_source_dir): for f in",
"import socket import shutil from base64 import b64encode from urllib.parse import quote from",
"else: return raster_data(image_filename, ext) if __name__ == '__main__': try: arg = sys.argv[1] except",
"in filenames: name, ext = splitext(f) if ext == '.scss' and name[0] !=",
"http.server import socketserver import socket import shutil from base64 import b64encode from urllib.parse",
"join(css_dest_dir, f), update=1) print(\"[ok]\") break def make_fallback_images(images_dir): images = find_built_images(images_dir) for image, files",
"name[0] != '_': print(\"[sass] \" + f + ' ', end='') run([ 'sass',",
"pngimage = image + '.png' if pngimage not in files: print(\"[create] \" +",
"from subprocess import run from distutils.dir_util import copy_tree from distutils.file_util import copy_file build_dir",
"f), join(images_dir, pngimage) ], check = True) print(\"[ok]\") def images_in_dir(dir): vectors = []",
"serving on port \" + str(port)) httpd.serve_forever() def clean(): shutil.rmtree(build_dir) shutil.rmtree(dest_dir) def build():",
"from base64 import b64encode from urllib.parse import quote from os.path import basename, splitext,",
"== '.scss' and name[0] != '_': print(\"[sass] \" + f + ' ',",
"'.scss' and name[0] != '_': print(\"[sass] \" + f + ' ', end='')",
"[f] if ext in ['.png']: rasters += [f] if ext in ['.gif']: dumb_rasters",
"+ name + \" {\\n\" files_and_extensions = [(f, splitext(f)[1][1:]) for f in files]",
"+ ext + ';base64,' + data def xml_data(image_filename, ext): with open(image_filename, 'r') as",
"splitext(f) if ext == '.scss' and name[0] != '_': print(\"[sass] \" + f",
"if ext in ['.png']: rasters += [f] if ext in ['.gif']: dumb_rasters +=",
"ext) css += 'background-image: url(' + data + \");\\n\" for svg, ext in",
"name, _ = splitext(basename(image)) images[name] += [image] return dict(images) def images_to_css(images_dir): images =",
"in ['.gif']: dumb_rasters += [f] if ext in ['.jpg', '.jpeg']: lossy += [f]",
"port), handler) print(\"[serve] serving on port \" + str(port)) httpd.serve_forever() def clean(): shutil.rmtree(build_dir)",
"run([ 'convert', '-background', 'none', join(images_dir, f), join(images_dir, pngimage) ], check = True) print(\"[ok]\")",
"== 'serve': try: port = int(sys.argv[2]) except IndexError: port = 8000 build() serve(port)",
"build() serve(port) else: print('please use \"build\", \"clean\" or \"serve\" as a first argument.')",
"return xml_data(image_filename, ext) else: return raster_data(image_filename, ext) if __name__ == '__main__': try: arg",
"def raster_data(image_filename, ext): with open(image_filename, 'rb') as f: data = b64encode(f.read()).decode('utf-8') return 'data:image/'",
"= 'source' dest_dir = 'built_static' css_dir = join(build_dir, 'css') images_dir = join(build_dir, 'images')",
"for (dirpath, dirnames, filenames) in os.walk(css_source_dir): for f in filenames: name, ext =",
"end='') copy_file(join(css_source_dir, f), join(css_dest_dir, f), update=1) print(\"[ok]\") break def make_fallback_images(images_dir): images = find_built_images(images_dir)",
"elif ext == '.css': print(\"[copy] \" + f + ' ', end='') copy_file(join(css_source_dir,",
"'serve': try: port = int(sys.argv[2]) except IndexError: port = 8000 build() serve(port) else:",
"css_dir = join(build_dir, 'css') images_dir = join(build_dir, 'images') class TemporaryTCPServer(socketserver.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET,",
"in files_and_extensions if ext == 'svg']: data = xml_data(join(images_dir, svg), ext) css +=",
"filenames: name, ext = splitext(f) if ext == '.scss' and name[0] != '_':",
"+ ' ', end='') run([ 'sass', join(css_source_dir, f), join(css_dest_dir, name + '.css') ],",
"join(build_dir, 'images') class TemporaryTCPServer(socketserver.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) def serve(port): os.chdir(dest_dir)",
"\"}\\n\" csseses += [css] return \"\\n\".join(csseses) def save_images_css(images_dir, css_file): with open(css_file, 'w') as",
"as f: data = quote(f.read()) return 'data:image/' + ext + '+xml;charset=US-ASCII,' + data",
"run([ 'sass', join(css_source_dir, f), join(css_dest_dir, name + '.css') ], check = True) print(\"[ok]\")",
"for name, files in images.items(): css = '.image-' + name + \" {\\n\"",
"arg == 'clean': clean() elif arg == 'serve': try: port = int(sys.argv[2]) except",
"os.makedirs(css_dest_dir, exist_ok=True) for (dirpath, dirnames, filenames) in os.walk(css_source_dir): for f in filenames: name,",
"'sass', join(css_source_dir, f), join(css_dest_dir, name + '.css') ], check = True) print(\"[ok]\") elif",
"run_sass(css_dir, join(dest_dir, 'css')) print('[update] asis ', end='') copy_tree(join(source_dir, 'asis'), join(dest_dir, 'asis'), update=1) print('[ok]')",
"urllib.parse import quote from os.path import basename, splitext, join, isfile from collections import",
"files_and_extensions if ext != 'svg']: data = raster_data(join(images_dir, image), ext) css += 'background-image:",
"== '.svg': return xml_data(image_filename, ext) else: return raster_data(image_filename, ext) if __name__ == '__main__':",
"from collections import defaultdict from subprocess import run from distutils.dir_util import copy_tree from",
"update=1) make_fallback_images(images_dir) print('[create] _images.scss ', end='') save_images_css(images_dir, join(css_dir, '_images.scss')) print('[ok]') run_sass(css_dir, join(dest_dir, 'css'))",
"', end='') copy_file(join(css_source_dir, f), join(css_dest_dir, f), update=1) print(\"[ok]\") break def make_fallback_images(images_dir): images =",
"images_to_css(images_dir): images = find_built_images(images_dir) csseses = [] for name, files in images.items(): css",
"def serve(port): os.chdir(dest_dir) handler = http.server.SimpleHTTPRequestHandler httpd = TemporaryTCPServer((\"\", port), handler) print(\"[serve] serving",
"+ str(port)) httpd.serve_forever() def clean(): shutil.rmtree(build_dir) shutil.rmtree(dest_dir) def build(): copy_tree(source_dir, build_dir, update=1) make_fallback_images(images_dir)",
"class TemporaryTCPServer(socketserver.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) def serve(port): os.chdir(dest_dir) handler =",
"except IndexError: port = 8000 build() serve(port) else: print('please use \"build\", \"clean\" or",
"csseses = [] for name, files in images.items(): css = '.image-' + name",
"in os.walk(dir): for f in filenames: name, ext = splitext(basename(f)) if ext in",
"= splitext(basename(f)) if ext in ['.svg']: vectors += [f] if ext in ['.png']:",
"in [(f, ext) for f, ext in files_and_extensions if ext != 'svg']: data",
"in files: print(\"[create] \" + pngimage + ' ', end='') run([ 'convert', '-background',",
"+ data + \"), linear-gradient(transparent, transparent);\\n\" css += \"}\\n\" csseses += [css] return",
"IndexError: arg = None if arg == 'build': build() elif arg == 'clean':",
"import os import sys import http.server import socketserver import socket import shutil from",
"ext == 'svg']: data = xml_data(join(images_dir, svg), ext) css += 'background-image: url(' +",
"ext): with open(image_filename, 'rb') as f: data = b64encode(f.read()).decode('utf-8') return 'data:image/' + ext",
"build() elif arg == 'clean': clean() elif arg == 'serve': try: port =",
"handler) print(\"[serve] serving on port \" + str(port)) httpd.serve_forever() def clean(): shutil.rmtree(build_dir) shutil.rmtree(dest_dir)",
"= sys.argv[1] except IndexError: arg = None if arg == 'build': build() elif",
"str(port)) httpd.serve_forever() def clean(): shutil.rmtree(build_dir) shutil.rmtree(dest_dir) def build(): copy_tree(source_dir, build_dir, update=1) make_fallback_images(images_dir) print('[create]",
"shutil from base64 import b64encode from urllib.parse import quote from os.path import basename,",
"True) print(\"[ok]\") elif ext == '.css': print(\"[copy] \" + f + ' ',",
"join(dest_dir, 'css')) print('[update] asis ', end='') copy_tree(join(source_dir, 'asis'), join(dest_dir, 'asis'), update=1) print('[ok]') def",
"build_dir = 'build' source_dir = 'source' dest_dir = 'built_static' css_dir = join(build_dir, 'css')",
"pngimage + ' ', end='') run([ 'convert', '-background', 'none', join(images_dir, f), join(images_dir, pngimage)",
"arg == 'serve': try: port = int(sys.argv[2]) except IndexError: port = 8000 build()",
"return \"\\n\".join(csseses) def save_images_css(images_dir, css_file): with open(css_file, 'w') as f: f.write(images_to_css(images_dir)) def raster_data(image_filename,",
"[] for (dirpath, dirnames, filenames) in os.walk(dir): for f in filenames: name, ext",
"css += 'background-image: url(' + data + \");\\n\" for svg, ext in [(f,",
"' ', end='') run([ 'sass', join(css_source_dir, f), join(css_dest_dir, name + '.css') ], check",
"= [] lossy = [] for (dirpath, dirnames, filenames) in os.walk(dir): for f",
"in filenames: name, ext = splitext(basename(f)) if ext in ['.svg']: vectors += [f]",
"isfile from collections import defaultdict from subprocess import run from distutils.dir_util import copy_tree",
"!= '_': print(\"[sass] \" + f + ' ', end='') run([ 'sass', join(css_source_dir,",
"== '__main__': try: arg = sys.argv[1] except IndexError: arg = None if arg",
"copy_file build_dir = 'build' source_dir = 'source' dest_dir = 'built_static' css_dir = join(build_dir,",
"os.path import basename, splitext, join, isfile from collections import defaultdict from subprocess import",
"in [(f, ext) for f, ext in files_and_extensions if ext == 'svg']: data",
"ext == '.scss' and name[0] != '_': print(\"[sass] \" + f + '",
"images[name] += [image] return dict(images) def images_to_css(images_dir): images = find_built_images(images_dir) csseses = []",
"'+xml;charset=US-ASCII,' + data def image_data(image_filename): _, ext = splitext(image_filename) if ext == '.svg':",
"end='') run([ 'convert', '-background', 'none', join(images_dir, f), join(images_dir, pngimage) ], check = True)",
"print(\"[ok]\") def images_in_dir(dir): vectors = [] rasters = [] dumb_rasters = [] lossy",
"import b64encode from urllib.parse import quote from os.path import basename, splitext, join, isfile",
"join(dest_dir, 'asis'), update=1) print('[ok]') def run_sass(css_source_dir, css_dest_dir): os.makedirs(css_dest_dir, exist_ok=True) for (dirpath, dirnames, filenames)",
"end='') save_images_css(images_dir, join(css_dir, '_images.scss')) print('[ok]') run_sass(css_dir, join(dest_dir, 'css')) print('[update] asis ', end='') copy_tree(join(source_dir,",
"'.jpeg']: lossy += [f] break return vectors + rasters + dumb_rasters + lossy",
"def make_fallback_images(images_dir): images = find_built_images(images_dir) for image, files in images.items(): f = files[0]",
"in ['.jpg', '.jpeg']: lossy += [f] break return vectors + rasters + dumb_rasters",
"images = find_built_images(images_dir) for image, files in images.items(): f = files[0] pngimage =",
"(dirpath, dirnames, filenames) in os.walk(dir): for f in filenames: name, ext = splitext(basename(f))",
"save_images_css(images_dir, css_file): with open(css_file, 'w') as f: f.write(images_to_css(images_dir)) def raster_data(image_filename, ext): with open(image_filename,",
"socketserver import socket import shutil from base64 import b64encode from urllib.parse import quote",
"update=1) print(\"[ok]\") break def make_fallback_images(images_dir): images = find_built_images(images_dir) for image, files in images.items():",
"'data:image/' + ext + ';base64,' + data def xml_data(image_filename, ext): with open(image_filename, 'r')",
"files[0] pngimage = image + '.png' if pngimage not in files: print(\"[create] \"",
"'built_static' css_dir = join(build_dir, 'css') images_dir = join(build_dir, 'images') class TemporaryTCPServer(socketserver.TCPServer): def server_bind(self):",
"= find_built_images(images_dir) for image, files in images.items(): f = files[0] pngimage = image",
"f: f.write(images_to_css(images_dir)) def raster_data(image_filename, ext): with open(image_filename, 'rb') as f: data = b64encode(f.read()).decode('utf-8')",
"+ '+xml;charset=US-ASCII,' + data def image_data(image_filename): _, ext = splitext(image_filename) if ext ==",
"raster_data(image_filename, ext): with open(image_filename, 'rb') as f: data = b64encode(f.read()).decode('utf-8') return 'data:image/' +",
"f), update=1) print(\"[ok]\") break def make_fallback_images(images_dir): images = find_built_images(images_dir) for image, files in",
"from urllib.parse import quote from os.path import basename, splitext, join, isfile from collections",
"end='') run([ 'sass', join(css_source_dir, f), join(css_dest_dir, name + '.css') ], check = True)",
"for image, files in images.items(): f = files[0] pngimage = image + '.png'",
"+ rasters + dumb_rasters + lossy def find_built_images(images_dir): images = defaultdict(list) for image",
"css += 'background-image: url(' + data + \"), linear-gradient(transparent, transparent);\\n\" css += \"}\\n\"",
"distutils.dir_util import copy_tree from distutils.file_util import copy_file build_dir = 'build' source_dir = 'source'",
"= quote(f.read()) return 'data:image/' + ext + '+xml;charset=US-ASCII,' + data def image_data(image_filename): _,",
"== 'svg']: data = xml_data(join(images_dir, svg), ext) css += 'background-image: url(' + data",
"'convert', '-background', 'none', join(images_dir, f), join(images_dir, pngimage) ], check = True) print(\"[ok]\") def",
"', end='') save_images_css(images_dir, join(css_dir, '_images.scss')) print('[ok]') run_sass(css_dir, join(dest_dir, 'css')) print('[update] asis ', end='')",
"and name[0] != '_': print(\"[sass] \" + f + ' ', end='') run([",
"if ext == 'svg']: data = xml_data(join(images_dir, svg), ext) css += 'background-image: url('",
"files in images.items(): f = files[0] pngimage = image + '.png' if pngimage",
"name, files in images.items(): css = '.image-' + name + \" {\\n\" files_and_extensions",
"print(\"[ok]\") elif ext == '.css': print(\"[copy] \" + f + ' ', end='')",
"os.walk(dir): for f in filenames: name, ext = splitext(basename(f)) if ext in ['.svg']:",
"def images_to_css(images_dir): images = find_built_images(images_dir) csseses = [] for name, files in images.items():",
"if ext in ['.svg']: vectors += [f] if ext in ['.png']: rasters +=",
"= 'built_static' css_dir = join(build_dir, 'css') images_dir = join(build_dir, 'images') class TemporaryTCPServer(socketserver.TCPServer): def",
"url(' + data + \"), linear-gradient(transparent, transparent);\\n\" css += \"}\\n\" csseses += [css]",
"image, ext in [(f, ext) for f, ext in files_and_extensions if ext !=",
"build_dir, update=1) make_fallback_images(images_dir) print('[create] _images.scss ', end='') save_images_css(images_dir, join(css_dir, '_images.scss')) print('[ok]') run_sass(css_dir, join(dest_dir,",
"= image + '.png' if pngimage not in files: print(\"[create] \" + pngimage",
"import socketserver import socket import shutil from base64 import b64encode from urllib.parse import",
"httpd.serve_forever() def clean(): shutil.rmtree(build_dir) shutil.rmtree(dest_dir) def build(): copy_tree(source_dir, build_dir, update=1) make_fallback_images(images_dir) print('[create] _images.scss",
"True) print(\"[ok]\") def images_in_dir(dir): vectors = [] rasters = [] dumb_rasters = []",
"+= [image] return dict(images) def images_to_css(images_dir): images = find_built_images(images_dir) csseses = [] for",
"= [] for (dirpath, dirnames, filenames) in os.walk(dir): for f in filenames: name,",
"filenames) in os.walk(dir): for f in filenames: name, ext = splitext(basename(f)) if ext",
"'_images.scss')) print('[ok]') run_sass(css_dir, join(dest_dir, 'css')) print('[update] asis ', end='') copy_tree(join(source_dir, 'asis'), join(dest_dir, 'asis'),",
"'.css') ], check = True) print(\"[ok]\") elif ext == '.css': print(\"[copy] \" +",
"defaultdict(list) for image in images_in_dir(images_dir): name, _ = splitext(basename(image)) images[name] += [image] return",
"if pngimage not in files: print(\"[create] \" + pngimage + ' ', end='')",
"shutil.rmtree(dest_dir) def build(): copy_tree(source_dir, build_dir, update=1) make_fallback_images(images_dir) print('[create] _images.scss ', end='') save_images_css(images_dir, join(css_dir,",
"find_built_images(images_dir) csseses = [] for name, files in images.items(): css = '.image-' +",
"'svg']: data = xml_data(join(images_dir, svg), ext) css += 'background-image: url(' + data +",
"['.svg']: vectors += [f] if ext in ['.png']: rasters += [f] if ext",
"xml_data(image_filename, ext) else: return raster_data(image_filename, ext) if __name__ == '__main__': try: arg =",
"['.jpg', '.jpeg']: lossy += [f] break return vectors + rasters + dumb_rasters +",
"print(\"[ok]\") break def make_fallback_images(images_dir): images = find_built_images(images_dir) for image, files in images.items(): f",
"ext in ['.jpg', '.jpeg']: lossy += [f] break return vectors + rasters +",
"linear-gradient(transparent, transparent);\\n\" css += \"}\\n\" csseses += [css] return \"\\n\".join(csseses) def save_images_css(images_dir, css_file):",
"= True) print(\"[ok]\") def images_in_dir(dir): vectors = [] rasters = [] dumb_rasters =",
"name + \" {\\n\" files_and_extensions = [(f, splitext(f)[1][1:]) for f in files] for",
"print('[ok]') run_sass(css_dir, join(dest_dir, 'css')) print('[update] asis ', end='') copy_tree(join(source_dir, 'asis'), join(dest_dir, 'asis'), update=1)",
"' ', end='') copy_file(join(css_source_dir, f), join(css_dest_dir, f), update=1) print(\"[ok]\") break def make_fallback_images(images_dir): images",
"int(sys.argv[2]) except IndexError: port = 8000 build() serve(port) else: print('please use \"build\", \"clean\"",
"save_images_css(images_dir, join(css_dir, '_images.scss')) print('[ok]') run_sass(css_dir, join(dest_dir, 'css')) print('[update] asis ', end='') copy_tree(join(source_dir, 'asis'),",
"[(f, splitext(f)[1][1:]) for f in files] for image, ext in [(f, ext) for",
"';base64,' + data def xml_data(image_filename, ext): with open(image_filename, 'r') as f: data =",
"f: data = b64encode(f.read()).decode('utf-8') return 'data:image/' + ext + ';base64,' + data def",
"ext) else: return raster_data(image_filename, ext) if __name__ == '__main__': try: arg = sys.argv[1]",
"= join(build_dir, 'images') class TemporaryTCPServer(socketserver.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) def serve(port):",
"[(f, ext) for f, ext in files_and_extensions if ext == 'svg']: data =",
"dirnames, filenames) in os.walk(css_source_dir): for f in filenames: name, ext = splitext(f) if",
"for image, ext in [(f, ext) for f, ext in files_and_extensions if ext",
"+= [f] if ext in ['.jpg', '.jpeg']: lossy += [f] break return vectors",
"lossy def find_built_images(images_dir): images = defaultdict(list) for image in images_in_dir(images_dir): name, _ =",
"import shutil from base64 import b64encode from urllib.parse import quote from os.path import",
"+ pngimage + ' ', end='') run([ 'convert', '-background', 'none', join(images_dir, f), join(images_dir,",
"from distutils.dir_util import copy_tree from distutils.file_util import copy_file build_dir = 'build' source_dir =",
"self.socket.bind(self.server_address) def serve(port): os.chdir(dest_dir) handler = http.server.SimpleHTTPRequestHandler httpd = TemporaryTCPServer((\"\", port), handler) print(\"[serve]",
"\" + str(port)) httpd.serve_forever() def clean(): shutil.rmtree(build_dir) shutil.rmtree(dest_dir) def build(): copy_tree(source_dir, build_dir, update=1)",
"ext = splitext(f) if ext == '.scss' and name[0] != '_': print(\"[sass] \"",
"'-background', 'none', join(images_dir, f), join(images_dir, pngimage) ], check = True) print(\"[ok]\") def images_in_dir(dir):",
"'.image-' + name + \" {\\n\" files_and_extensions = [(f, splitext(f)[1][1:]) for f in",
"subprocess import run from distutils.dir_util import copy_tree from distutils.file_util import copy_file build_dir =",
"transparent);\\n\" css += \"}\\n\" csseses += [css] return \"\\n\".join(csseses) def save_images_css(images_dir, css_file): with",
"+ '.css') ], check = True) print(\"[ok]\") elif ext == '.css': print(\"[copy] \"",
"images_in_dir(dir): vectors = [] rasters = [] dumb_rasters = [] lossy = []",
"[(f, ext) for f, ext in files_and_extensions if ext != 'svg']: data =",
"= xml_data(join(images_dir, svg), ext) css += 'background-image: url(' + data + \"), linear-gradient(transparent,",
"import http.server import socketserver import socket import shutil from base64 import b64encode from",
"+ f + ' ', end='') copy_file(join(css_source_dir, f), join(css_dest_dir, f), update=1) print(\"[ok]\") break",
"for f in filenames: name, ext = splitext(f) if ext == '.scss' and",
"'source' dest_dir = 'built_static' css_dir = join(build_dir, 'css') images_dir = join(build_dir, 'images') class",
"in images.items(): f = files[0] pngimage = image + '.png' if pngimage not",
"join, isfile from collections import defaultdict from subprocess import run from distutils.dir_util import",
"+= [f] break return vectors + rasters + dumb_rasters + lossy def find_built_images(images_dir):",
"= http.server.SimpleHTTPRequestHandler httpd = TemporaryTCPServer((\"\", port), handler) print(\"[serve] serving on port \" +",
"quote(f.read()) return 'data:image/' + ext + '+xml;charset=US-ASCII,' + data def image_data(image_filename): _, ext",
"ext in files_and_extensions if ext == 'svg']: data = xml_data(join(images_dir, svg), ext) css",
"as f: data = b64encode(f.read()).decode('utf-8') return 'data:image/' + ext + ';base64,' + data",
"splitext(image_filename) if ext == '.svg': return xml_data(image_filename, ext) else: return raster_data(image_filename, ext) if",
"server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) def serve(port): os.chdir(dest_dir) handler = http.server.SimpleHTTPRequestHandler httpd =",
"+= [f] if ext in ['.gif']: dumb_rasters += [f] if ext in ['.jpg',",
"return dict(images) def images_to_css(images_dir): images = find_built_images(images_dir) csseses = [] for name, files",
"if ext in ['.jpg', '.jpeg']: lossy += [f] break return vectors + rasters",
"not in files: print(\"[create] \" + pngimage + ' ', end='') run([ 'convert',",
"data def image_data(image_filename): _, ext = splitext(image_filename) if ext == '.svg': return xml_data(image_filename,",
"socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) def serve(port): os.chdir(dest_dir) handler = http.server.SimpleHTTPRequestHandler httpd = TemporaryTCPServer((\"\", port),",
"except IndexError: arg = None if arg == 'build': build() elif arg ==",
"def images_in_dir(dir): vectors = [] rasters = [] dumb_rasters = [] lossy =",
"files_and_extensions = [(f, splitext(f)[1][1:]) for f in files] for image, ext in [(f,",
"return vectors + rasters + dumb_rasters + lossy def find_built_images(images_dir): images = defaultdict(list)",
"collections import defaultdict from subprocess import run from distutils.dir_util import copy_tree from distutils.file_util",
"image + '.png' if pngimage not in files: print(\"[create] \" + pngimage +",
"TemporaryTCPServer(socketserver.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) def serve(port): os.chdir(dest_dir) handler = http.server.SimpleHTTPRequestHandler",
"in images.items(): css = '.image-' + name + \" {\\n\" files_and_extensions = [(f,",
"xml_data(image_filename, ext): with open(image_filename, 'r') as f: data = quote(f.read()) return 'data:image/' +",
"b64encode(f.read()).decode('utf-8') return 'data:image/' + ext + ';base64,' + data def xml_data(image_filename, ext): with",
"csseses += [css] return \"\\n\".join(csseses) def save_images_css(images_dir, css_file): with open(css_file, 'w') as f:",
"on port \" + str(port)) httpd.serve_forever() def clean(): shutil.rmtree(build_dir) shutil.rmtree(dest_dir) def build(): copy_tree(source_dir,",
"socket import shutil from base64 import b64encode from urllib.parse import quote from os.path",
"copy_tree from distutils.file_util import copy_file build_dir = 'build' source_dir = 'source' dest_dir =",
"import copy_tree from distutils.file_util import copy_file build_dir = 'build' source_dir = 'source' dest_dir",
"raster_data(image_filename, ext) if __name__ == '__main__': try: arg = sys.argv[1] except IndexError: arg",
"arg = None if arg == 'build': build() elif arg == 'clean': clean()",
"lossy += [f] break return vectors + rasters + dumb_rasters + lossy def",
"ext in [(f, ext) for f, ext in files_and_extensions if ext == 'svg']:",
"lossy = [] for (dirpath, dirnames, filenames) in os.walk(dir): for f in filenames:",
"'rb') as f: data = b64encode(f.read()).decode('utf-8') return 'data:image/' + ext + ';base64,' +",
"f, ext in files_and_extensions if ext != 'svg']: data = raster_data(join(images_dir, image), ext)",
"join(images_dir, f), join(images_dir, pngimage) ], check = True) print(\"[ok]\") def images_in_dir(dir): vectors =",
"print('[create] _images.scss ', end='') save_images_css(images_dir, join(css_dir, '_images.scss')) print('[ok]') run_sass(css_dir, join(dest_dir, 'css')) print('[update] asis",
"= TemporaryTCPServer((\"\", port), handler) print(\"[serve] serving on port \" + str(port)) httpd.serve_forever() def",
"port = int(sys.argv[2]) except IndexError: port = 8000 build() serve(port) else: print('please use",
"rasters + dumb_rasters + lossy def find_built_images(images_dir): images = defaultdict(list) for image in",
"for f in filenames: name, ext = splitext(basename(f)) if ext in ['.svg']: vectors",
"'w') as f: f.write(images_to_css(images_dir)) def raster_data(image_filename, ext): with open(image_filename, 'rb') as f: data",
"'data:image/' + ext + '+xml;charset=US-ASCII,' + data def image_data(image_filename): _, ext = splitext(image_filename)",
"ext) if __name__ == '__main__': try: arg = sys.argv[1] except IndexError: arg =",
"f in filenames: name, ext = splitext(basename(f)) if ext in ['.svg']: vectors +=",
"+ data def xml_data(image_filename, ext): with open(image_filename, 'r') as f: data = quote(f.read())",
"+= [css] return \"\\n\".join(csseses) def save_images_css(images_dir, css_file): with open(css_file, 'w') as f: f.write(images_to_css(images_dir))",
"import quote from os.path import basename, splitext, join, isfile from collections import defaultdict",
"self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) def serve(port): os.chdir(dest_dir) handler = http.server.SimpleHTTPRequestHandler httpd = TemporaryTCPServer((\"\",",
"image), ext) css += 'background-image: url(' + data + \");\\n\" for svg, ext",
"['.gif']: dumb_rasters += [f] if ext in ['.jpg', '.jpeg']: lossy += [f] break",
"import defaultdict from subprocess import run from distutils.dir_util import copy_tree from distutils.file_util import",
"print(\"[copy] \" + f + ' ', end='') copy_file(join(css_source_dir, f), join(css_dest_dir, f), update=1)",
"for image in images_in_dir(images_dir): name, _ = splitext(basename(image)) images[name] += [image] return dict(images)",
"break return vectors + rasters + dumb_rasters + lossy def find_built_images(images_dir): images =",
"for f, ext in files_and_extensions if ext != 'svg']: data = raster_data(join(images_dir, image),",
"def xml_data(image_filename, ext): with open(image_filename, 'r') as f: data = quote(f.read()) return 'data:image/'",
"splitext(basename(image)) images[name] += [image] return dict(images) def images_to_css(images_dir): images = find_built_images(images_dir) csseses =",
"name + '.css') ], check = True) print(\"[ok]\") elif ext == '.css': print(\"[copy]",
"TemporaryTCPServer((\"\", port), handler) print(\"[serve] serving on port \" + str(port)) httpd.serve_forever() def clean():",
"distutils.file_util import copy_file build_dir = 'build' source_dir = 'source' dest_dir = 'built_static' css_dir",
"'.png' if pngimage not in files: print(\"[create] \" + pngimage + ' ',",
"= 'build' source_dir = 'source' dest_dir = 'built_static' css_dir = join(build_dir, 'css') images_dir",
"images = find_built_images(images_dir) csseses = [] for name, files in images.items(): css =",
"ext + ';base64,' + data def xml_data(image_filename, ext): with open(image_filename, 'r') as f:",
"], check = True) print(\"[ok]\") def images_in_dir(dir): vectors = [] rasters = []",
"_images.scss ', end='') save_images_css(images_dir, join(css_dir, '_images.scss')) print('[ok]') run_sass(css_dir, join(dest_dir, 'css')) print('[update] asis ',",
"data + \"), linear-gradient(transparent, transparent);\\n\" css += \"}\\n\" csseses += [css] return \"\\n\".join(csseses)",
"files in images.items(): css = '.image-' + name + \" {\\n\" files_and_extensions =",
"], check = True) print(\"[ok]\") elif ext == '.css': print(\"[copy] \" + f",
"dict(images) def images_to_css(images_dir): images = find_built_images(images_dir) csseses = [] for name, files in",
"'build' source_dir = 'source' dest_dir = 'built_static' css_dir = join(build_dir, 'css') images_dir =",
"sys.argv[1] except IndexError: arg = None if arg == 'build': build() elif arg",
"'css') images_dir = join(build_dir, 'images') class TemporaryTCPServer(socketserver.TCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address)",
"\" + f + ' ', end='') copy_file(join(css_source_dir, f), join(css_dest_dir, f), update=1) print(\"[ok]\")",
"= splitext(basename(image)) images[name] += [image] return dict(images) def images_to_css(images_dir): images = find_built_images(images_dir) csseses",
"find_built_images(images_dir) for image, files in images.items(): f = files[0] pngimage = image +",
"os import sys import http.server import socketserver import socket import shutil from base64",
"ext) for f, ext in files_and_extensions if ext != 'svg']: data = raster_data(join(images_dir,",
"+ '.png' if pngimage not in files: print(\"[create] \" + pngimage + '",
"= [] for name, files in images.items(): css = '.image-' + name +",
"vectors += [f] if ext in ['.png']: rasters += [f] if ext in",
"dirnames, filenames) in os.walk(dir): for f in filenames: name, ext = splitext(basename(f)) if",
"in images_in_dir(images_dir): name, _ = splitext(basename(image)) images[name] += [image] return dict(images) def images_to_css(images_dir):",
"+ ' ', end='') copy_file(join(css_source_dir, f), join(css_dest_dir, f), update=1) print(\"[ok]\") break def make_fallback_images(images_dir):",
"ext) css += 'background-image: url(' + data + \"), linear-gradient(transparent, transparent);\\n\" css +=",
"vectors = [] rasters = [] dumb_rasters = [] lossy = [] for",
"ext in [(f, ext) for f, ext in files_and_extensions if ext != 'svg']:",
"print('[update] asis ', end='') copy_tree(join(source_dir, 'asis'), join(dest_dir, 'asis'), update=1) print('[ok]') def run_sass(css_source_dir, css_dest_dir):",
"defaultdict from subprocess import run from distutils.dir_util import copy_tree from distutils.file_util import copy_file",
"copy_tree(join(source_dir, 'asis'), join(dest_dir, 'asis'), update=1) print('[ok]') def run_sass(css_source_dir, css_dest_dir): os.makedirs(css_dest_dir, exist_ok=True) for (dirpath,",
"elif arg == 'clean': clean() elif arg == 'serve': try: port = int(sys.argv[2])",
"'.svg': return xml_data(image_filename, ext) else: return raster_data(image_filename, ext) if __name__ == '__main__': try:",
"ext in ['.png']: rasters += [f] if ext in ['.gif']: dumb_rasters += [f]",
"try: port = int(sys.argv[2]) except IndexError: port = 8000 build() serve(port) else: print('please",
"url(' + data + \");\\n\" for svg, ext in [(f, ext) for f,",
"#!/usr/bin/python3 import os import sys import http.server import socketserver import socket import shutil",
"os.walk(css_source_dir): for f in filenames: name, ext = splitext(f) if ext == '.scss'",
"!= 'svg']: data = raster_data(join(images_dir, image), ext) css += 'background-image: url(' + data",
"[] dumb_rasters = [] lossy = [] for (dirpath, dirnames, filenames) in os.walk(dir):",
"image_data(image_filename): _, ext = splitext(image_filename) if ext == '.svg': return xml_data(image_filename, ext) else:",
"for f, ext in files_and_extensions if ext == 'svg']: data = xml_data(join(images_dir, svg),",
"build(): copy_tree(source_dir, build_dir, update=1) make_fallback_images(images_dir) print('[create] _images.scss ', end='') save_images_css(images_dir, join(css_dir, '_images.scss')) print('[ok]')",
"['.png']: rasters += [f] if ext in ['.gif']: dumb_rasters += [f] if ext",
"in ['.svg']: vectors += [f] if ext in ['.png']: rasters += [f] if",
"def run_sass(css_source_dir, css_dest_dir): os.makedirs(css_dest_dir, exist_ok=True) for (dirpath, dirnames, filenames) in os.walk(css_source_dir): for f"
] |
[
"== \"__main__\": with open(sys.argv[1],'r',encoding = 'utf8') as f: # indicates that the second",
"how to use it $ python readFile.py data.txt Show content of data.txt \"\"\"",
"\"\"\" import sys if __name__ == \"__main__\": with open(sys.argv[1],'r',encoding = 'utf8') as f:",
"f: # indicates that the second argument in terminal is to be used",
"-*- coding: utf-8 -*- \"\"\" Doc: show how to use it $ python",
"data.txt Show content of data.txt \"\"\" import sys if __name__ == \"__main__\": with",
"second argument in terminal is to be used for line in f: print(line[:-1])",
"that the second argument in terminal is to be used for line in",
"to use it $ python readFile.py data.txt Show content of data.txt \"\"\" import",
"python readFile.py data.txt Show content of data.txt \"\"\" import sys if __name__ ==",
"Show content of data.txt \"\"\" import sys if __name__ == \"__main__\": with open(sys.argv[1],'r',encoding",
"Doc: show how to use it $ python readFile.py data.txt Show content of",
"# -*- coding: utf-8 -*- \"\"\" Doc: show how to use it $",
"of data.txt \"\"\" import sys if __name__ == \"__main__\": with open(sys.argv[1],'r',encoding = 'utf8')",
"if __name__ == \"__main__\": with open(sys.argv[1],'r',encoding = 'utf8') as f: # indicates that",
"content of data.txt \"\"\" import sys if __name__ == \"__main__\": with open(sys.argv[1],'r',encoding =",
"\"__main__\": with open(sys.argv[1],'r',encoding = 'utf8') as f: # indicates that the second argument",
"as f: # indicates that the second argument in terminal is to be",
"-*- \"\"\" Doc: show how to use it $ python readFile.py data.txt Show",
"show how to use it $ python readFile.py data.txt Show content of data.txt",
"$ python readFile.py data.txt Show content of data.txt \"\"\" import sys if __name__",
"open(sys.argv[1],'r',encoding = 'utf8') as f: # indicates that the second argument in terminal",
"# indicates that the second argument in terminal is to be used for",
"coding: utf-8 -*- \"\"\" Doc: show how to use it $ python readFile.py",
"use it $ python readFile.py data.txt Show content of data.txt \"\"\" import sys",
"\"\"\" Doc: show how to use it $ python readFile.py data.txt Show content",
"data.txt \"\"\" import sys if __name__ == \"__main__\": with open(sys.argv[1],'r',encoding = 'utf8') as",
"with open(sys.argv[1],'r',encoding = 'utf8') as f: # indicates that the second argument in",
"it $ python readFile.py data.txt Show content of data.txt \"\"\" import sys if",
"__name__ == \"__main__\": with open(sys.argv[1],'r',encoding = 'utf8') as f: # indicates that the",
"= 'utf8') as f: # indicates that the second argument in terminal is",
"readFile.py data.txt Show content of data.txt \"\"\" import sys if __name__ == \"__main__\":",
"import sys if __name__ == \"__main__\": with open(sys.argv[1],'r',encoding = 'utf8') as f: #",
"utf-8 -*- \"\"\" Doc: show how to use it $ python readFile.py data.txt",
"sys if __name__ == \"__main__\": with open(sys.argv[1],'r',encoding = 'utf8') as f: # indicates",
"the second argument in terminal is to be used for line in f:",
"'utf8') as f: # indicates that the second argument in terminal is to",
"indicates that the second argument in terminal is to be used for line"
] |
[
"path from . import views app_name = 'operations' urlpatterns = [ # 用户个人中心",
"name='reset_head_portrait'), # 修改用户密码 path('reset_user_password/', views.ResetUserPasswordView.as_view(), name='reset_user_password'), # 修改用户信息 path('reset_user_information/', views.ResetUserInformationView.as_view(), name='reset_user_information'), # 修改邮箱是发送的验证码",
"'2019/2/25 18:14' from django.urls import path from . import views app_name = 'operations'",
"# _*_ coding: utf-8 _*_ __author__ = 'nick' __date__ = '2019/2/25 18:14' from",
"import views app_name = 'operations' urlpatterns = [ # 用户个人中心 path('user_center_information/', views.UserCenterInformation.as_view(), name='user_center_information'),",
"[ # 用户个人中心 path('user_center_information/', views.UserCenterInformation.as_view(), name='user_center_information'), # 用户学习的课程 path('user_center_my_courses/', views.UserStudyCourse.as_view(), name='user_center_my_courses'), # 用户消息",
"views.UserCollectedTeacher.as_view(), name='user_center_fav_teachers'), # 用户收藏的教师 path('user_center_fav_courses/', views.UserCollectedCourse.as_view(), name='user_center_fav_courses'), # 用户收藏的教师 path('user_center_fav_organizations/', views.UserCollectedOrganization.as_view(), name='user_center_fav_organizations'), #",
"views.UserMessageView.as_view(), name='user_center_messages'), # 用户收藏的教师 path('user_center_fav_teachers/', views.UserCollectedTeacher.as_view(), name='user_center_fav_teachers'), # 用户收藏的教师 path('user_center_fav_courses/', views.UserCollectedCourse.as_view(), name='user_center_fav_courses'), #",
"# 用户收藏的教师 path('user_center_fav_courses/', views.UserCollectedCourse.as_view(), name='user_center_fav_courses'), # 用户收藏的教师 path('user_center_fav_organizations/', views.UserCollectedOrganization.as_view(), name='user_center_fav_organizations'), # 修改用户头像 path('reset_head_portrait/',",
"修改用户头像 path('reset_head_portrait/', views.ResetUserHeaderPortraitView.as_view(), name='reset_head_portrait'), # 修改用户密码 path('reset_user_password/', views.ResetUserPasswordView.as_view(), name='reset_user_password'), # 修改用户信息 path('reset_user_information/', views.ResetUserInformationView.as_view(),",
"views.UserStudyCourse.as_view(), name='user_center_my_courses'), # 用户消息 path('user_center_messages/', views.UserMessageView.as_view(), name='user_center_messages'), # 用户收藏的教师 path('user_center_fav_teachers/', views.UserCollectedTeacher.as_view(), name='user_center_fav_teachers'), #",
"from django.urls import path from . import views app_name = 'operations' urlpatterns =",
"_*_ coding: utf-8 _*_ __author__ = 'nick' __date__ = '2019/2/25 18:14' from django.urls",
"_*_ __author__ = 'nick' __date__ = '2019/2/25 18:14' from django.urls import path from",
"path('reset_user_password/', views.ResetUserPasswordView.as_view(), name='reset_user_password'), # 修改用户信息 path('reset_user_information/', views.ResetUserInformationView.as_view(), name='reset_user_information'), # 修改邮箱是发送的验证码 path('send_email_verify_record/', views.SendEmailView.as_view(), name='send_email_verify_record'),",
"views.UserCollectedOrganization.as_view(), name='user_center_fav_organizations'), # 修改用户头像 path('reset_head_portrait/', views.ResetUserHeaderPortraitView.as_view(), name='reset_head_portrait'), # 修改用户密码 path('reset_user_password/', views.ResetUserPasswordView.as_view(), name='reset_user_password'), #",
"path('reset_head_portrait/', views.ResetUserHeaderPortraitView.as_view(), name='reset_head_portrait'), # 修改用户密码 path('reset_user_password/', views.ResetUserPasswordView.as_view(), name='reset_user_password'), # 修改用户信息 path('reset_user_information/', views.ResetUserInformationView.as_view(), name='reset_user_information'),",
"views.SendEmailView.as_view(), name='send_email_verify_record'), # 修改邮箱 path('reset_user_email/', views.ResetUserEmailView.as_view(), name='reset_user_email'), # 读取用户消息 path('read_message/', views.ReadMessageView.as_view(), name='read_message'), ]",
"# 修改用户信息 path('reset_user_information/', views.ResetUserInformationView.as_view(), name='reset_user_information'), # 修改邮箱是发送的验证码 path('send_email_verify_record/', views.SendEmailView.as_view(), name='send_email_verify_record'), # 修改邮箱 path('reset_user_email/',",
"django.urls import path from . import views app_name = 'operations' urlpatterns = [",
"'operations' urlpatterns = [ # 用户个人中心 path('user_center_information/', views.UserCenterInformation.as_view(), name='user_center_information'), # 用户学习的课程 path('user_center_my_courses/', views.UserStudyCourse.as_view(),",
"utf-8 _*_ __author__ = 'nick' __date__ = '2019/2/25 18:14' from django.urls import path",
"app_name = 'operations' urlpatterns = [ # 用户个人中心 path('user_center_information/', views.UserCenterInformation.as_view(), name='user_center_information'), # 用户学习的课程",
"= '2019/2/25 18:14' from django.urls import path from . import views app_name =",
"urlpatterns = [ # 用户个人中心 path('user_center_information/', views.UserCenterInformation.as_view(), name='user_center_information'), # 用户学习的课程 path('user_center_my_courses/', views.UserStudyCourse.as_view(), name='user_center_my_courses'),",
"= [ # 用户个人中心 path('user_center_information/', views.UserCenterInformation.as_view(), name='user_center_information'), # 用户学习的课程 path('user_center_my_courses/', views.UserStudyCourse.as_view(), name='user_center_my_courses'), #",
"views app_name = 'operations' urlpatterns = [ # 用户个人中心 path('user_center_information/', views.UserCenterInformation.as_view(), name='user_center_information'), #",
"name='user_center_messages'), # 用户收藏的教师 path('user_center_fav_teachers/', views.UserCollectedTeacher.as_view(), name='user_center_fav_teachers'), # 用户收藏的教师 path('user_center_fav_courses/', views.UserCollectedCourse.as_view(), name='user_center_fav_courses'), # 用户收藏的教师",
"用户收藏的教师 path('user_center_fav_teachers/', views.UserCollectedTeacher.as_view(), name='user_center_fav_teachers'), # 用户收藏的教师 path('user_center_fav_courses/', views.UserCollectedCourse.as_view(), name='user_center_fav_courses'), # 用户收藏的教师 path('user_center_fav_organizations/', views.UserCollectedOrganization.as_view(),",
"name='user_center_fav_teachers'), # 用户收藏的教师 path('user_center_fav_courses/', views.UserCollectedCourse.as_view(), name='user_center_fav_courses'), # 用户收藏的教师 path('user_center_fav_organizations/', views.UserCollectedOrganization.as_view(), name='user_center_fav_organizations'), # 修改用户头像",
". import views app_name = 'operations' urlpatterns = [ # 用户个人中心 path('user_center_information/', views.UserCenterInformation.as_view(),",
"path('user_center_fav_courses/', views.UserCollectedCourse.as_view(), name='user_center_fav_courses'), # 用户收藏的教师 path('user_center_fav_organizations/', views.UserCollectedOrganization.as_view(), name='user_center_fav_organizations'), # 修改用户头像 path('reset_head_portrait/', views.ResetUserHeaderPortraitView.as_view(), name='reset_head_portrait'),",
"views.ResetUserInformationView.as_view(), name='reset_user_information'), # 修改邮箱是发送的验证码 path('send_email_verify_record/', views.SendEmailView.as_view(), name='send_email_verify_record'), # 修改邮箱 path('reset_user_email/', views.ResetUserEmailView.as_view(), name='reset_user_email'), #",
"name='reset_user_information'), # 修改邮箱是发送的验证码 path('send_email_verify_record/', views.SendEmailView.as_view(), name='send_email_verify_record'), # 修改邮箱 path('reset_user_email/', views.ResetUserEmailView.as_view(), name='reset_user_email'), # 读取用户消息",
"path('send_email_verify_record/', views.SendEmailView.as_view(), name='send_email_verify_record'), # 修改邮箱 path('reset_user_email/', views.ResetUserEmailView.as_view(), name='reset_user_email'), # 读取用户消息 path('read_message/', views.ReadMessageView.as_view(), name='read_message'),",
"path('user_center_fav_teachers/', views.UserCollectedTeacher.as_view(), name='user_center_fav_teachers'), # 用户收藏的教师 path('user_center_fav_courses/', views.UserCollectedCourse.as_view(), name='user_center_fav_courses'), # 用户收藏的教师 path('user_center_fav_organizations/', views.UserCollectedOrganization.as_view(), name='user_center_fav_organizations'),",
"name='user_center_fav_courses'), # 用户收藏的教师 path('user_center_fav_organizations/', views.UserCollectedOrganization.as_view(), name='user_center_fav_organizations'), # 修改用户头像 path('reset_head_portrait/', views.ResetUserHeaderPortraitView.as_view(), name='reset_head_portrait'), # 修改用户密码",
"= 'operations' urlpatterns = [ # 用户个人中心 path('user_center_information/', views.UserCenterInformation.as_view(), name='user_center_information'), # 用户学习的课程 path('user_center_my_courses/',",
"path('user_center_my_courses/', views.UserStudyCourse.as_view(), name='user_center_my_courses'), # 用户消息 path('user_center_messages/', views.UserMessageView.as_view(), name='user_center_messages'), # 用户收藏的教师 path('user_center_fav_teachers/', views.UserCollectedTeacher.as_view(), name='user_center_fav_teachers'),",
"name='user_center_fav_organizations'), # 修改用户头像 path('reset_head_portrait/', views.ResetUserHeaderPortraitView.as_view(), name='reset_head_portrait'), # 修改用户密码 path('reset_user_password/', views.ResetUserPasswordView.as_view(), name='reset_user_password'), # 修改用户信息",
"18:14' from django.urls import path from . import views app_name = 'operations' urlpatterns",
"# 用户收藏的教师 path('user_center_fav_organizations/', views.UserCollectedOrganization.as_view(), name='user_center_fav_organizations'), # 修改用户头像 path('reset_head_portrait/', views.ResetUserHeaderPortraitView.as_view(), name='reset_head_portrait'), # 修改用户密码 path('reset_user_password/',",
"用户收藏的教师 path('user_center_fav_organizations/', views.UserCollectedOrganization.as_view(), name='user_center_fav_organizations'), # 修改用户头像 path('reset_head_portrait/', views.ResetUserHeaderPortraitView.as_view(), name='reset_head_portrait'), # 修改用户密码 path('reset_user_password/', views.ResetUserPasswordView.as_view(),",
"__date__ = '2019/2/25 18:14' from django.urls import path from . import views app_name",
"'nick' __date__ = '2019/2/25 18:14' from django.urls import path from . import views",
"views.UserCenterInformation.as_view(), name='user_center_information'), # 用户学习的课程 path('user_center_my_courses/', views.UserStudyCourse.as_view(), name='user_center_my_courses'), # 用户消息 path('user_center_messages/', views.UserMessageView.as_view(), name='user_center_messages'), #",
"# 修改用户密码 path('reset_user_password/', views.ResetUserPasswordView.as_view(), name='reset_user_password'), # 修改用户信息 path('reset_user_information/', views.ResetUserInformationView.as_view(), name='reset_user_information'), # 修改邮箱是发送的验证码 path('send_email_verify_record/',",
"修改用户密码 path('reset_user_password/', views.ResetUserPasswordView.as_view(), name='reset_user_password'), # 修改用户信息 path('reset_user_information/', views.ResetUserInformationView.as_view(), name='reset_user_information'), # 修改邮箱是发送的验证码 path('send_email_verify_record/', views.SendEmailView.as_view(),",
"views.ResetUserHeaderPortraitView.as_view(), name='reset_head_portrait'), # 修改用户密码 path('reset_user_password/', views.ResetUserPasswordView.as_view(), name='reset_user_password'), # 修改用户信息 path('reset_user_information/', views.ResetUserInformationView.as_view(), name='reset_user_information'), #",
"path('reset_user_information/', views.ResetUserInformationView.as_view(), name='reset_user_information'), # 修改邮箱是发送的验证码 path('send_email_verify_record/', views.SendEmailView.as_view(), name='send_email_verify_record'), # 修改邮箱 path('reset_user_email/', views.ResetUserEmailView.as_view(), name='reset_user_email'),",
"from . import views app_name = 'operations' urlpatterns = [ # 用户个人中心 path('user_center_information/',",
"# 修改用户头像 path('reset_head_portrait/', views.ResetUserHeaderPortraitView.as_view(), name='reset_head_portrait'), # 修改用户密码 path('reset_user_password/', views.ResetUserPasswordView.as_view(), name='reset_user_password'), # 修改用户信息 path('reset_user_information/',",
"# 用户学习的课程 path('user_center_my_courses/', views.UserStudyCourse.as_view(), name='user_center_my_courses'), # 用户消息 path('user_center_messages/', views.UserMessageView.as_view(), name='user_center_messages'), # 用户收藏的教师 path('user_center_fav_teachers/',",
"name='user_center_information'), # 用户学习的课程 path('user_center_my_courses/', views.UserStudyCourse.as_view(), name='user_center_my_courses'), # 用户消息 path('user_center_messages/', views.UserMessageView.as_view(), name='user_center_messages'), # 用户收藏的教师",
"用户消息 path('user_center_messages/', views.UserMessageView.as_view(), name='user_center_messages'), # 用户收藏的教师 path('user_center_fav_teachers/', views.UserCollectedTeacher.as_view(), name='user_center_fav_teachers'), # 用户收藏的教师 path('user_center_fav_courses/', views.UserCollectedCourse.as_view(),",
"views.UserCollectedCourse.as_view(), name='user_center_fav_courses'), # 用户收藏的教师 path('user_center_fav_organizations/', views.UserCollectedOrganization.as_view(), name='user_center_fav_organizations'), # 修改用户头像 path('reset_head_portrait/', views.ResetUserHeaderPortraitView.as_view(), name='reset_head_portrait'), #",
"用户学习的课程 path('user_center_my_courses/', views.UserStudyCourse.as_view(), name='user_center_my_courses'), # 用户消息 path('user_center_messages/', views.UserMessageView.as_view(), name='user_center_messages'), # 用户收藏的教师 path('user_center_fav_teachers/', views.UserCollectedTeacher.as_view(),",
"# 修改邮箱是发送的验证码 path('send_email_verify_record/', views.SendEmailView.as_view(), name='send_email_verify_record'), # 修改邮箱 path('reset_user_email/', views.ResetUserEmailView.as_view(), name='reset_user_email'), # 读取用户消息 path('read_message/',",
"用户个人中心 path('user_center_information/', views.UserCenterInformation.as_view(), name='user_center_information'), # 用户学习的课程 path('user_center_my_courses/', views.UserStudyCourse.as_view(), name='user_center_my_courses'), # 用户消息 path('user_center_messages/', views.UserMessageView.as_view(),",
"# 用户收藏的教师 path('user_center_fav_teachers/', views.UserCollectedTeacher.as_view(), name='user_center_fav_teachers'), # 用户收藏的教师 path('user_center_fav_courses/', views.UserCollectedCourse.as_view(), name='user_center_fav_courses'), # 用户收藏的教师 path('user_center_fav_organizations/',",
"path('user_center_messages/', views.UserMessageView.as_view(), name='user_center_messages'), # 用户收藏的教师 path('user_center_fav_teachers/', views.UserCollectedTeacher.as_view(), name='user_center_fav_teachers'), # 用户收藏的教师 path('user_center_fav_courses/', views.UserCollectedCourse.as_view(), name='user_center_fav_courses'),",
"path('user_center_information/', views.UserCenterInformation.as_view(), name='user_center_information'), # 用户学习的课程 path('user_center_my_courses/', views.UserStudyCourse.as_view(), name='user_center_my_courses'), # 用户消息 path('user_center_messages/', views.UserMessageView.as_view(), name='user_center_messages'),",
"views.ResetUserPasswordView.as_view(), name='reset_user_password'), # 修改用户信息 path('reset_user_information/', views.ResetUserInformationView.as_view(), name='reset_user_information'), # 修改邮箱是发送的验证码 path('send_email_verify_record/', views.SendEmailView.as_view(), name='send_email_verify_record'), #",
"= 'nick' __date__ = '2019/2/25 18:14' from django.urls import path from . import",
"用户收藏的教师 path('user_center_fav_courses/', views.UserCollectedCourse.as_view(), name='user_center_fav_courses'), # 用户收藏的教师 path('user_center_fav_organizations/', views.UserCollectedOrganization.as_view(), name='user_center_fav_organizations'), # 修改用户头像 path('reset_head_portrait/', views.ResetUserHeaderPortraitView.as_view(),",
"name='reset_user_password'), # 修改用户信息 path('reset_user_information/', views.ResetUserInformationView.as_view(), name='reset_user_information'), # 修改邮箱是发送的验证码 path('send_email_verify_record/', views.SendEmailView.as_view(), name='send_email_verify_record'), # 修改邮箱",
"修改用户信息 path('reset_user_information/', views.ResetUserInformationView.as_view(), name='reset_user_information'), # 修改邮箱是发送的验证码 path('send_email_verify_record/', views.SendEmailView.as_view(), name='send_email_verify_record'), # 修改邮箱 path('reset_user_email/', views.ResetUserEmailView.as_view(),",
"修改邮箱是发送的验证码 path('send_email_verify_record/', views.SendEmailView.as_view(), name='send_email_verify_record'), # 修改邮箱 path('reset_user_email/', views.ResetUserEmailView.as_view(), name='reset_user_email'), # 读取用户消息 path('read_message/', views.ReadMessageView.as_view(),",
"name='user_center_my_courses'), # 用户消息 path('user_center_messages/', views.UserMessageView.as_view(), name='user_center_messages'), # 用户收藏的教师 path('user_center_fav_teachers/', views.UserCollectedTeacher.as_view(), name='user_center_fav_teachers'), # 用户收藏的教师",
"coding: utf-8 _*_ __author__ = 'nick' __date__ = '2019/2/25 18:14' from django.urls import",
"__author__ = 'nick' __date__ = '2019/2/25 18:14' from django.urls import path from .",
"import path from . import views app_name = 'operations' urlpatterns = [ #",
"path('user_center_fav_organizations/', views.UserCollectedOrganization.as_view(), name='user_center_fav_organizations'), # 修改用户头像 path('reset_head_portrait/', views.ResetUserHeaderPortraitView.as_view(), name='reset_head_portrait'), # 修改用户密码 path('reset_user_password/', views.ResetUserPasswordView.as_view(), name='reset_user_password'),",
"# 用户消息 path('user_center_messages/', views.UserMessageView.as_view(), name='user_center_messages'), # 用户收藏的教师 path('user_center_fav_teachers/', views.UserCollectedTeacher.as_view(), name='user_center_fav_teachers'), # 用户收藏的教师 path('user_center_fav_courses/',",
"# 用户个人中心 path('user_center_information/', views.UserCenterInformation.as_view(), name='user_center_information'), # 用户学习的课程 path('user_center_my_courses/', views.UserStudyCourse.as_view(), name='user_center_my_courses'), # 用户消息 path('user_center_messages/',"
] |
[
"255)) def thumbnail(**options): # images: a list of Image objects, or a list",
"back_image.paste(star, (LEFT_OFFSET, OUT_HEIGHT - BOTTOM_OFFSET - STAT_STEP * (i + 1)), mask=star) back_image.save(fn)",
"- real_height draw.text((x, y), s, fill=(245, 255, 250), font=font) elif back_number in [f'back_{n}'",
"Image.new('RGB', (ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(max(lines, key=lambda line: len(line)), font=font)[0] + 2 * col_space, (line_height",
"OUT_HEIGHT = 1364, 1020 INNER_WIDTH, INNER_HEIGHT = 1334, 1002 STAR_SIZE, ICON_SIZE = 100,",
"mask=frame) back_image.paste(band_icon, (LEFT_OFFSET, TOP_OFFSET), mask=band_icon) back_image.paste(attribute_icon, (OUT_WIDTH - RIGHT_OFFSET, TOP_OFFSET), mask=attribute_icon) for i",
"except: import sys sys.excepthook(*sys.exc_info()) return None else: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/m_{rsn}_{\"normal\" if",
"real_height = real_width + SPACING im = Image.new('RGB', (im_src.width, im_src.height + real_height), (255,",
"objects, or a list of lists(tuples) of Image objects # labels: a list",
"in range(col_num): if r * col_num + c >= len(images): break image_group =",
"i in range(rarity): back_image.paste(star, (LEFT_OFFSET, OUT_HEIGHT - BOTTOM_OFFSET - STAT_STEP * (i +",
"draw.textsize(labels[r * col_num + c], font=font) draw.text(( len(image_group) * c * box_width +",
"* len(images[0]) * box_width + (col_num - 1) * col_space, box_height * row_num",
"box_height = first_image.size else: if options['image_style'].get('width') and options['image_style'].get('height'): box_width, box_height = options['image_style']['width'], options['image_style']['height']",
"in im_list] for im_list in images] box_width, box_height = options['image_style']['width'], max([im.size[1] for im_list",
"box_height = options['image_style']['width'], max([im.size[1] for im_list in images for im in im_list]) elif",
"ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height = real_width + SPACING im = Image.new('RGB', (im_src.width, im_src.height",
"return Image.new('RGB', (width, height), (255, 255, 255)) def thumbnail(**options): # images: a list",
"rarity == 1: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-1-{attribute}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) else: frame = Image.open(os.path.join(globals.asset_resource_path,",
"= im_src.height draw.text((x, y), s, fill=(23, 0, 0), font=font) return im def get_back_pics():",
"c * col_space, r * (box_height + label_height + row_space) + box_height ),",
"2), mask=card) back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon, (LEFT_OFFSET, TOP_OFFSET), mask=band_icon) back_image.paste(attribute_icon, (OUT_WIDTH -",
"if return_fn: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') back_image.save(fn)",
"box_width, box_height = first_image.size else: if options['image_style'].get('width') and options['image_style'].get('height'): box_width, box_height = options['image_style']['width'],",
"c in range(col_num): if r * col_num + c >= len(images): break image_group",
"'star_trained.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) if rarity == 1: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-1-{attribute}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS)",
"except: return '' def white_padding(width, height): return Image.new('RGB', (width, height), (255, 255, 255))",
"= 140, 130 BACK_PIC_NUM_EACH_LINE = 5 def bg_image_gen(back_number, s): def half_en_len(s): return (len(s)",
"= draw.textsize(s, font=font) x = (text_width - sz[0]) / 2 y = 5",
"resize # width: width of each image, if not assigned, will be min(scaled",
"objects') else: images = [[im] for im in images] if not options.get('image_style'): box_width,",
"100, 150 TOP_OFFSET, RIGHT_OFFSET, BOTTOM_OFFSET, LEFT_OFFSET = 22, 165, 20, 10 STAT_STEP =",
"- sz[0]) / 2 y = im_src.height draw.text((x, y), s, fill=(23, 0, 0),",
"isinstance(first_image, Image.Image): raise Exception('images must be a list of Image objects, or a",
"BACK_PIC_UNIT_HEIGHT * (((cur_back_pic_nums - 1) // BACK_PIC_NUM_EACH_LINE) + 1)), (255, 255, 255)) for",
"image_group = images[r * col_num + c] for i, im in enumerate(image_group): back_image.paste(im,",
"(box_width - im.size[0]) // 2 + col_space * c, r * (box_height +",
"Image objects') else: images = [[im] for im in images] if not options.get('image_style'):",
"max(3, im_src.width // max(6, half_en_len(s)) * 4 // 5) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'),",
"Image.open(img_path) if back_number in [f'back_{n}' for n in [38, 46, 47, 51, 52,",
"Image.new('RGB', (im_src.width, im_src.height), (255, 255, 255)) im.paste(im_src) text_width = im_src.width draw = ImageDraw.Draw(im)",
"\"after_training\"}.png') back_image.save(fn) return fn return back_image except: import sys sys.excepthook(*sys.exc_info()) return None else:",
"strings shown at the bottom # image_style: if not assigned, take the params",
"raw = ImageAsset.get('back_catalogue') if raw: return raw back_pic_set = set() for _, _,",
"real_width = max(3, im_src.width // max(6, half_en_len(s))) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height",
"except: pass def manual(): raw = ImageAsset.get('manual') if raw: return raw row_space =",
"means the space between the label of row1 and the image of row2)",
"[f'back_{n}' for n in [33]]: real_width = max(3, im_src.width // max(6, half_en_len(s)) *",
"= real_width + SPACING im = Image.new('RGB', (im_src.width, im_src.height + real_height), (255, 255,",
"def compress(infile, mb=None, step=10, quality=80, isabs=False): if not isabs: absinfile = os.path.join(globals.datapath, 'image',",
"files in os.walk(os.path.join(globals.staticpath, 'bg')): for f in files: if f.startswith('back_') and f.endswith('.jpg'): num",
"try: if return_fn: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png')",
"sz = draw.textsize(s, font=font) x = (text_width - sz[0]) / 2 y =",
"= os.path.join(globals.datapath, 'image', infile) else: absinfile = infile outfile = infile[infile.rfind('/') + 1:infile.rfind('.')]",
"each label # col_num (images are arranged row by row) # col_space: (space",
"os.walk(os.path.join(globals.staticpath, 'bg')): for f in files: if f.startswith('back_') and f.endswith('.jpg'): num = int(back_regex.findall(f)[0])",
"+ (col_num - 1) * col_space, box_height * row_num + (row_num - 1)",
"trained=False, return_fn=False): if thumbnail: try: if return_fn: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if",
"real_height), (255, 255, 255)) im.paste(im_src) text_width = im_src.width draw = ImageDraw.Draw(im) sz =",
"image) return new_image except: pass def manual(): raw = ImageAsset.get('manual') if raw: return",
"len(line)), font=font)[0] + 2 * col_space, (line_height + row_space) * len(lines)), (255, 255,",
"image.size, (255, 255, 255, 255)) new_image.paste(image, (0, 0), image) return new_image except: pass",
"Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) else: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((STAR_SIZE,",
"+ c] for i, im in enumerate(image_group): back_image.paste(im, ( (len(image_group) * c +",
"value by height, 180) # height: height of each image, if not assigned,",
"im.paste(im_src) text_width = im_src.width draw = ImageDraw.Draw(im) sz = draw.textsize(s, font=font) x =",
"), (255, 255, 255)) draw = ImageDraw.Draw(back_image) labels = options['labels'] for r in",
"row_space) )) return ImageAsset.image_raw(back_image) def open_nontransparent(filename): try: image = Image.open(filename).convert('RGBA') new_image = Image.new('RGBA',",
"Image.ANTIALIAS) if rarity == 1: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-1-{attribute}.png')) else: frame = Image.open(os.path.join(globals.asset_resource_path,",
"for im in im_list]) elif not options['image_style'].get('width') and options['image_style'].get('height'): images = [[im.resize((options['image_style']['height'] *",
"y = im_src.height draw.text((x, y), s, fill=(23, 0, 0), font=font) return im def",
"while o_size > mb: im = Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile, quality=quality) if",
"im_src.height + real_height), (255, 255, 255)) im.paste(im_src) text_width = im_src.width draw = ImageDraw.Draw(im)",
"if not trained else \"after_training\"}.png') back_image.save(fn) return fn return back_image except: import sys",
"f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') back_image.save(fn) return fn return back_image except: import",
"r in range(row_num): for c in range(col_num): if r * col_num + c",
"mask=star) back_image.save(fn) return fn except: return '' def white_padding(width, height): return Image.new('RGB', (width,",
"c], font=font) draw.text(( len(image_group) * c * box_width + (len(image_group) * box_width -",
"row_space ), (255, 255, 255)) draw = ImageDraw.Draw(back_image) for r in range(row_num): for",
"font=font) x = (text_width - sz[0]) / 2 y = 5 draw.text((x, y),",
"BOTTOM_OFFSET - STAT_STEP * (i + 1)), mask=star) back_image.save(fn) return fn except: return",
"and not options['image_style'].get('height'): images = [[im.resize((options['image_style']['width'], options['image_style']['width'] * im.size[1] // im.size[0])) for im",
"= 1364, 1020 INNER_WIDTH, INNER_HEIGHT = 1334, 1002 STAR_SIZE, ICON_SIZE = 100, 150",
"and f.endswith('.jpg'): num = int(back_regex.findall(f)[0]) back_pic_set.add(num) cur_back_pic_nums = len(back_pic_set) if cur_back_pic_nums == 0:",
"0))).textsize('底图目录', font=font)[1] image = Image.new('RGB', (ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(max(lines, key=lambda line: len(line)), font=font)[0] +",
"(ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(max(lines, key=lambda line: len(line)), font=font)[0] + 2 * col_space, (line_height +",
"if raw: return raw back_pic_set = set() for _, _, files in os.walk(os.path.join(globals.staticpath,",
"(0, 0))).textsize(''.join(all_chars), font=font)[1] box_width = max(box_width * len(images[0]), max_label_width) // len(images[0]) back_image =",
"for im_list in images] box_width, box_height = max([im.size[0] for im_list in images for",
"'' def white_padding(width, height): return Image.new('RGB', (width, height), (255, 255, 255)) def thumbnail(**options):",
"= ImageDraw.Draw(im) sz = draw.textsize(s, font=font) x = (text_width - sz[0]) / 2",
"[[im.resize((box_width, box_height)) for im in im_list] for im_list in images] elif options['image_style'].get('width') and",
"im.save(absoutfile, quality=quality) return absoutfile o_size = os.path.getsize(absinfile) / 1024 if o_size <= mb:",
"row) # col_space: (space between two columns) # row_space (space between two rows,",
"images = options['images'] first_image = images[0] if not isinstance(first_image, Image.Image): if isinstance(first_image, (list,",
"if not isabs: absinfile = os.path.join(globals.datapath, 'image', infile) else: absinfile = infile outfile",
"f'frame-{rarity}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) back_image.paste(card, ((OUT_WIDTH - INNER_WIDTH) // 2, (OUT_HEIGHT - INNER_HEIGHT) //",
"[技能类型]: 按条件筛选符合要求的卡片,同类条件取并集,不同类条件取交集。例如: 查卡 4x pure ksm 分', '查卡+数字: 按id查询单卡信息', '无框+数字: 按id查询单卡无框卡面', '活动列表 [活动类型]:",
"c] for i, im in enumerate(image_group): back_image.paste(im, ( (len(image_group) * c + i)",
"pure ksm 分', '查卡+数字: 按id查询单卡信息', '无框+数字: 按id查询单卡无框卡面', '活动列表 [活动类型]: 按条件筛选符合要求的活动,活动类型包括“一般活动”,“竞演LIVE”或“对邦”,“挑战LIVE”或“CP”,“LIVE试炼”,“任务LIVE”', '活动+数字 [服务器]: 按id查询单活动信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”',",
"row by row) # col_space: (space between two columns) # row_space (space between",
"box_width, box_height = options['image_style']['width'], options['image_style']['height'] images = [[im.resize((box_width, box_height)) for im in im_list]",
"== 1: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-1-{attribute}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) else: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-{rarity}.png')).resize((OUT_WIDTH,",
"= f'back_{back_number}' img_path = os.path.join(globals.staticpath, f'bg/{back_number}.jpg') im_src = Image.open(img_path) if back_number in [f'back_{n}'",
"+ c], font=font) draw.text(( len(image_group) * c * box_width + (len(image_group) * box_width",
"= [[im.resize((box_width, box_height)) for im in im_list] for im_list in images] elif options['image_style'].get('width')",
"== 1: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-1-{attribute}.png')) else: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-{rarity}.png')) back_image.paste(frame, (0,",
"lines = [ 'ycm/有车吗: 查询车牌(来源: https://bandoristation.com/)', '底图目录: 查询底图目录(是的,不仅功能一样,连图都盗过来了,虽然还没更新。底图31,Tsugu!.jpg)', '底图+数字: 切换底图', 'xx.jpg: 图片合成', '',",
"按id查询单卡信息', '无框+数字: 按id查询单卡无框卡面', '活动列表 [活动类型]: 按条件筛选符合要求的活动,活动类型包括“一般活动”,“竞演LIVE”或“对邦”,“挑战LIVE”或“CP”,“LIVE试炼”,“任务LIVE”', '活动+数字 [服务器]: 按id查询单活动信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '卡池列表 [卡池类型]: 按条件筛选符合要求的卡池,卡池类型包括“常驻”或“无期限”,“限时”或“限定”或“期间限定”,“特殊”(该条件慎加,因为没啥特别的卡池),“必4”', '卡池+数字",
"255)) im.paste(im_src) text_width = im_src.width draw = ImageDraw.Draw(im) sz = draw.textsize(s, font=font) x",
"text_width = im_src.width draw = ImageDraw.Draw(im) sz = draw.textsize(s, font=font) x = (text_width",
"Image objects') else: raise Exception('images must be a list of Image objects, or",
"(((cur_back_pic_nums - 1) // BACK_PIC_NUM_EACH_LINE) + 1)), (255, 255, 255)) for i, num",
"/ 2 y = im_src.height - real_height draw.text((x, y), s, fill=(245, 255, 250),",
"x = (text_width - sz[0]) / 2 y = im_src.height - 2 *",
"if not trained else \"after_training\"}.png') if os.access(fn, os.R_OK): return fn try: OUT_WIDTH, OUT_HEIGHT",
"max(box_width * len(images[0]), max_label_width) // len(images[0]) back_image = Image.new('RGB', ( col_num * len(images[0])",
"import ImageAsset SPACING = 5 back_regex = re.compile(r'back_([0-9]*)\\.jpg') BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT = 140, 130",
"OUT_HEIGHT)) attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS)",
"fill=(23, 0, 0), font=font) else: real_width = max(3, im_src.width // max(6, half_en_len(s))) font",
"thumbnail: try: if return_fn: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else",
"attribute, band_id, thumbnail=True, trained=False, return_fn=False): if thumbnail: try: if return_fn: fn = os.path.join(globals.datapath,",
"r * col_num + c >= len(images): break image_group = images[r * col_num",
"im_src.width // max(6, half_en_len(s))) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height = real_width +",
"20) lines = [ 'ycm/有车吗: 查询车牌(来源: https://bandoristation.com/)', '底图目录: 查询底图目录(是的,不仅功能一样,连图都盗过来了,虽然还没更新。底图31,Tsugu!.jpg)', '底图+数字: 切换底图', 'xx.jpg: 图片合成',",
"image = Image.new('RGB', (ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(max(lines, key=lambda line: len(line)), font=font)[0] + 2 *",
"2 * col_space, (line_height + row_space) * len(lines)), (255, 255, 255)) draw =",
"os.R_OK): return fn attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')) if not",
"= 5 def bg_image_gen(back_number, s): def half_en_len(s): return (len(s) + (len(s.encode(encoding='utf-8')) - len(s))",
"2 + c * col_space, r * (box_height + label_height + row_space) +",
"165, 20, 10 STAT_STEP = 95 back_image = Image.new('RGB', (OUT_WIDTH, OUT_HEIGHT)) attribute_icon =",
"raise Exception('images must be a list of Image objects, or a list of",
"// im.size[1], options['image_style']['height'])) for im in im_list] for im_list in images] box_width, box_height",
"max(max_label_width, ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(label, font=font)[0]) all_chars |= set(label) label_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(''.join(all_chars),",
"RIGHT_OFFSET, TOP_OFFSET), mask=attribute_icon) for i in range(rarity): back_image.paste(star, (LEFT_OFFSET, OUT_HEIGHT - BOTTOM_OFFSET -",
"im_src.width // max(6, half_en_len(s)) * 4 // 5) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width)",
"# images: a list of Image objects, or a list of lists(tuples) of",
"box_width + (box_width - im.size[0]) // 2 + col_space * c, r *",
"= (text_width - sz[0]) / 2 y = 5 draw.text((x, y), s, fill=(23,",
"= len(back_pic_set) if cur_back_pic_nums == 0: return im = Image.new('RGB', (BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH,",
"(box_height + row_space) )) return ImageAsset.image_raw(back_image) def open_nontransparent(filename): try: image = Image.open(filename).convert('RGBA') new_image",
"[乐团] [技能类型]: 按条件筛选符合要求的卡片,同类条件取并集,不同类条件取交集。例如: 查卡 4x pure ksm 分', '查卡+数字: 按id查询单卡信息', '无框+数字: 按id查询单卡无框卡面', '活动列表",
"height, 180) # height: height of each image, if not assigned, will be",
"1)), mask=star) back_image.save(fn) return fn except: return '' def white_padding(width, height): return Image.new('RGB',",
"raw: return raw row_space = 20 col_space = 50 font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'),",
"(255, 255, 255, 255)) new_image.paste(image, (0, 0), image) return new_image except: pass def",
"= options['images'] first_image = images[0] if not isinstance(first_image, Image.Image): if isinstance(first_image, (list, tuple)):",
"cur_back_pic_nums == 0: return im = Image.new('RGB', (BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT * (((cur_back_pic_nums",
"else: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((32, 32), Image.ANTIALIAS) if rarity",
"- 1) // BACK_PIC_NUM_EACH_LINE) + 1)), (255, 255, 255)) for i, num in",
"height), (255, 255, 255)) def thumbnail(**options): # images: a list of Image objects,",
"col_space = options.get('col_space', 0) row_space = options.get('row_space', 0) if options.get('labels'): font = ImageFont.truetype(os.path.join(globals.staticpath,",
"- INNER_HEIGHT) // 2), mask=card) back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon, (LEFT_OFFSET, TOP_OFFSET), mask=band_icon)",
"infile[infile.rfind('/') + 1:infile.rfind('.')] + '-c.jpg' absoutfile = os.path.join(globals.datapath, 'image', outfile) if os.path.exists(absoutfile): return",
"140, 130 BACK_PIC_NUM_EACH_LINE = 5 def bg_image_gen(back_number, s): def half_en_len(s): return (len(s) +",
"% BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, i // BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_HEIGHT) im.paste(im_o, box) return ImageAsset.image_raw(im,",
"fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') if os.access(fn, os.R_OK):",
"images for im in im_list]) elif not options['image_style'].get('width') and options['image_style'].get('height'): images = [[im.resize((options['image_style']['height']",
"图片合成', '', '以下查询功能数据来源Bestdori', '查卡 [稀有度] [颜色] [人物] [乐团] [技能类型]: 按条件筛选符合要求的卡片,同类条件取并集,不同类条件取交集。例如: 查卡 4x pure",
"real_width) real_height = real_width + SPACING im = Image.new('RGB', (im_src.width, im_src.height + real_height),",
"# width: width of each image, if not assigned, will be min(scaled value",
"and the image of row2) images = options['images'] first_image = images[0] if not",
"of Image objects, or a list of lists(tuples) of Image objects') else: images",
"# labels: a list of strings shown at the bottom # image_style: if",
"of each label # col_num (images are arranged row by row) # col_space:",
"255)) draw = ImageDraw.Draw(image) line_pos = row_space for i, line in enumerate(lines): sz",
"按id查询单卡无框卡面', '活动列表 [活动类型]: 按条件筛选符合要求的活动,活动类型包括“一般活动”,“竞演LIVE”或“对邦”,“挑战LIVE”或“CP”,“LIVE试炼”,“任务LIVE”', '活动+数字 [服务器]: 按id查询单活动信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '卡池列表 [卡池类型]: 按条件筛选符合要求的卡池,卡池类型包括“常驻”或“无期限”,“限时”或“限定”或“期间限定”,“特殊”(该条件慎加,因为没啥特别的卡池),“必4”', '卡池+数字 [服务器]: 按id查询单卡池信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”',",
"y), s, fill=(23, 0, 0), font=font) return im def get_back_pics(): raw = ImageAsset.get('back_catalogue')",
"max([im.size[0] for im_list in images for im in im_list]), options['image_style']['height'] col_num = options.get('col_num',",
"= Image.new('RGB', ( col_num * len(images[0]) * box_width + (col_num - 1) *",
"= max(3, im_src.width // max(6, half_en_len(s))) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height =",
"# image_style: if not assigned, take the params of the first image; if",
"'simhei.ttf'), options.get('label_style', {}).get('font_size', 20)) all_chars = set() max_label_width = 0 for label in",
"'以下查询功能数据来源Bestdori', '查卡 [稀有度] [颜色] [人物] [乐团] [技能类型]: 按条件筛选符合要求的卡片,同类条件取并集,不同类条件取交集。例如: 查卡 4x pure ksm 分',",
"* c + i) * box_width + (box_width - im.size[0]) // 2 +",
"half_en_len(s)) * 4 // 5) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height = real_width",
"1024 if o_size <= mb: return infile while o_size > mb: im =",
"= re.compile(r'back_([0-9]*)\\.jpg') BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT = 140, 130 BACK_PIC_NUM_EACH_LINE = 5 def bg_image_gen(back_number, s):",
"= Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) if not",
"os.access(fn, os.R_OK): return fn attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')) if",
"box_width + (col_num - 1) * col_space, (box_height + label_height) * row_num +",
"* col_space, (box_height + label_height) * row_num + row_num * row_space, ), (255,",
"'查抽卡名字 名字: 查用户名称包含该名字的玩家出的4星', ] line_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize('底图目录', font=font)[1] image = Image.new('RGB',",
"objects, or a list of lists(tuples) of Image objects') else: raise Exception('images must",
"break image_group = images[r * col_num + c] for i, im in enumerate(image_group):",
"(i + 1)), mask=star) back_image.save(fn) return fn except: return '' def white_padding(width, height):",
"from PIL import Image, ImageDraw, ImageFont from utils.Asset import ImageAsset SPACING = 5",
"(255, 255, 255)) im.paste(im_src) text_width = im_src.width draw = ImageDraw.Draw(im) sz = draw.textsize(s,",
"return fn try: OUT_WIDTH, OUT_HEIGHT = 1364, 1020 INNER_WIDTH, INNER_HEIGHT = 1334, 1002",
"* box_width + (len(image_group) * box_width - sz[0]) // 2 + c *",
"4x pure ksm 分', '查卡+数字: 按id查询单卡信息', '无框+数字: 按id查询单卡无框卡面', '活动列表 [活动类型]: 按条件筛选符合要求的活动,活动类型包括“一般活动”,“竞演LIVE”或“对邦”,“挑战LIVE”或“CP”,“LIVE试炼”,“任务LIVE”', '活动+数字 [服务器]:",
"options['image_style'].get('width') and not options['image_style'].get('height'): images = [[im.resize((options['image_style']['width'], options['image_style']['width'] * im.size[1] // im.size[0])) for",
"// 2 + c * col_space, r * (box_height + label_height + row_space)",
"images[r * col_num + c] for i, im in enumerate(image_group): back_image.paste(im, ( (len(image_group)",
"2 y = im_src.height - 2 * real_height draw.text((x, y), s, fill=(245, 255,",
"= ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height = real_width + SPACING im = Image.new('RGB', (im_src.width,",
"im.save(absoutfile, quality=quality) if quality - step < 0: break quality -= step o_size",
"images: a list of Image objects, or a list of lists(tuples) of Image",
"im = im.convert('RGB') im.save(absoutfile, quality=quality) if quality - step < 0: break quality",
"each image, if not assigned, will be min(scaled value by width, 180) #",
"if not assigned, will be min(scaled value by width, 180) # label_style: #",
"* row_num + (row_num - 1) * row_space ), (255, 255, 255)) draw",
"'simhei.ttf'), real_width) real_height = real_width + SPACING im = Image.new('RGB', (im_src.width, im_src.height +",
"[38, 46, 47, 51, 52, 53]]: real_width = max(3, im_src.width // max(6, half_en_len(s))",
"), (255, 255, 255)) draw = ImageDraw.Draw(back_image) for r in range(row_num): for c",
"label # col_num (images are arranged row by row) # col_space: (space between",
"back_image.paste(band_icon, (0, 0), mask=band_icon) back_image.paste(attribute_icon, (180 - 50, 0), mask=attribute_icon) for i in",
"x = (text_width - sz[0]) / 2 y = im_src.height - real_height draw.text((x,",
"ImageAsset.get('back_catalogue') if raw: return raw back_pic_set = set() for _, _, files in",
"(0, 0), mask=frame) back_image.paste(band_icon, (LEFT_OFFSET, TOP_OFFSET), mask=band_icon) back_image.paste(attribute_icon, (OUT_WIDTH - RIGHT_OFFSET, TOP_OFFSET), mask=attribute_icon)",
"a list of lists(tuples) of Image objects') else: raise Exception('images must be a",
"max_label_width = max(max_label_width, ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(label, font=font)[0]) all_chars |= set(label) label_height = ImageDraw.Draw(Image.new('RGB',",
"f.startswith('back_') and f.endswith('.jpg'): num = int(back_regex.findall(f)[0]) back_pic_set.add(num) cur_back_pic_nums = len(back_pic_set) if cur_back_pic_nums ==",
"(i + 1)), mask=star) if return_fn: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not",
"= int(back_regex.findall(f)[0]) back_pic_set.add(num) cur_back_pic_nums = len(back_pic_set) if cur_back_pic_nums == 0: return im =",
"( col_num * len(images[0]) * box_width + (col_num - 1) * col_space, box_height",
"for _, _, files in os.walk(os.path.join(globals.staticpath, 'bg')): for f in files: if f.startswith('back_')",
"im.convert('RGB') im.save(absoutfile, quality=quality) return absoutfile o_size = os.path.getsize(absinfile) / 1024 if o_size <=",
"for i in range(rarity): back_image.paste(star, (LEFT_OFFSET, OUT_HEIGHT - BOTTOM_OFFSET - STAT_STEP * (i",
"draw.text((col_space, line_pos), line, fill=(0, 0, 0), font=font) line_pos += sz[1] + row_space return",
"if raw: return raw row_space = 20 col_space = 50 font = ImageFont.truetype(os.path.join(globals.staticpath,",
"20 col_space = 50 font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), 20) lines = [ 'ycm/有车吗:",
"170 - 27 * (i + 1)), mask=star) if return_fn: fn = os.path.join(globals.datapath,",
"isinstance(first_image, Image.Image): if isinstance(first_image, (list, tuple)): first_image = first_image[0] if not isinstance(first_image, Image.Image):",
"// col_num + 1 col_space = options.get('col_space', 0) row_space = options.get('row_space', 0) if",
"5 def bg_image_gen(back_number, s): def half_en_len(s): return (len(s) + (len(s.encode(encoding='utf-8')) - len(s)) //",
"fill=(0, 0, 0), font=font) else: back_image = Image.new('RGB', ( col_num * len(images[0]) *",
"the image of row2) images = options['images'] first_image = images[0] if not isinstance(first_image,",
"(text_width - sz[0]) / 2 y = im_src.height - real_height draw.text((x, y), s,",
"not isinstance(first_image, Image.Image): raise Exception('images must be a list of Image objects, or",
"* len(lines)), (255, 255, 255)) draw = ImageDraw.Draw(image) line_pos = row_space for i,",
"1334, 1002 STAR_SIZE, ICON_SIZE = 100, 150 TOP_OFFSET, RIGHT_OFFSET, BOTTOM_OFFSET, LEFT_OFFSET = 22,",
"= Image.open(os.path.join(globals.asset_resource_path, f'frame-1-{attribute}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) else: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-{rarity}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) back_image.paste(card,",
"list of lists(tuples) of Image objects') else: images = [[im] for im in",
"= im.convert('RGB') im.save(absoutfile, quality=quality) return absoutfile o_size = os.path.getsize(absinfile) / 1024 if o_size",
"[f'back_{n}' for n in [38, 46, 47, 51, 52, 53]]: real_width = max(3,",
"isabs=False): if not isabs: absinfile = os.path.join(globals.datapath, 'image', infile) else: absinfile = infile",
"image of row2) images = options['images'] first_image = images[0] if not isinstance(first_image, Image.Image):",
"row_num = (len(images) - 1) // col_num + 1 col_space = options.get('col_space', 0)",
"new_image except: pass def manual(): raw = ImageAsset.get('manual') if raw: return raw row_space",
"labels = options['labels'] for r in range(row_num): for c in range(col_num): if r",
"label_height) * row_num + row_num * row_space, ), (255, 255, 255)) draw =",
"32), Image.ANTIALIAS) else: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((32, 32), Image.ANTIALIAS)",
"im_o = bg_image_gen(num, f'底图 {num}') im_o = im_o.resize((BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT)) box = (i %",
"frame = Image.open(os.path.join(globals.asset_resource_path, f'card-{rarity}.png')) back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon, (0, 0), mask=band_icon) back_image.paste(attribute_icon,",
"draw.text(( len(image_group) * c * box_width + (len(image_group) * box_width - sz[0]) //",
"and options['image_style'].get('height'): box_width, box_height = options['image_style']['width'], options['image_style']['height'] images = [[im.resize((box_width, box_height)) for im",
"= images[0] if not isinstance(first_image, Image.Image): if isinstance(first_image, (list, tuple)): first_image = first_image[0]",
"i, im in enumerate(image_group): back_image.paste(im, ( (len(image_group) * c + i) * box_width",
"star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((32, 32), Image.ANTIALIAS) if rarity == 1: frame = Image.open(os.path.join(globals.asset_resource_path,",
"255, 250), font=font) elif back_number in [f'back_{n}' for n in [50]]: real_width =",
"for f in files: if f.startswith('back_') and f.endswith('.jpg'): num = int(back_regex.findall(f)[0]) back_pic_set.add(num) cur_back_pic_nums",
"f\"{rsn}_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((32, 32), Image.ANTIALIAS) else: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_after_training.png\")}') star",
"the first image; if both assigned, will be forced to resize # width:",
"切换底图', 'xx.jpg: 图片合成', '', '以下查询功能数据来源Bestdori', '查卡 [稀有度] [颜色] [人物] [乐团] [技能类型]: 按条件筛选符合要求的卡片,同类条件取并集,不同类条件取交集。例如: 查卡",
"row_space) + box_height ), labels[r * col_num + c], fill=(0, 0, 0), font=font)",
"27 * (i + 1)), mask=star) if return_fn: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\"",
"be min(scaled value by width, 180) # label_style: # font_size: font_size of each",
"= Image.open(os.path.join(globals.asset_resource_path, f'frame-{rarity}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) back_image.paste(card, ((OUT_WIDTH - INNER_WIDTH) // 2, (OUT_HEIGHT -",
"options['image_style']['height'] images = [[im.resize((box_width, box_height)) for im in im_list] for im_list in images]",
"ICON_SIZE), Image.ANTIALIAS) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) if not trained: card =",
"'simhei.ttf'), 20) lines = [ 'ycm/有车吗: 查询车牌(来源: https://bandoristation.com/)', '底图目录: 查询底图目录(是的,不仅功能一样,连图都盗过来了,虽然还没更新。底图31,Tsugu!.jpg)', '底图+数字: 切换底图', 'xx.jpg:",
"+ c * col_space, r * (box_height + label_height + row_space) + box_height",
"[服务器]: 按id查询单卡池信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '', '以下查询功能数据来源bilibili开放的豹跳接口,慎用', '查抽卡名字 名字: 查用户名称包含该名字的玩家出的4星', ] line_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize('底图目录',",
"= Image.open(os.path.join(globals.asset_resource_path, f'card-{rarity}.png')) back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon, (0, 0), mask=band_icon) back_image.paste(attribute_icon, (180",
"im_list in images for im in im_list]) elif not options['image_style'].get('width') and options['image_style'].get('height'): images",
"row_space) )) sz = draw.textsize(labels[r * col_num + c], font=font) draw.text(( len(image_group) *",
"1) * col_space, box_height * row_num + (row_num - 1) * row_space ),",
"if f.startswith('back_') and f.endswith('.jpg'): num = int(back_regex.findall(f)[0]) back_pic_set.add(num) cur_back_pic_nums = len(back_pic_set) if cur_back_pic_nums",
"i, line in enumerate(lines): sz = draw.textsize(line, font=font) draw.text((col_space, line_pos), line, fill=(0, 0,",
"row_space (space between two rows, if labels exist, it means the space between",
"in [f'back_{n}' for n in [33]]: real_width = max(3, im_src.width // max(6, half_en_len(s))",
"[稀有度] [颜色] [人物] [乐团] [技能类型]: 按条件筛选符合要求的卡片,同类条件取并集,不同类条件取交集。例如: 查卡 4x pure ksm 分', '查卡+数字: 按id查询单卡信息',",
"Image.ANTIALIAS) else: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((32, 32), Image.ANTIALIAS) if",
"new_image = Image.new('RGBA', image.size, (255, 255, 255, 255)) new_image.paste(image, (0, 0), image) return",
"(OUT_WIDTH - RIGHT_OFFSET, TOP_OFFSET), mask=attribute_icon) for i in range(rarity): back_image.paste(star, (LEFT_OFFSET, OUT_HEIGHT -",
"for im_list in images for im in im_list]) elif not options['image_style'].get('width') and options['image_style'].get('height'):",
"* col_num + c], fill=(0, 0, 0), font=font) else: back_image = Image.new('RGB', (",
"sys.excepthook(*sys.exc_info()) return None else: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/m_{rsn}_{\"normal\" if not trained else",
"for i, line in enumerate(lines): sz = draw.textsize(line, font=font) draw.text((col_space, line_pos), line, fill=(0,",
"line: len(line)), font=font)[0] + 2 * col_space, (line_height + row_space) * len(lines)), (255,",
"255)) draw = ImageDraw.Draw(back_image) labels = options['labels'] for r in range(row_num): for c",
"row_space = 20 col_space = 50 font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), 20) lines =",
"BACK_PIC_UNIT_HEIGHT)) box = (i % BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, i // BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_HEIGHT)",
"0), font=font) else: real_width = max(3, im_src.width // max(6, half_en_len(s))) font = ImageFont.truetype(os.path.join(globals.staticpath,",
"Image.new('RGB', (BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT * (((cur_back_pic_nums - 1) // BACK_PIC_NUM_EACH_LINE) + 1)),",
"mb=None, step=10, quality=80, isabs=False): if not isabs: absinfile = os.path.join(globals.datapath, 'image', infile) else:",
"Image, ImageDraw, ImageFont from utils.Asset import ImageAsset SPACING = 5 back_regex = re.compile(r'back_([0-9]*)\\.jpg')",
"not assigned, will be min(scaled value by width, 180) # label_style: # font_size:",
"in images] box_width, box_height = max([im.size[0] for im_list in images for im in",
"分', '查卡+数字: 按id查询单卡信息', '无框+数字: 按id查询单卡无框卡面', '活动列表 [活动类型]: 按条件筛选符合要求的活动,活动类型包括“一般活动”,“竞演LIVE”或“对邦”,“挑战LIVE”或“CP”,“LIVE试炼”,“任务LIVE”', '活动+数字 [服务器]: 按id查询单活动信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '卡池列表 [卡池类型]:",
"= Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) else: card = Image.open(f'{os.path.join(globals.asset_card_path,",
"font=font) return im def get_back_pics(): raw = ImageAsset.get('back_catalogue') if raw: return raw back_pic_set",
"n in [50]]: real_width = max(3, im_src.width // max(6, half_en_len(s)) * 4 //",
"def half_en_len(s): return (len(s) + (len(s.encode(encoding='utf-8')) - len(s)) // 2) // 2 back_number",
"if return_fn: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') if",
"f'frame-1-{attribute}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) else: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-{rarity}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) back_image.paste(card, ((OUT_WIDTH -",
"to resize # width: width of each image, if not assigned, will be",
"(space between two columns) # row_space (space between two rows, if labels exist,",
"height of each image, if not assigned, will be min(scaled value by width,",
"ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), 20) lines = [ 'ycm/有车吗: 查询车牌(来源: https://bandoristation.com/)', '底图目录: 查询底图目录(是的,不仅功能一样,连图都盗过来了,虽然还没更新。底图31,Tsugu!.jpg)', '底图+数字: 切换底图',",
"else: images = [[im] for im in images] if not options.get('image_style'): box_width, box_height",
"line in enumerate(lines): sz = draw.textsize(line, font=font) draw.text((col_space, line_pos), line, fill=(0, 0, 0),",
"frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-1-{attribute}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) else: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-{rarity}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS)",
"(col_num - 1) * col_space, (box_height + label_height) * row_num + row_num *",
"label_height + row_space) + box_height ), labels[r * col_num + c], fill=(0, 0,",
"f'auto_reply/cards/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') if os.access(fn, os.R_OK): return fn try: OUT_WIDTH,",
"+ (len(image_group) * box_width - sz[0]) // 2 + c * col_space, r",
"[50]]: real_width = max(3, im_src.width // max(6, half_en_len(s)) * 4 // 5) font",
"= ImageAsset.get('manual') if raw: return raw row_space = 20 col_space = 50 font",
"5 back_regex = re.compile(r'back_([0-9]*)\\.jpg') BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT = 140, 130 BACK_PIC_NUM_EACH_LINE = 5 def",
"(box_height + label_height + row_space) + box_height ), labels[r * col_num + c],",
"star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((32, 32), Image.ANTIALIAS) else: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_after_training.png\")}') star =",
"= (i % BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, i // BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_HEIGHT) im.paste(im_o, box)",
"box_height ), labels[r * col_num + c], fill=(0, 0, 0), font=font) else: back_image",
"len(lines)), (255, 255, 255)) draw = ImageDraw.Draw(image) line_pos = row_space for i, line",
"options.get('col_space', 0) row_space = options.get('row_space', 0) if options.get('labels'): font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), options.get('label_style',",
"TOP_OFFSET, RIGHT_OFFSET, BOTTOM_OFFSET, LEFT_OFFSET = 22, 165, 20, 10 STAT_STEP = 95 back_image",
"/ 2 y = im_src.height - 2 * real_height draw.text((x, y), s, fill=(245,",
"SPACING im = Image.new('RGB', (im_src.width, im_src.height), (255, 255, 255)) im.paste(im_src) text_width = im_src.width",
"outfile if mb is None: im = Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile, quality=quality)",
"* BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT * (((cur_back_pic_nums - 1) // BACK_PIC_NUM_EACH_LINE) + 1)), (255, 255,",
"re.compile(r'back_([0-9]*)\\.jpg') BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT = 140, 130 BACK_PIC_NUM_EACH_LINE = 5 def bg_image_gen(back_number, s): def",
"draw.textsize(s, font=font) x = (text_width - sz[0]) / 2 y = 5 draw.text((x,",
"= [ 'ycm/有车吗: 查询车牌(来源: https://bandoristation.com/)', '底图目录: 查询底图目录(是的,不仅功能一样,连图都盗过来了,虽然还没更新。底图31,Tsugu!.jpg)', '底图+数字: 切换底图', 'xx.jpg: 图片合成', '', '以下查询功能数据来源Bestdori',",
"trained: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) else: card",
"= Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((32, 32), Image.ANTIALIAS) if rarity == 1: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-1-{attribute}.png'))",
"y), s, fill=(23, 0, 0), font=font) else: real_width = max(3, im_src.width // max(6,",
"thumbnail(**options): # images: a list of Image objects, or a list of lists(tuples)",
"= set() max_label_width = 0 for label in options['labels']: max_label_width = max(max_label_width, ImageDraw.Draw(Image.new('RGB',",
"// max(6, half_en_len(s)) * 4 // 5) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height",
"return back_image except: import sys sys.excepthook(*sys.exc_info()) return None else: fn = os.path.join(globals.datapath, 'image',",
"quality=quality) if quality - step < 0: break quality -= step o_size =",
"/ 2 y = im_src.height draw.text((x, y), s, fill=(23, 0, 0), font=font) return",
"o_size > mb: im = Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile, quality=quality) if quality",
"# font_size: font_size of each label # col_num (images are arranged row by",
"+ (row_num - 1) * row_space ), (255, 255, 255)) draw = ImageDraw.Draw(back_image)",
"c], fill=(0, 0, 0), font=font) else: back_image = Image.new('RGB', ( col_num * len(images[0])",
"* box_width + (col_num - 1) * col_space, (box_height + label_height) * row_num",
"+ c * col_space * int(i == len(image_group) - 1), r * (box_height",
"(box_width - im.size[0]) // 2 + c * col_space * int(i == len(image_group)",
"col_space, r * (box_height + label_height + row_space) + box_height ), labels[r *",
"files: if f.startswith('back_') and f.endswith('.jpg'): num = int(back_regex.findall(f)[0]) back_pic_set.add(num) cur_back_pic_nums = len(back_pic_set) if",
"按条件筛选符合要求的活动,活动类型包括“一般活动”,“竞演LIVE”或“对邦”,“挑战LIVE”或“CP”,“LIVE试炼”,“任务LIVE”', '活动+数字 [服务器]: 按id查询单活动信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '卡池列表 [卡池类型]: 按条件筛选符合要求的卡池,卡池类型包括“常驻”或“无期限”,“限时”或“限定”或“期间限定”,“特殊”(该条件慎加,因为没啥特别的卡池),“必4”', '卡池+数字 [服务器]: 按id查询单卡池信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '', '以下查询功能数据来源bilibili开放的豹跳接口,慎用', '查抽卡名字",
"0), mask=frame) back_image.paste(band_icon, (0, 0), mask=band_icon) back_image.paste(attribute_icon, (180 - 50, 0), mask=attribute_icon) for",
"Image.open(filename).convert('RGBA') new_image = Image.new('RGBA', image.size, (255, 255, 255, 255)) new_image.paste(image, (0, 0), image)",
"im in enumerate(image_group): back_image.paste(im, ( (len(image_group) * c + i) * box_width +",
"get_back_pics(): raw = ImageAsset.get('back_catalogue') if raw: return raw back_pic_set = set() for _,",
"'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') back_image.save(fn) return fn return back_image except:",
"= os.path.join(globals.datapath, 'image', f'auto_reply/cards/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') if os.access(fn, os.R_OK): return",
"(0, 0), image) return new_image except: pass def manual(): raw = ImageAsset.get('manual') if",
"f'{attribute}.png')) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')) if not trained: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_normal.png\")}') star",
"mask=star) if return_fn: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png')",
"be a list of Image objects, or a list of lists(tuples) of Image",
"f'{attribute}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) if not trained: card",
"+ row_num * row_space, ), (255, 255, 255)) draw = ImageDraw.Draw(back_image) labels =",
"range(rarity): back_image.paste(star, (2, 170 - 27 * (i + 1)), mask=star) if return_fn:",
"else: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) if rarity",
"STAT_STEP = 95 back_image = Image.new('RGB', (OUT_WIDTH, OUT_HEIGHT)) attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')).resize((ICON_SIZE, ICON_SIZE),",
"OUT_HEIGHT), Image.ANTIALIAS) back_image.paste(card, ((OUT_WIDTH - INNER_WIDTH) // 2, (OUT_HEIGHT - INNER_HEIGHT) // 2),",
"back_regex = re.compile(r'back_([0-9]*)\\.jpg') BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT = 140, 130 BACK_PIC_NUM_EACH_LINE = 5 def bg_image_gen(back_number,",
"50 font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), 20) lines = [ 'ycm/有车吗: 查询车牌(来源: https://bandoristation.com/)', '底图目录:",
"row_space = options.get('row_space', 0) if options.get('labels'): font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), options.get('label_style', {}).get('font_size', 20))",
"STAR_SIZE), Image.ANTIALIAS) if rarity == 1: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-1-{attribute}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) else:",
"= im_o.resize((BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT)) box = (i % BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, i // BACK_PIC_NUM_EACH_LINE",
"line_pos), line, fill=(0, 0, 0), font=font) line_pos += sz[1] + row_space return ImageAsset.image_raw(image,",
"= ImageDraw.Draw(image) line_pos = row_space for i, line in enumerate(lines): sz = draw.textsize(line,",
"if both assigned, will be forced to resize # width: width of each",
"= Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) else: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path,",
"o_size <= mb: return infile while o_size > mb: im = Image.open(absinfile) im",
"options['image_style'].get('height'): box_width, box_height = options['image_style']['width'], options['image_style']['height'] images = [[im.resize((box_width, box_height)) for im in",
"elif back_number in [f'back_{n}' for n in [50]]: real_width = max(3, im_src.width //",
"in images for im in im_list]) elif not options['image_style'].get('width') and options['image_style'].get('height'): images =",
"if cur_back_pic_nums == 0: return im = Image.new('RGB', (BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT *",
"not isabs: absinfile = os.path.join(globals.datapath, 'image', infile) else: absinfile = infile outfile =",
"box_height)) for im in im_list] for im_list in images] elif options['image_style'].get('width') and not",
"between two columns) # row_space (space between two rows, if labels exist, it",
"= Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((32, 32), Image.ANTIALIAS) if rarity == 1:",
"+ row_space) + box_height ), labels[r * col_num + c], fill=(0, 0, 0),",
"objects') else: raise Exception('images must be a list of Image objects, or a",
"col_space, box_height * row_num + (row_num - 1) * row_space ), (255, 255,",
"if rarity == 1: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-1-{attribute}.png')) else: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-{rarity}.png'))",
"len(images[0]) * box_width + (col_num - 1) * col_space, (box_height + label_height) *",
"Image objects, or a list of lists(tuples) of Image objects') else: raise Exception('images",
"= os.path.getsize(absinfile) / 1024 if o_size <= mb: return infile while o_size >",
"set() max_label_width = 0 for label in options['labels']: max_label_width = max(max_label_width, ImageDraw.Draw(Image.new('RGB', (0,",
"label_height + row_space) )) sz = draw.textsize(labels[r * col_num + c], font=font) draw.text((",
"font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), 20) lines = [ 'ycm/有车吗: 查询车牌(来源: https://bandoristation.com/)', '底图目录: 查询底图目录(是的,不仅功能一样,连图都盗过来了,虽然还没更新。底图31,Tsugu!.jpg)',",
"between the label of row1 and the image of row2) images = options['images']",
"or a list of lists(tuples) of Image objects') else: images = [[im] for",
"row_space for i, line in enumerate(lines): sz = draw.textsize(line, font=font) draw.text((col_space, line_pos), line,",
"im = Image.new('RGB', (im_src.width, im_src.height), (255, 255, 255)) im.paste(im_src) text_width = im_src.width draw",
"255, 255)) new_image.paste(image, (0, 0), image) return new_image except: pass def manual(): raw",
"* box_width + (col_num - 1) * col_space, box_height * row_num + (row_num",
"a list of lists(tuples) of Image objects') else: images = [[im] for im",
"pass def manual(): raw = ImageAsset.get('manual') if raw: return raw row_space = 20",
"n in [38, 46, 47, 51, 52, 53]]: real_width = max(3, im_src.width //",
"images] elif options['image_style'].get('width') and not options['image_style'].get('height'): images = [[im.resize((options['image_style']['width'], options['image_style']['width'] * im.size[1] //",
"1 col_space = options.get('col_space', 0) row_space = options.get('row_space', 0) if options.get('labels'): font =",
"= im_src.height - real_height draw.text((x, y), s, fill=(245, 255, 250), font=font) elif back_number",
"(line_height + row_space) * len(lines)), (255, 255, 255)) draw = ImageDraw.Draw(image) line_pos =",
"im in im_list]), options['image_style']['height'] col_num = options.get('col_num', 4) row_num = (len(images) - 1)",
"options['image_style'].get('width') and options['image_style'].get('height'): box_width, box_height = options['image_style']['width'], options['image_style']['height'] images = [[im.resize((box_width, box_height)) for",
"f\"{rsn}_card_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) if rarity == 1: frame =",
"= Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) if not trained: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_normal.png\")}') star",
"52, 53]]: real_width = max(3, im_src.width // max(6, half_en_len(s)) * 4 // 5)",
"options['image_style'].get('width') and options['image_style'].get('height'): images = [[im.resize((options['image_style']['height'] * im.size[0] // im.size[1], options['image_style']['height'])) for im",
"if not assigned, will be min(scaled value by height, 180) # height: height",
"for r in range(row_num): for c in range(col_num): if r * col_num +",
"* col_space * int(i == len(image_group) - 1), r * (box_height + row_space)",
"params of the first image; if both assigned, will be forced to resize",
"ImageDraw, ImageFont from utils.Asset import ImageAsset SPACING = 5 back_regex = re.compile(r'back_([0-9]*)\\.jpg') BACK_PIC_UNIT_WIDTH,",
"real_width = max(3, im_src.width // max(6, half_en_len(s)) * 4 // 5) font =",
"0) row_space = options.get('row_space', 0) if options.get('labels'): font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), options.get('label_style', {}).get('font_size',",
"= 22, 165, 20, 10 STAT_STEP = 95 back_image = Image.new('RGB', (OUT_WIDTH, OUT_HEIGHT))",
"if not isinstance(first_image, Image.Image): if isinstance(first_image, (list, tuple)): first_image = first_image[0] if not",
"font=font)[1] box_width = max(box_width * len(images[0]), max_label_width) // len(images[0]) back_image = Image.new('RGB', (",
"max([im.size[1] for im_list in images for im in im_list]) elif not options['image_style'].get('width') and",
"- im.size[0]) // 2 + c * col_space * int(i == len(image_group) -",
"- 1) * row_space ), (255, 255, 255)) draw = ImageDraw.Draw(back_image) for r",
"images] if not options.get('image_style'): box_width, box_height = first_image.size else: if options['image_style'].get('width') and options['image_style'].get('height'):",
"20)) all_chars = set() max_label_width = 0 for label in options['labels']: max_label_width =",
"col_space = 50 font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), 20) lines = [ 'ycm/有车吗: 查询车牌(来源:",
"f'back_{back_number}' img_path = os.path.join(globals.staticpath, f'bg/{back_number}.jpg') im_src = Image.open(img_path) if back_number in [f'back_{n}' for",
"if os.access(fn, os.R_OK): return fn attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png'))",
"if not isinstance(first_image, Image.Image): raise Exception('images must be a list of Image objects,",
"im = Image.new('RGB', (BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT * (((cur_back_pic_nums - 1) // BACK_PIC_NUM_EACH_LINE)",
"(0, 0))).textsize(label, font=font)[0]) all_chars |= set(label) label_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(''.join(all_chars), font=font)[1] box_width",
"os import re import uuid import globals from PIL import Image, ImageDraw, ImageFont",
"uuid import globals from PIL import Image, ImageDraw, ImageFont from utils.Asset import ImageAsset",
"real_width + SPACING im = Image.new('RGB', (im_src.width, im_src.height), (255, 255, 255)) im.paste(im_src) text_width",
"- 1) * col_space, box_height * row_num + (row_num - 1) * row_space",
"f'card-1-{attribute}.png')) else: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-{rarity}.png')) back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon, (0, 0),",
"white_padding(width, height): return Image.new('RGB', (width, height), (255, 255, 255)) def thumbnail(**options): # images:",
"y = im_src.height - 2 * real_height draw.text((x, y), s, fill=(245, 255, 250),",
"if thumbnail: try: if return_fn: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained",
"first_image.size else: if options['image_style'].get('width') and options['image_style'].get('height'): box_width, box_height = options['image_style']['width'], options['image_style']['height'] images =",
"attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) if",
"255, 255)) draw = ImageDraw.Draw(image) line_pos = row_space for i, line in enumerate(lines):",
"+ 1 col_space = options.get('col_space', 0) row_space = options.get('row_space', 0) if options.get('labels'): font",
"STAR_SIZE), Image.ANTIALIAS) else: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS)",
"back_image = Image.new('RGB', (OUT_WIDTH, OUT_HEIGHT)) attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) band_icon =",
"def thumbnail(**options): # images: a list of Image objects, or a list of",
"1) // BACK_PIC_NUM_EACH_LINE) + 1)), (255, 255, 255)) for i, num in enumerate(back_pic_set):",
"= 50 font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), 20) lines = [ 'ycm/有车吗: 查询车牌(来源: https://bandoristation.com/)',",
"(0, 0), mask=frame) back_image.paste(band_icon, (0, 0), mask=band_icon) back_image.paste(attribute_icon, (180 - 50, 0), mask=attribute_icon)",
"back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon, (0, 0), mask=band_icon) back_image.paste(attribute_icon, (180 - 50, 0),",
"= options.get('row_space', 0) if options.get('labels'): font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), options.get('label_style', {}).get('font_size', 20)) all_chars",
"return infile while o_size > mb: im = Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile,",
"ksm 分', '查卡+数字: 按id查询单卡信息', '无框+数字: 按id查询单卡无框卡面', '活动列表 [活动类型]: 按条件筛选符合要求的活动,活动类型包括“一般活动”,“竞演LIVE”或“对邦”,“挑战LIVE”或“CP”,“LIVE试炼”,“任务LIVE”', '活动+数字 [服务器]: 按id查询单活动信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '卡池列表",
"OUT_WIDTH, OUT_HEIGHT = 1364, 1020 INNER_WIDTH, INNER_HEIGHT = 1334, 1002 STAR_SIZE, ICON_SIZE =",
"'以下查询功能数据来源bilibili开放的豹跳接口,慎用', '查抽卡名字 名字: 查用户名称包含该名字的玩家出的4星', ] line_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize('底图目录', font=font)[1] image =",
"if labels exist, it means the space between the label of row1 and",
"'卡池列表 [卡池类型]: 按条件筛选符合要求的卡池,卡池类型包括“常驻”或“无期限”,“限时”或“限定”或“期间限定”,“特殊”(该条件慎加,因为没啥特别的卡池),“必4”', '卡池+数字 [服务器]: 按id查询单卡池信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '', '以下查询功能数据来源bilibili开放的豹跳接口,慎用', '查抽卡名字 名字: 查用户名称包含该名字的玩家出的4星', ] line_height",
"label of row1 and the image of row2) images = options['images'] first_image =",
"* (((cur_back_pic_nums - 1) // BACK_PIC_NUM_EACH_LINE) + 1)), (255, 255, 255)) for i,",
"image, if not assigned, will be min(scaled value by width, 180) # label_style:",
"Image.ANTIALIAS) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) if not trained: card = Image.open(f'{os.path.join(globals.asset_card_path,",
"= (len(images) - 1) // col_num + 1 col_space = options.get('col_space', 0) row_space",
"0), font=font) else: back_image = Image.new('RGB', ( col_num * len(images[0]) * box_width +",
"raw = ImageAsset.get('manual') if raw: return raw row_space = 20 col_space = 50",
"im_list in images] box_width, box_height = max([im.size[0] for im_list in images for im",
"255)) draw = ImageDraw.Draw(back_image) for r in range(row_num): for c in range(col_num): if",
"+ i) * box_width + (box_width - im.size[0]) // 2 + col_space *",
"r * (box_height + row_space) )) return ImageAsset.image_raw(back_image) def open_nontransparent(filename): try: image =",
"range(rarity): back_image.paste(star, (LEFT_OFFSET, OUT_HEIGHT - BOTTOM_OFFSET - STAT_STEP * (i + 1)), mask=star)",
"fill=(0, 0, 0), font=font) line_pos += sz[1] + row_space return ImageAsset.image_raw(image, 'manual') def",
"the space between the label of row1 and the image of row2) images",
"Image.new('RGB', (im_src.width, im_src.height + real_height), (255, 255, 255)) im.paste(im_src) text_width = im_src.width draw",
"= Image.new('RGB', (ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(max(lines, key=lambda line: len(line)), font=font)[0] + 2 * col_space,",
"f'bg/{back_number}.jpg') im_src = Image.open(img_path) if back_number in [f'back_{n}' for n in [38, 46,",
"in images] if not options.get('image_style'): box_width, box_height = first_image.size else: if options['image_style'].get('width') and",
"\"after_training\"}.png') if os.access(fn, os.R_OK): return fn attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')) band_icon = Image.open(os.path.join(globals.asset_resource_path,",
"y = im_src.height - real_height draw.text((x, y), s, fill=(245, 255, 250), font=font) elif",
"(text_width - sz[0]) / 2 y = 5 draw.text((x, y), s, fill=(23, 0,",
"查询底图目录(是的,不仅功能一样,连图都盗过来了,虽然还没更新。底图31,Tsugu!.jpg)', '底图+数字: 切换底图', 'xx.jpg: 图片合成', '', '以下查询功能数据来源Bestdori', '查卡 [稀有度] [颜色] [人物] [乐团] [技能类型]:",
"// 2 + col_space * c, r * (box_height + label_height + row_space)",
"- 27 * (i + 1)), mask=star) if return_fn: fn = os.path.join(globals.datapath, 'image',",
"set() for _, _, files in os.walk(os.path.join(globals.staticpath, 'bg')): for f in files: if",
"arranged row by row) # col_space: (space between two columns) # row_space (space",
"elif options['image_style'].get('width') and not options['image_style'].get('height'): images = [[im.resize((options['image_style']['width'], options['image_style']['width'] * im.size[1] // im.size[0]))",
"line_pos = row_space for i, line in enumerate(lines): sz = draw.textsize(line, font=font) draw.text((col_space,",
"+ 1:infile.rfind('.')] + '-c.jpg' absoutfile = os.path.join(globals.datapath, 'image', outfile) if os.path.exists(absoutfile): return outfile",
"draw.text((x, y), s, fill=(245, 255, 250), font=font) elif back_number in [f'back_{n}' for n",
"> mb: im = Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile, quality=quality) if quality -",
"forced to resize # width: width of each image, if not assigned, will",
"not assigned, take the params of the first image; if both assigned, will",
"0, 0), font=font) line_pos += sz[1] + row_space return ImageAsset.image_raw(image, 'manual') def compress(infile,",
"im in im_list] for im_list in images] elif options['image_style'].get('width') and not options['image_style'].get('height'): images",
"[卡池类型]: 按条件筛选符合要求的卡池,卡池类型包括“常驻”或“无期限”,“限时”或“限定”或“期间限定”,“特殊”(该条件慎加,因为没啥特别的卡池),“必4”', '卡池+数字 [服务器]: 按id查询单卡池信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '', '以下查询功能数据来源bilibili开放的豹跳接口,慎用', '查抽卡名字 名字: 查用户名称包含该名字的玩家出的4星', ] line_height =",
"of Image objects, or a list of lists(tuples) of Image objects # labels:",
"for n in [38, 46, 47, 51, 52, 53]]: real_width = max(3, im_src.width",
"+ row_space) * len(lines)), (255, 255, 255)) draw = ImageDraw.Draw(image) line_pos = row_space",
"half_en_len(s): return (len(s) + (len(s.encode(encoding='utf-8')) - len(s)) // 2) // 2 back_number =",
"tuple)): first_image = first_image[0] if not isinstance(first_image, Image.Image): raise Exception('images must be a",
"+ i) * box_width + (box_width - im.size[0]) // 2 + c *",
"def merge_image(rsn, rarity, attribute, band_id, thumbnail=True, trained=False, return_fn=False): if thumbnail: try: if return_fn:",
"mb is None: im = Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile, quality=quality) return absoutfile",
"sz[0]) / 2 y = im_src.height draw.text((x, y), s, fill=(23, 0, 0), font=font)",
"\"after_training\"}.png') if os.access(fn, os.R_OK): return fn try: OUT_WIDTH, OUT_HEIGHT = 1364, 1020 INNER_WIDTH,",
"im in im_list] for im_list in images] box_width, box_height = options['image_style']['width'], max([im.size[1] for",
"im.size[0] // im.size[1], options['image_style']['height'])) for im in im_list] for im_list in images] box_width,",
"Image.open(os.path.join(globals.asset_resource_path, f'card-{rarity}.png')) back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon, (0, 0), mask=band_icon) back_image.paste(attribute_icon, (180 -",
"os.path.join(globals.datapath, 'image', f'auto_reply/cards/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') if os.access(fn, os.R_OK): return fn",
"label_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(''.join(all_chars), font=font)[1] box_width = max(box_width * len(images[0]), max_label_width) //",
"'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') if os.access(fn, os.R_OK): return fn attribute_icon",
"s, fill=(23, 0, 0), font=font) else: real_width = max(3, im_src.width // max(6, half_en_len(s)))",
"(LEFT_OFFSET, TOP_OFFSET), mask=band_icon) back_image.paste(attribute_icon, (OUT_WIDTH - RIGHT_OFFSET, TOP_OFFSET), mask=attribute_icon) for i in range(rarity):",
"STAT_STEP * (i + 1)), mask=star) back_image.save(fn) return fn except: return '' def",
"os.R_OK): return fn try: OUT_WIDTH, OUT_HEIGHT = 1364, 1020 INNER_WIDTH, INNER_HEIGHT = 1334,",
"font=font) draw.text(( len(image_group) * c * box_width + (len(image_group) * box_width - sz[0])",
"return_fn=False): if thumbnail: try: if return_fn: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not",
"os.path.exists(absoutfile): return outfile if mb is None: im = Image.open(absinfile) im = im.convert('RGB')",
"(i % BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, i // BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_HEIGHT) im.paste(im_o, box) return",
"* (box_height + label_height + row_space) + box_height ), labels[r * col_num +",
"font=font) x = (text_width - sz[0]) / 2 y = im_src.height draw.text((x, y),",
"options['image_style']['height'] col_num = options.get('col_num', 4) row_num = (len(images) - 1) // col_num +",
"'ycm/有车吗: 查询车牌(来源: https://bandoristation.com/)', '底图目录: 查询底图目录(是的,不仅功能一样,连图都盗过来了,虽然还没更新。底图31,Tsugu!.jpg)', '底图+数字: 切换底图', 'xx.jpg: 图片合成', '', '以下查询功能数据来源Bestdori', '查卡 [稀有度]",
"i in range(rarity): back_image.paste(star, (2, 170 - 27 * (i + 1)), mask=star)",
"+ box_height ), labels[r * col_num + c], fill=(0, 0, 0), font=font) else:",
"for n in [50]]: real_width = max(3, im_src.width // max(6, half_en_len(s)) * 4",
"SPACING im = Image.new('RGB', (im_src.width, im_src.height + real_height), (255, 255, 255)) im.paste(im_src) text_width",
"[活动类型]: 按条件筛选符合要求的活动,活动类型包括“一般活动”,“竞演LIVE”或“对邦”,“挑战LIVE”或“CP”,“LIVE试炼”,“任务LIVE”', '活动+数字 [服务器]: 按id查询单活动信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '卡池列表 [卡池类型]: 按条件筛选符合要求的卡池,卡池类型包括“常驻”或“无期限”,“限时”或“限定”或“期间限定”,“特殊”(该条件慎加,因为没啥特别的卡池),“必4”', '卡池+数字 [服务器]: 按id查询单卡池信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '', '以下查询功能数据来源bilibili开放的豹跳接口,慎用',",
"- im.size[0]) // 2 + col_space * c, r * (box_height + label_height",
"'xx.jpg: 图片合成', '', '以下查询功能数据来源Bestdori', '查卡 [稀有度] [颜色] [人物] [乐团] [技能类型]: 按条件筛选符合要求的卡片,同类条件取并集,不同类条件取交集。例如: 查卡 4x",
"x = (text_width - sz[0]) / 2 y = 5 draw.text((x, y), s,",
"Image.Image): raise Exception('images must be a list of Image objects, or a list",
"2 y = 5 draw.text((x, y), s, fill=(23, 0, 0), font=font) else: real_width",
"* col_num + c] for i, im in enumerate(image_group): back_image.paste(im, ( (len(image_group) *",
"real_height = real_width + SPACING im = Image.new('RGB', (im_src.width, im_src.height), (255, 255, 255))",
"fill=(23, 0, 0), font=font) return im def get_back_pics(): raw = ImageAsset.get('back_catalogue') if raw:",
"(255, 255, 255)) draw = ImageDraw.Draw(image) line_pos = row_space for i, line in",
"import re import uuid import globals from PIL import Image, ImageDraw, ImageFont from",
"= max(box_width * len(images[0]), max_label_width) // len(images[0]) back_image = Image.new('RGB', ( col_num *",
"will be forced to resize # width: width of each image, if not",
"else: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') if os.access(fn,",
"for im in im_list] for im_list in images] box_width, box_height = max([im.size[0] for",
"of lists(tuples) of Image objects # labels: a list of strings shown at",
"os.path.join(globals.staticpath, f'bg/{back_number}.jpg') im_src = Image.open(img_path) if back_number in [f'back_{n}' for n in [38,",
"def open_nontransparent(filename): try: image = Image.open(filename).convert('RGBA') new_image = Image.new('RGBA', image.size, (255, 255, 255,",
"image_style: if not assigned, take the params of the first image; if both",
"isabs: absinfile = os.path.join(globals.datapath, 'image', infile) else: absinfile = infile outfile = infile[infile.rfind('/')",
"< 0: break quality -= step o_size = os.path.getsize(absoutfile) / 1024 return absoutfile",
"= im.convert('RGB') im.save(absoutfile, quality=quality) if quality - step < 0: break quality -=",
"Image.ANTIALIAS) if rarity == 1: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-1-{attribute}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) else: frame",
"* col_space, (line_height + row_space) * len(lines)), (255, 255, 255)) draw = ImageDraw.Draw(image)",
"columns) # row_space (space between two rows, if labels exist, it means the",
"= ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), 20) lines = [ 'ycm/有车吗: 查询车牌(来源: https://bandoristation.com/)', '底图目录: 查询底图目录(是的,不仅功能一样,连图都盗过来了,虽然还没更新。底图31,Tsugu!.jpg)', '底图+数字:",
"elif not options['image_style'].get('width') and options['image_style'].get('height'): images = [[im.resize((options['image_style']['height'] * im.size[0] // im.size[1], options['image_style']['height']))",
"len(image_group) - 1), r * (box_height + row_space) )) return ImageAsset.image_raw(back_image) def open_nontransparent(filename):",
"+ SPACING im = Image.new('RGB', (im_src.width, im_src.height), (255, 255, 255)) im.paste(im_src) text_width =",
"back_image.paste(card, ((OUT_WIDTH - INNER_WIDTH) // 2, (OUT_HEIGHT - INNER_HEIGHT) // 2), mask=card) back_image.paste(frame,",
"font=font) draw.text((col_space, line_pos), line, fill=(0, 0, 0), font=font) line_pos += sz[1] + row_space",
"col_num + 1 col_space = options.get('col_space', 0) row_space = options.get('row_space', 0) if options.get('labels'):",
"'-c.jpg' absoutfile = os.path.join(globals.datapath, 'image', outfile) if os.path.exists(absoutfile): return outfile if mb is",
"col_num = options.get('col_num', 4) row_num = (len(images) - 1) // col_num + 1",
"Exception('images must be a list of Image objects, or a list of lists(tuples)",
"quality=quality) return absoutfile o_size = os.path.getsize(absinfile) / 1024 if o_size <= mb: return",
"* box_width + (box_width - im.size[0]) // 2 + col_space * c, r",
"(im_src.width, im_src.height), (255, 255, 255)) im.paste(im_src) text_width = im_src.width draw = ImageDraw.Draw(im) sz",
"by row) # col_space: (space between two columns) # row_space (space between two",
"font=font)[1] image = Image.new('RGB', (ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(max(lines, key=lambda line: len(line)), font=font)[0] + 2",
"infile outfile = infile[infile.rfind('/') + 1:infile.rfind('.')] + '-c.jpg' absoutfile = os.path.join(globals.datapath, 'image', outfile)",
"(len(s.encode(encoding='utf-8')) - len(s)) // 2) // 2 back_number = f'back_{back_number}' img_path = os.path.join(globals.staticpath,",
"[[im.resize((options['image_style']['width'], options['image_style']['width'] * im.size[1] // im.size[0])) for im in im_list] for im_list in",
"star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) else: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_after_training.png\")}') star =",
"image, if not assigned, will be min(scaled value by height, 180) # height:",
"Image.Image): if isinstance(first_image, (list, tuple)): first_image = first_image[0] if not isinstance(first_image, Image.Image): raise",
"must be a list of Image objects, or a list of lists(tuples) of",
"im_list]), options['image_style']['height'] col_num = options.get('col_num', 4) row_num = (len(images) - 1) // col_num",
"os.access(fn, os.R_OK): return fn try: OUT_WIDTH, OUT_HEIGHT = 1364, 1020 INNER_WIDTH, INNER_HEIGHT =",
"= options['image_style']['width'], max([im.size[1] for im_list in images for im in im_list]) elif not",
"int(back_regex.findall(f)[0]) back_pic_set.add(num) cur_back_pic_nums = len(back_pic_set) if cur_back_pic_nums == 0: return im = Image.new('RGB',",
"list of Image objects, or a list of lists(tuples) of Image objects #",
"infile) else: absinfile = infile outfile = infile[infile.rfind('/') + 1:infile.rfind('.')] + '-c.jpg' absoutfile",
"not options.get('image_style'): box_width, box_height = first_image.size else: if options['image_style'].get('width') and options['image_style'].get('height'): box_width, box_height",
"(255, 255, 255)) for i, num in enumerate(back_pic_set): im_o = bg_image_gen(num, f'底图 {num}')",
"+= sz[1] + row_space return ImageAsset.image_raw(image, 'manual') def compress(infile, mb=None, step=10, quality=80, isabs=False):",
"= Image.new('RGBA', image.size, (255, 255, 255, 255)) new_image.paste(image, (0, 0), image) return new_image",
"= Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((32, 32), Image.ANTIALIAS) else: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path,",
"draw.textsize(line, font=font) draw.text((col_space, line_pos), line, fill=(0, 0, 0), font=font) line_pos += sz[1] +",
"draw = ImageDraw.Draw(back_image) labels = options['labels'] for r in range(row_num): for c in",
"line, fill=(0, 0, 0), font=font) line_pos += sz[1] + row_space return ImageAsset.image_raw(image, 'manual')",
"= infile[infile.rfind('/') + 1:infile.rfind('.')] + '-c.jpg' absoutfile = os.path.join(globals.datapath, 'image', outfile) if os.path.exists(absoutfile):",
"s, fill=(245, 255, 250), font=font) elif back_number in [f'back_{n}' for n in [50]]:",
"in enumerate(image_group): back_image.paste(im, ( (len(image_group) * c + i) * box_width + (box_width",
"[f'back_{n}' for n in [50]]: real_width = max(3, im_src.width // max(6, half_en_len(s)) *",
"for im_list in images for im in im_list]), options['image_style']['height'] col_num = options.get('col_num', 4)",
"ImageAsset.image_raw(back_image) def open_nontransparent(filename): try: image = Image.open(filename).convert('RGBA') new_image = Image.new('RGBA', image.size, (255, 255,",
"/ 1024 if o_size <= mb: return infile while o_size > mb: im",
"+ 1)), (255, 255, 255)) for i, num in enumerate(back_pic_set): im_o = bg_image_gen(num,",
"options['image_style']['width'], options['image_style']['height'] images = [[im.resize((box_width, box_height)) for im in im_list] for im_list in",
"merge_image(rsn, rarity, attribute, band_id, thumbnail=True, trained=False, return_fn=False): if thumbnail: try: if return_fn: fn",
"{num}') im_o = im_o.resize((BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT)) box = (i % BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, i",
"== 0: return im = Image.new('RGB', (BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT * (((cur_back_pic_nums -",
"'无框+数字: 按id查询单卡无框卡面', '活动列表 [活动类型]: 按条件筛选符合要求的活动,活动类型包括“一般活动”,“竞演LIVE”或“对邦”,“挑战LIVE”或“CP”,“LIVE试炼”,“任务LIVE”', '活动+数字 [服务器]: 按id查询单活动信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '卡池列表 [卡池类型]: 按条件筛选符合要求的卡池,卡池类型包括“常驻”或“无期限”,“限时”或“限定”或“期间限定”,“特殊”(该条件慎加,因为没啥特别的卡池),“必4”', '卡池+数字 [服务器]:",
"名字: 查用户名称包含该名字的玩家出的4星', ] line_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize('底图目录', font=font)[1] image = Image.new('RGB', (ImageDraw.Draw(Image.new('RGB',",
"first image; if both assigned, will be forced to resize # width: width",
"0), font=font) return im def get_back_pics(): raw = ImageAsset.get('back_catalogue') if raw: return raw",
"options.get('row_space', 0) if options.get('labels'): font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), options.get('label_style', {}).get('font_size', 20)) all_chars =",
"im = Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile, quality=quality) if quality - step <",
"ImageAsset.get('manual') if raw: return raw row_space = 20 col_space = 50 font =",
"max_label_width) // len(images[0]) back_image = Image.new('RGB', ( col_num * len(images[0]) * box_width +",
"250), font=font) elif back_number in [f'back_{n}' for n in [33]]: real_width = max(3,",
"width of each image, if not assigned, will be min(scaled value by height,",
"font=font) elif back_number in [f'back_{n}' for n in [33]]: real_width = max(3, im_src.width",
"return None else: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png')",
"'simhei.ttf'), real_width) real_height = real_width + SPACING im = Image.new('RGB', (im_src.width, im_src.height), (255,",
"draw = ImageDraw.Draw(back_image) for r in range(row_num): for c in range(col_num): if r",
"查询车牌(来源: https://bandoristation.com/)', '底图目录: 查询底图目录(是的,不仅功能一样,连图都盗过来了,虽然还没更新。底图31,Tsugu!.jpg)', '底图+数字: 切换底图', 'xx.jpg: 图片合成', '', '以下查询功能数据来源Bestdori', '查卡 [稀有度] [颜色]",
"fn attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')) if not trained: back_image",
"col_num + c], fill=(0, 0, 0), font=font) else: back_image = Image.new('RGB', ( col_num",
"TOP_OFFSET), mask=band_icon) back_image.paste(attribute_icon, (OUT_WIDTH - RIGHT_OFFSET, TOP_OFFSET), mask=attribute_icon) for i in range(rarity): back_image.paste(star,",
"= Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile, quality=quality) return absoutfile o_size = os.path.getsize(absinfile) /",
"= max(max_label_width, ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(label, font=font)[0]) all_chars |= set(label) label_height = ImageDraw.Draw(Image.new('RGB', (0,",
"_, _, files in os.walk(os.path.join(globals.staticpath, 'bg')): for f in files: if f.startswith('back_') and",
"= set() for _, _, files in os.walk(os.path.join(globals.staticpath, 'bg')): for f in files:",
"back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((32, 32), Image.ANTIALIAS) if rarity ==",
"if os.access(fn, os.R_OK): return fn try: OUT_WIDTH, OUT_HEIGHT = 1364, 1020 INNER_WIDTH, INNER_HEIGHT",
"- step < 0: break quality -= step o_size = os.path.getsize(absoutfile) / 1024",
"for im_list in images] box_width, box_height = options['image_style']['width'], max([im.size[1] for im_list in images",
"first_image = first_image[0] if not isinstance(first_image, Image.Image): raise Exception('images must be a list",
"im in im_list] for im_list in images] box_width, box_height = max([im.size[0] for im_list",
"* BACK_PIC_UNIT_WIDTH, i // BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_HEIGHT) im.paste(im_o, box) return ImageAsset.image_raw(im, 'back_catalogue') def",
"Image.new('RGB', (OUT_WIDTH, OUT_HEIGHT)) attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')).resize((ICON_SIZE,",
"back_image.paste(band_icon, (LEFT_OFFSET, TOP_OFFSET), mask=band_icon) back_image.paste(attribute_icon, (OUT_WIDTH - RIGHT_OFFSET, TOP_OFFSET), mask=attribute_icon) for i in",
"two rows, if labels exist, it means the space between the label of",
"min(scaled value by height, 180) # height: height of each image, if not",
"'查卡+数字: 按id查询单卡信息', '无框+数字: 按id查询单卡无框卡面', '活动列表 [活动类型]: 按条件筛选符合要求的活动,活动类型包括“一般活动”,“竞演LIVE”或“对邦”,“挑战LIVE”或“CP”,“LIVE试炼”,“任务LIVE”', '活动+数字 [服务器]: 按id查询单活动信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '卡池列表 [卡池类型]: 按条件筛选符合要求的卡池,卡池类型包括“常驻”或“无期限”,“限时”或“限定”或“期间限定”,“特殊”(该条件慎加,因为没啥特别的卡池),“必4”',",
"Image.ANTIALIAS) back_image.paste(card, ((OUT_WIDTH - INNER_WIDTH) // 2, (OUT_HEIGHT - INNER_HEIGHT) // 2), mask=card)",
"back_image.paste(attribute_icon, (180 - 50, 0), mask=attribute_icon) for i in range(rarity): back_image.paste(star, (2, 170",
"fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') back_image.save(fn) return fn",
"absinfile = os.path.join(globals.datapath, 'image', infile) else: absinfile = infile outfile = infile[infile.rfind('/') +",
"back_pic_set = set() for _, _, files in os.walk(os.path.join(globals.staticpath, 'bg')): for f in",
"else \"after_training\"}.png') if os.access(fn, os.R_OK): return fn attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')) band_icon =",
"back_image.save(fn) return fn except: return '' def white_padding(width, height): return Image.new('RGB', (width, height),",
"0), image) return new_image except: pass def manual(): raw = ImageAsset.get('manual') if raw:",
"return_fn: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') if os.access(fn,",
"查卡 4x pure ksm 分', '查卡+数字: 按id查询单卡信息', '无框+数字: 按id查询单卡无框卡面', '活动列表 [活动类型]: 按条件筛选符合要求的活动,活动类型包括“一般活动”,“竞演LIVE”或“对邦”,“挑战LIVE”或“CP”,“LIVE试炼”,“任务LIVE”', '活动+数字",
"by height, 180) # height: height of each image, if not assigned, will",
"* box_width + (box_width - im.size[0]) // 2 + c * col_space *",
"star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) if rarity == 1: frame = Image.open(os.path.join(globals.asset_resource_path,",
"+ label_height + row_space) + box_height ), labels[r * col_num + c], fill=(0,",
"(images are arranged row by row) # col_space: (space between two columns) #",
"按条件筛选符合要求的卡片,同类条件取并集,不同类条件取交集。例如: 查卡 4x pure ksm 分', '查卡+数字: 按id查询单卡信息', '无框+数字: 按id查询单卡无框卡面', '活动列表 [活动类型]: 按条件筛选符合要求的活动,活动类型包括“一般活动”,“竞演LIVE”或“对邦”,“挑战LIVE”或“CP”,“LIVE试炼”,“任务LIVE”',",
"be min(scaled value by height, 180) # height: height of each image, if",
"- INNER_WIDTH) // 2, (OUT_HEIGHT - INNER_HEIGHT) // 2), mask=card) back_image.paste(frame, (0, 0),",
"180) # label_style: # font_size: font_size of each label # col_num (images are",
"= Image.new('RGB', (BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT * (((cur_back_pic_nums - 1) // BACK_PIC_NUM_EACH_LINE) +",
")) sz = draw.textsize(labels[r * col_num + c], font=font) draw.text(( len(image_group) * c",
"* BACK_PIC_UNIT_HEIGHT) im.paste(im_o, box) return ImageAsset.image_raw(im, 'back_catalogue') def merge_image(rsn, rarity, attribute, band_id, thumbnail=True,",
"# col_space: (space between two columns) # row_space (space between two rows, if",
"the label of row1 and the image of row2) images = options['images'] first_image",
"num in enumerate(back_pic_set): im_o = bg_image_gen(num, f'底图 {num}') im_o = im_o.resize((BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT)) box",
"5 draw.text((x, y), s, fill=(23, 0, 0), font=font) else: real_width = max(3, im_src.width",
"os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') back_image.save(fn) return fn return back_image",
"PIL import Image, ImageDraw, ImageFont from utils.Asset import ImageAsset SPACING = 5 back_regex",
"+ c >= len(images): break image_group = images[r * col_num + c] for",
"* box_width - sz[0]) // 2 + c * col_space, r * (box_height",
"col_num + c], font=font) draw.text(( len(image_group) * c * box_width + (len(image_group) *",
"in im_list]) elif not options['image_style'].get('width') and options['image_style'].get('height'): images = [[im.resize((options['image_style']['height'] * im.size[0] //",
"assigned, will be min(scaled value by width, 180) # label_style: # font_size: font_size",
"'star_trained.png')).resize((32, 32), Image.ANTIALIAS) if rarity == 1: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-1-{attribute}.png')) else: frame",
"mask=attribute_icon) for i in range(rarity): back_image.paste(star, (LEFT_OFFSET, OUT_HEIGHT - BOTTOM_OFFSET - STAT_STEP *",
"im.paste(im_o, box) return ImageAsset.image_raw(im, 'back_catalogue') def merge_image(rsn, rarity, attribute, band_id, thumbnail=True, trained=False, return_fn=False):",
"Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((32, 32), Image.ANTIALIAS) else: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_after_training.png\")}')",
"1002 STAR_SIZE, ICON_SIZE = 100, 150 TOP_OFFSET, RIGHT_OFFSET, BOTTOM_OFFSET, LEFT_OFFSET = 22, 165,",
"labels: a list of strings shown at the bottom # image_style: if not",
"* row_num + row_num * row_space, ), (255, 255, 255)) draw = ImageDraw.Draw(back_image)",
"0))).textsize(''.join(all_chars), font=font)[1] box_width = max(box_width * len(images[0]), max_label_width) // len(images[0]) back_image = Image.new('RGB',",
"return ImageAsset.image_raw(back_image) def open_nontransparent(filename): try: image = Image.open(filename).convert('RGBA') new_image = Image.new('RGBA', image.size, (255,",
"in range(rarity): back_image.paste(star, (LEFT_OFFSET, OUT_HEIGHT - BOTTOM_OFFSET - STAT_STEP * (i + 1)),",
"objects, or a list of lists(tuples) of Image objects') else: images = [[im]",
"else: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-{rarity}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) back_image.paste(card, ((OUT_WIDTH - INNER_WIDTH) // 2,",
"for n in [33]]: real_width = max(3, im_src.width // max(6, half_en_len(s)) * 4",
"[[im] for im in images] if not options.get('image_style'): box_width, box_height = first_image.size else:",
"32), Image.ANTIALIAS) if rarity == 1: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-1-{attribute}.png')) else: frame =",
"im = im.convert('RGB') im.save(absoutfile, quality=quality) return absoutfile o_size = os.path.getsize(absinfile) / 1024 if",
"im_list in images] elif options['image_style'].get('width') and not options['image_style'].get('height'): images = [[im.resize((options['image_style']['width'], options['image_style']['width'] *",
"images = [[im.resize((options['image_style']['width'], options['image_style']['width'] * im.size[1] // im.size[0])) for im in im_list] for",
"return ImageAsset.image_raw(im, 'back_catalogue') def merge_image(rsn, rarity, attribute, band_id, thumbnail=True, trained=False, return_fn=False): if thumbnail:",
"0), mask=attribute_icon) for i in range(rarity): back_image.paste(star, (2, 170 - 27 * (i",
"= ImageDraw.Draw(back_image) for r in range(row_num): for c in range(col_num): if r *",
"+ label_height + row_space) )) sz = draw.textsize(labels[r * col_num + c], font=font)",
"enumerate(lines): sz = draw.textsize(line, font=font) draw.text((col_space, line_pos), line, fill=(0, 0, 0), font=font) line_pos",
"value by width, 180) # label_style: # font_size: font_size of each label #",
"(len(images) - 1) // col_num + 1 col_space = options.get('col_space', 0) row_space =",
"= (text_width - sz[0]) / 2 y = im_src.height draw.text((x, y), s, fill=(23,",
"'活动列表 [活动类型]: 按条件筛选符合要求的活动,活动类型包括“一般活动”,“竞演LIVE”或“对邦”,“挑战LIVE”或“CP”,“LIVE试炼”,“任务LIVE”', '活动+数字 [服务器]: 按id查询单活动信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '卡池列表 [卡池类型]: 按条件筛选符合要求的卡池,卡池类型包括“常驻”或“无期限”,“限时”或“限定”或“期间限定”,“特殊”(该条件慎加,因为没啥特别的卡池),“必4”', '卡池+数字 [服务器]: 按id查询单卡池信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '',",
"= 5 draw.text((x, y), s, fill=(23, 0, 0), font=font) else: real_width = max(3,",
"+ '-c.jpg' absoutfile = os.path.join(globals.datapath, 'image', outfile) if os.path.exists(absoutfile): return outfile if mb",
"height): return Image.new('RGB', (width, height), (255, 255, 255)) def thumbnail(**options): # images: a",
"// im.size[0])) for im in im_list] for im_list in images] box_width, box_height =",
"= Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((32, 32), Image.ANTIALIAS) else: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path,",
"font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height = real_width + SPACING im = Image.new('RGB',",
"10 STAT_STEP = 95 back_image = Image.new('RGB', (OUT_WIDTH, OUT_HEIGHT)) attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')).resize((ICON_SIZE,",
"in images for im in im_list]), options['image_style']['height'] col_num = options.get('col_num', 4) row_num =",
"[ 'ycm/有车吗: 查询车牌(来源: https://bandoristation.com/)', '底图目录: 查询底图目录(是的,不仅功能一样,连图都盗过来了,虽然还没更新。底图31,Tsugu!.jpg)', '底图+数字: 切换底图', 'xx.jpg: 图片合成', '', '以下查询功能数据来源Bestdori', '查卡",
"of the first image; if both assigned, will be forced to resize #",
"+ 1)), mask=star) back_image.save(fn) return fn except: return '' def white_padding(width, height): return",
"sz[1] + row_space return ImageAsset.image_raw(image, 'manual') def compress(infile, mb=None, step=10, quality=80, isabs=False): if",
"absoutfile = os.path.join(globals.datapath, 'image', outfile) if os.path.exists(absoutfile): return outfile if mb is None:",
"* row_space, ), (255, 255, 255)) draw = ImageDraw.Draw(back_image) labels = options['labels'] for",
"raw back_pic_set = set() for _, _, files in os.walk(os.path.join(globals.staticpath, 'bg')): for f",
"images] box_width, box_height = options['image_style']['width'], max([im.size[1] for im_list in images for im in",
"will be min(scaled value by height, 180) # height: height of each image,",
"len(images): break image_group = images[r * col_num + c] for i, im in",
"box_width, box_height = max([im.size[0] for im_list in images for im in im_list]), options['image_style']['height']",
"if quality - step < 0: break quality -= step o_size = os.path.getsize(absoutfile)",
"95 back_image = Image.new('RGB', (OUT_WIDTH, OUT_HEIGHT)) attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) band_icon",
"in options['labels']: max_label_width = max(max_label_width, ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(label, font=font)[0]) all_chars |= set(label) label_height",
"51, 52, 53]]: real_width = max(3, im_src.width // max(6, half_en_len(s)) * 4 //",
"(OUT_WIDTH, OUT_HEIGHT)) attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')).resize((ICON_SIZE, ICON_SIZE),",
"20, 10 STAT_STEP = 95 back_image = Image.new('RGB', (OUT_WIDTH, OUT_HEIGHT)) attribute_icon = Image.open(os.path.join(globals.asset_resource_path,",
"trained else \"after_training\"}.png') if os.access(fn, os.R_OK): return fn attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')) band_icon",
"= ImageAsset.get('back_catalogue') if raw: return raw back_pic_set = set() for _, _, files",
"not isinstance(first_image, Image.Image): if isinstance(first_image, (list, tuple)): first_image = first_image[0] if not isinstance(first_image,",
"(box_height + label_height) * row_num + row_num * row_space, ), (255, 255, 255))",
"lists(tuples) of Image objects') else: raise Exception('images must be a list of Image",
"band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')) if not trained: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_normal.png\")}') star =",
"for im in im_list] for im_list in images] box_width, box_height = options['image_style']['width'], max([im.size[1]",
"images = [[im] for im in images] if not options.get('image_style'): box_width, box_height =",
"// len(images[0]) back_image = Image.new('RGB', ( col_num * len(images[0]) * box_width + (col_num",
"0), mask=band_icon) back_image.paste(attribute_icon, (180 - 50, 0), mask=attribute_icon) for i in range(rarity): back_image.paste(star,",
"* row_space ), (255, 255, 255)) draw = ImageDraw.Draw(back_image) for r in range(row_num):",
"1) // col_num + 1 col_space = options.get('col_space', 0) row_space = options.get('row_space', 0)",
"for i in range(rarity): back_image.paste(star, (2, 170 - 27 * (i + 1)),",
"ICON_SIZE), Image.ANTIALIAS) if not trained: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((STAR_SIZE,",
"'star.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) else: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((STAR_SIZE, STAR_SIZE),",
"len(images[0]), max_label_width) // len(images[0]) back_image = Image.new('RGB', ( col_num * len(images[0]) * box_width",
"sz[0]) / 2 y = im_src.height - 2 * real_height draw.text((x, y), s,",
"y = 5 draw.text((x, y), s, fill=(23, 0, 0), font=font) else: real_width =",
"130 BACK_PIC_NUM_EACH_LINE = 5 def bg_image_gen(back_number, s): def half_en_len(s): return (len(s) + (len(s.encode(encoding='utf-8'))",
"space between the label of row1 and the image of row2) images =",
"frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-{rarity}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) back_image.paste(card, ((OUT_WIDTH - INNER_WIDTH) // 2, (OUT_HEIGHT",
"(text_width - sz[0]) / 2 y = im_src.height draw.text((x, y), s, fill=(23, 0,",
"- RIGHT_OFFSET, TOP_OFFSET), mask=attribute_icon) for i in range(rarity): back_image.paste(star, (LEFT_OFFSET, OUT_HEIGHT - BOTTOM_OFFSET",
"250), font=font) elif back_number in [f'back_{n}' for n in [50]]: real_width = max(3,",
"if options.get('labels'): font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), options.get('label_style', {}).get('font_size', 20)) all_chars = set() max_label_width",
"(0, 0))).textsize('底图目录', font=font)[1] image = Image.new('RGB', (ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(max(lines, key=lambda line: len(line)), font=font)[0]",
"INNER_HEIGHT = 1334, 1002 STAR_SIZE, ICON_SIZE = 100, 150 TOP_OFFSET, RIGHT_OFFSET, BOTTOM_OFFSET, LEFT_OFFSET",
"// 2) // 2 back_number = f'back_{back_number}' img_path = os.path.join(globals.staticpath, f'bg/{back_number}.jpg') im_src =",
"back_image.save(fn) return fn return back_image except: import sys sys.excepthook(*sys.exc_info()) return None else: fn",
"if mb is None: im = Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile, quality=quality) return",
"(OUT_HEIGHT - INNER_HEIGHT) // 2), mask=card) back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon, (LEFT_OFFSET, TOP_OFFSET),",
"im_src.height - real_height draw.text((x, y), s, fill=(245, 255, 250), font=font) elif back_number in",
"2) // 2 back_number = f'back_{back_number}' img_path = os.path.join(globals.staticpath, f'bg/{back_number}.jpg') im_src = Image.open(img_path)",
"Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((32, 32), Image.ANTIALIAS) if rarity == 1: frame",
"+ (box_width - im.size[0]) // 2 + col_space * c, r * (box_height",
"lists(tuples) of Image objects') else: images = [[im] for im in images] if",
"options['image_style']['height'])) for im in im_list] for im_list in images] box_width, box_height = max([im.size[0]",
">= len(images): break image_group = images[r * col_num + c] for i, im",
"r * (box_height + label_height + row_space) )) sz = draw.textsize(labels[r * col_num",
"not trained else \"after_training\"}.png') if os.access(fn, os.R_OK): return fn attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png'))",
"[颜色] [人物] [乐团] [技能类型]: 按条件筛选符合要求的卡片,同类条件取并集,不同类条件取交集。例如: 查卡 4x pure ksm 分', '查卡+数字: 按id查询单卡信息', '无框+数字:",
"ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height = real_width + SPACING im = Image.new('RGB', (im_src.width, im_src.height),",
"BACK_PIC_UNIT_WIDTH, i // BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_HEIGHT) im.paste(im_o, box) return ImageAsset.image_raw(im, 'back_catalogue') def merge_image(rsn,",
"BACK_PIC_UNIT_HEIGHT = 140, 130 BACK_PIC_NUM_EACH_LINE = 5 def bg_image_gen(back_number, s): def half_en_len(s): return",
"box_height = max([im.size[0] for im_list in images for im in im_list]), options['image_style']['height'] col_num",
"'image', infile) else: absinfile = infile outfile = infile[infile.rfind('/') + 1:infile.rfind('.')] + '-c.jpg'",
"return fn except: return '' def white_padding(width, height): return Image.new('RGB', (width, height), (255,",
"(LEFT_OFFSET, OUT_HEIGHT - BOTTOM_OFFSET - STAT_STEP * (i + 1)), mask=star) back_image.save(fn) return",
"Image objects, or a list of lists(tuples) of Image objects # labels: a",
"for im_list in images] elif options['image_style'].get('width') and not options['image_style'].get('height'): images = [[im.resize((options['image_style']['width'], options['image_style']['width']",
"return im = Image.new('RGB', (BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT * (((cur_back_pic_nums - 1) //",
"for im in im_list] for im_list in images] elif options['image_style'].get('width') and not options['image_style'].get('height'):",
"255, 255)) def thumbnail(**options): # images: a list of Image objects, or a",
"else \"after_training\"}.png') back_image.save(fn) return fn return back_image except: import sys sys.excepthook(*sys.exc_info()) return None",
"OUT_HEIGHT), Image.ANTIALIAS) else: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-{rarity}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) back_image.paste(card, ((OUT_WIDTH - INNER_WIDTH)",
"BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT * (((cur_back_pic_nums - 1) // BACK_PIC_NUM_EACH_LINE) + 1)), (255, 255, 255))",
"if not trained: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((32, 32), Image.ANTIALIAS)",
"font_size of each label # col_num (images are arranged row by row) #",
"row_space, ), (255, 255, 255)) draw = ImageDraw.Draw(back_image) labels = options['labels'] for r",
"in [f'back_{n}' for n in [50]]: real_width = max(3, im_src.width // max(6, half_en_len(s))",
"return_fn: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') back_image.save(fn) return",
"ImageFont from utils.Asset import ImageAsset SPACING = 5 back_regex = re.compile(r'back_([0-9]*)\\.jpg') BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT",
"bg_image_gen(num, f'底图 {num}') im_o = im_o.resize((BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT)) box = (i % BACK_PIC_NUM_EACH_LINE *",
"of row2) images = options['images'] first_image = images[0] if not isinstance(first_image, Image.Image): if",
"options.get('col_num', 4) row_num = (len(images) - 1) // col_num + 1 col_space =",
"1: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-1-{attribute}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) else: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-{rarity}.png')).resize((OUT_WIDTH, OUT_HEIGHT),",
"(len(image_group) * box_width - sz[0]) // 2 + c * col_space, r *",
"2 + col_space * c, r * (box_height + label_height + row_space) ))",
"are arranged row by row) # col_space: (space between two columns) # row_space",
"((OUT_WIDTH - INNER_WIDTH) // 2, (OUT_HEIGHT - INNER_HEIGHT) // 2), mask=card) back_image.paste(frame, (0,",
"(width, height), (255, 255, 255)) def thumbnail(**options): # images: a list of Image",
"* len(images[0]), max_label_width) // len(images[0]) back_image = Image.new('RGB', ( col_num * len(images[0]) *",
"back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon, (LEFT_OFFSET, TOP_OFFSET), mask=band_icon) back_image.paste(attribute_icon, (OUT_WIDTH - RIGHT_OFFSET, TOP_OFFSET),",
"return '' def white_padding(width, height): return Image.new('RGB', (width, height), (255, 255, 255)) def",
"+ c], fill=(0, 0, 0), font=font) else: back_image = Image.new('RGB', ( col_num *",
"= infile outfile = infile[infile.rfind('/') + 1:infile.rfind('.')] + '-c.jpg' absoutfile = os.path.join(globals.datapath, 'image',",
"for i, num in enumerate(back_pic_set): im_o = bg_image_gen(num, f'底图 {num}') im_o = im_o.resize((BACK_PIC_UNIT_WIDTH,",
"box_height * row_num + (row_num - 1) * row_space ), (255, 255, 255))",
"INNER_HEIGHT) // 2), mask=card) back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon, (LEFT_OFFSET, TOP_OFFSET), mask=band_icon) back_image.paste(attribute_icon,",
"back_number in [f'back_{n}' for n in [38, 46, 47, 51, 52, 53]]: real_width",
"# row_space (space between two rows, if labels exist, it means the space",
"BACK_PIC_NUM_EACH_LINE) + 1)), (255, 255, 255)) for i, num in enumerate(back_pic_set): im_o =",
"46, 47, 51, 52, 53]]: real_width = max(3, im_src.width // max(6, half_en_len(s)) *",
"globals from PIL import Image, ImageDraw, ImageFont from utils.Asset import ImageAsset SPACING =",
"1) * row_space ), (255, 255, 255)) draw = ImageDraw.Draw(back_image) for r in",
"def bg_image_gen(back_number, s): def half_en_len(s): return (len(s) + (len(s.encode(encoding='utf-8')) - len(s)) // 2)",
"= options['labels'] for r in range(row_num): for c in range(col_num): if r *",
"box_width - sz[0]) // 2 + c * col_space, r * (box_height +",
"im_src.width draw = ImageDraw.Draw(im) sz = draw.textsize(s, font=font) x = (text_width - sz[0])",
"INNER_WIDTH) // 2, (OUT_HEIGHT - INNER_HEIGHT) // 2), mask=card) back_image.paste(frame, (0, 0), mask=frame)",
"* real_height draw.text((x, y), s, fill=(245, 255, 250), font=font) elif back_number in [f'back_{n}'",
"53]]: real_width = max(3, im_src.width // max(6, half_en_len(s)) * 4 // 5) font",
"not trained else \"after_training\"}.png') if os.access(fn, os.R_OK): return fn try: OUT_WIDTH, OUT_HEIGHT =",
"BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, i // BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_HEIGHT) im.paste(im_o, box) return ImageAsset.image_raw(im, 'back_catalogue')",
"(180 - 50, 0), mask=attribute_icon) for i in range(rarity): back_image.paste(star, (2, 170 -",
"im_list in images for im in im_list]), options['image_style']['height'] col_num = options.get('col_num', 4) row_num",
"enumerate(back_pic_set): im_o = bg_image_gen(num, f'底图 {num}') im_o = im_o.resize((BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT)) box = (i",
"band_id, thumbnail=True, trained=False, return_fn=False): if thumbnail: try: if return_fn: fn = os.path.join(globals.datapath, 'image',",
"enumerate(image_group): back_image.paste(im, ( (len(image_group) * c + i) * box_width + (box_width -",
"0))).textsize(label, font=font)[0]) all_chars |= set(label) label_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(''.join(all_chars), font=font)[1] box_width =",
"+ SPACING im = Image.new('RGB', (im_src.width, im_src.height + real_height), (255, 255, 255)) im.paste(im_src)",
"im = Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile, quality=quality) return absoutfile o_size = os.path.getsize(absinfile)",
"22, 165, 20, 10 STAT_STEP = 95 back_image = Image.new('RGB', (OUT_WIDTH, OUT_HEIGHT)) attribute_icon",
"labels[r * col_num + c], fill=(0, 0, 0), font=font) else: back_image = Image.new('RGB',",
"Image.open(os.path.join(globals.asset_resource_path, f'card-1-{attribute}.png')) else: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-{rarity}.png')) back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon, (0,",
"[33]]: real_width = max(3, im_src.width // max(6, half_en_len(s)) * 4 // 5) font",
"width: width of each image, if not assigned, will be min(scaled value by",
"of row1 and the image of row2) images = options['images'] first_image = images[0]",
"ImageDraw.Draw(image) line_pos = row_space for i, line in enumerate(lines): sz = draw.textsize(line, font=font)",
"im def get_back_pics(): raw = ImageAsset.get('back_catalogue') if raw: return raw back_pic_set = set()",
"= options['image_style']['width'], options['image_style']['height'] images = [[im.resize((box_width, box_height)) for im in im_list] for im_list",
"it means the space between the label of row1 and the image of",
"sz = draw.textsize(labels[r * col_num + c], font=font) draw.text(( len(image_group) * c *",
"of lists(tuples) of Image objects') else: raise Exception('images must be a list of",
"1:infile.rfind('.')] + '-c.jpg' absoutfile = os.path.join(globals.datapath, 'image', outfile) if os.path.exists(absoutfile): return outfile if",
"attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')) if not trained: back_image =",
"real_height draw.text((x, y), s, fill=(245, 255, 250), font=font) elif back_number in [f'back_{n}' for",
"f\"{rsn}_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((32, 32), Image.ANTIALIAS) if rarity == 1: frame =",
"font=font)[0] + 2 * col_space, (line_height + row_space) * len(lines)), (255, 255, 255))",
"Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((32, 32), Image.ANTIALIAS) else: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((32,",
"width, 180) # label_style: # font_size: font_size of each label # col_num (images",
"im.size[1], options['image_style']['height'])) for im in im_list] for im_list in images] box_width, box_height =",
"images for im in im_list]), options['image_style']['height'] col_num = options.get('col_num', 4) row_num = (len(images)",
"ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize('底图目录', font=font)[1] image = Image.new('RGB', (ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(max(lines, key=lambda line: len(line)),",
"= (text_width - sz[0]) / 2 y = im_src.height - 2 * real_height",
"f'card-{rarity}.png')) back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon, (0, 0), mask=band_icon) back_image.paste(attribute_icon, (180 - 50,",
"back_number in [f'back_{n}' for n in [33]]: real_width = max(3, im_src.width // max(6,",
"- 1), r * (box_height + row_space) )) return ImageAsset.image_raw(back_image) def open_nontransparent(filename): try:",
"Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) if not trained:",
"len(image_group) * c * box_width + (len(image_group) * box_width - sz[0]) // 2",
"else \"after_training\"}.png') if os.access(fn, os.R_OK): return fn try: OUT_WIDTH, OUT_HEIGHT = 1364, 1020",
"2 * real_height draw.text((x, y), s, fill=(245, 255, 250), font=font) elif back_number in",
"0, 0), font=font) else: real_width = max(3, im_src.width // max(6, half_en_len(s))) font =",
"first_image[0] if not isinstance(first_image, Image.Image): raise Exception('images must be a list of Image",
"options.get('label_style', {}).get('font_size', 20)) all_chars = set() max_label_width = 0 for label in options['labels']:",
"= [[im.resize((options['image_style']['width'], options['image_style']['width'] * im.size[1] // im.size[0])) for im in im_list] for im_list",
"back_image = Image.new('RGB', ( col_num * len(images[0]) * box_width + (col_num - 1)",
"compress(infile, mb=None, step=10, quality=80, isabs=False): if not isabs: absinfile = os.path.join(globals.datapath, 'image', infile)",
"options['image_style'].get('height'): images = [[im.resize((options['image_style']['height'] * im.size[0] // im.size[1], options['image_style']['height'])) for im in im_list]",
"f'底图 {num}') im_o = im_o.resize((BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT)) box = (i % BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH,",
"o_size = os.path.getsize(absinfile) / 1024 if o_size <= mb: return infile while o_size",
"bottom # image_style: if not assigned, take the params of the first image;",
"(len(image_group) * c + i) * box_width + (box_width - im.size[0]) // 2",
"1)), mask=star) if return_fn: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else",
"Image.open(os.path.join(globals.asset_resource_path, f'frame-1-{attribute}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) else: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-{rarity}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) back_image.paste(card, ((OUT_WIDTH",
"in range(rarity): back_image.paste(star, (2, 170 - 27 * (i + 1)), mask=star) if",
"* c * box_width + (len(image_group) * box_width - sz[0]) // 2 +",
"between two rows, if labels exist, it means the space between the label",
"'star.png')).resize((32, 32), Image.ANTIALIAS) else: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((32, 32),",
"Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile, quality=quality) if quality - step < 0: break",
"(row_num - 1) * row_space ), (255, 255, 255)) draw = ImageDraw.Draw(back_image) for",
"1) * col_space, (box_height + label_height) * row_num + row_num * row_space, ),",
"im_list] for im_list in images] box_width, box_height = max([im.size[0] for im_list in images",
"box_width = max(box_width * len(images[0]), max_label_width) // len(images[0]) back_image = Image.new('RGB', ( col_num",
"draw.textsize(s, font=font) x = (text_width - sz[0]) / 2 y = im_src.height draw.text((x,",
"= 95 back_image = Image.new('RGB', (OUT_WIDTH, OUT_HEIGHT)) attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS)",
"try: image = Image.open(filename).convert('RGBA') new_image = Image.new('RGBA', image.size, (255, 255, 255, 255)) new_image.paste(image,",
"ICON_SIZE = 100, 150 TOP_OFFSET, RIGHT_OFFSET, BOTTOM_OFFSET, LEFT_OFFSET = 22, 165, 20, 10",
"half_en_len(s))) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height = real_width + SPACING im =",
"for im in images] if not options.get('image_style'): box_width, box_height = first_image.size else: if",
"+ real_height), (255, 255, 255)) im.paste(im_src) text_width = im_src.width draw = ImageDraw.Draw(im) sz",
"for label in options['labels']: max_label_width = max(max_label_width, ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(label, font=font)[0]) all_chars |=",
"img_path = os.path.join(globals.staticpath, f'bg/{back_number}.jpg') im_src = Image.open(img_path) if back_number in [f'back_{n}' for n",
"i) * box_width + (box_width - im.size[0]) // 2 + col_space * c,",
"c + i) * box_width + (box_width - im.size[0]) // 2 + col_space",
"back_number = f'back_{back_number}' img_path = os.path.join(globals.staticpath, f'bg/{back_number}.jpg') im_src = Image.open(img_path) if back_number in",
"= real_width + SPACING im = Image.new('RGB', (im_src.width, im_src.height), (255, 255, 255)) im.paste(im_src)",
"0 for label in options['labels']: max_label_width = max(max_label_width, ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(label, font=font)[0]) all_chars",
"(2, 170 - 27 * (i + 1)), mask=star) if return_fn: fn =",
"* int(i == len(image_group) - 1), r * (box_height + row_space) )) return",
"LEFT_OFFSET = 22, 165, 20, 10 STAT_STEP = 95 back_image = Image.new('RGB', (OUT_WIDTH,",
"mask=frame) back_image.paste(band_icon, (0, 0), mask=band_icon) back_image.paste(attribute_icon, (180 - 50, 0), mask=attribute_icon) for i",
"* 4 // 5) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height = real_width +",
"im_list] for im_list in images] elif options['image_style'].get('width') and not options['image_style'].get('height'): images = [[im.resize((options['image_style']['width'],",
"is None: im = Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile, quality=quality) return absoutfile o_size",
"list of lists(tuples) of Image objects') else: raise Exception('images must be a list",
"draw.text((x, y), s, fill=(23, 0, 0), font=font) return im def get_back_pics(): raw =",
"back_image.paste(im, ( (len(image_group) * c + i) * box_width + (box_width - im.size[0])",
"- STAT_STEP * (i + 1)), mask=star) back_image.save(fn) return fn except: return ''",
"assigned, take the params of the first image; if both assigned, will be",
"im = Image.new('RGB', (im_src.width, im_src.height + real_height), (255, 255, 255)) im.paste(im_src) text_width =",
"= im_src.width draw = ImageDraw.Draw(im) sz = draw.textsize(s, font=font) x = (text_width -",
"- 1) * col_space, (box_height + label_height) * row_num + row_num * row_space,",
"// 2 + c * col_space * int(i == len(image_group) - 1), r",
"( col_num * len(images[0]) * box_width + (col_num - 1) * col_space, (box_height",
"options['image_style']['width'], max([im.size[1] for im_list in images for im in im_list]) elif not options['image_style'].get('width')",
"manual(): raw = ImageAsset.get('manual') if raw: return raw row_space = 20 col_space =",
"'底图+数字: 切换底图', 'xx.jpg: 图片合成', '', '以下查询功能数据来源Bestdori', '查卡 [稀有度] [颜色] [人物] [乐团] [技能类型]: 按条件筛选符合要求的卡片,同类条件取并集,不同类条件取交集。例如:",
"box) return ImageAsset.image_raw(im, 'back_catalogue') def merge_image(rsn, rarity, attribute, band_id, thumbnail=True, trained=False, return_fn=False): if",
"font=font) line_pos += sz[1] + row_space return ImageAsset.image_raw(image, 'manual') def compress(infile, mb=None, step=10,",
"raw row_space = 20 col_space = 50 font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), 20) lines",
"max(6, half_en_len(s)) * 4 // 5) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height =",
"[[im.resize((options['image_style']['height'] * im.size[0] // im.size[1], options['image_style']['height'])) for im in im_list] for im_list in",
"row_space) * len(lines)), (255, 255, 255)) draw = ImageDraw.Draw(image) line_pos = row_space for",
"of Image objects, or a list of lists(tuples) of Image objects') else: raise",
"0) if options.get('labels'): font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), options.get('label_style', {}).get('font_size', 20)) all_chars = set()",
"'image', f'auto_reply/cards/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') if os.access(fn, os.R_OK): return fn try:",
"2 back_number = f'back_{back_number}' img_path = os.path.join(globals.staticpath, f'bg/{back_number}.jpg') im_src = Image.open(img_path) if back_number",
"draw = ImageDraw.Draw(image) line_pos = row_space for i, line in enumerate(lines): sz =",
"try: OUT_WIDTH, OUT_HEIGHT = 1364, 1020 INNER_WIDTH, INNER_HEIGHT = 1334, 1002 STAR_SIZE, ICON_SIZE",
"im_src = Image.open(img_path) if back_number in [f'back_{n}' for n in [38, 46, 47,",
"in [33]]: real_width = max(3, im_src.width // max(6, half_en_len(s)) * 4 // 5)",
"draw = ImageDraw.Draw(im) sz = draw.textsize(s, font=font) x = (text_width - sz[0]) /",
"two columns) # row_space (space between two rows, if labels exist, it means",
"open_nontransparent(filename): try: image = Image.open(filename).convert('RGBA') new_image = Image.new('RGBA', image.size, (255, 255, 255, 255))",
"https://bandoristation.com/)', '底图目录: 查询底图目录(是的,不仅功能一样,连图都盗过来了,虽然还没更新。底图31,Tsugu!.jpg)', '底图+数字: 切换底图', 'xx.jpg: 图片合成', '', '以下查询功能数据来源Bestdori', '查卡 [稀有度] [颜色] [人物]",
"im_o.resize((BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT)) box = (i % BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, i // BACK_PIC_NUM_EACH_LINE *",
"int(i == len(image_group) - 1), r * (box_height + row_space) )) return ImageAsset.image_raw(back_image)",
"0, 0), font=font) else: back_image = Image.new('RGB', ( col_num * len(images[0]) * box_width",
"in enumerate(lines): sz = draw.textsize(line, font=font) draw.text((col_space, line_pos), line, fill=(0, 0, 0), font=font)",
"'', '以下查询功能数据来源bilibili开放的豹跳接口,慎用', '查抽卡名字 名字: 查用户名称包含该名字的玩家出的4星', ] line_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize('底图目录', font=font)[1] image",
"BACK_PIC_UNIT_HEIGHT) im.paste(im_o, box) return ImageAsset.image_raw(im, 'back_catalogue') def merge_image(rsn, rarity, attribute, band_id, thumbnail=True, trained=False,",
"+ row_space return ImageAsset.image_raw(image, 'manual') def compress(infile, mb=None, step=10, quality=80, isabs=False): if not",
"else: back_image = Image.new('RGB', ( col_num * len(images[0]) * box_width + (col_num -",
"47, 51, 52, 53]]: real_width = max(3, im_src.width // max(6, half_en_len(s)) * 4",
")) return ImageAsset.image_raw(back_image) def open_nontransparent(filename): try: image = Image.open(filename).convert('RGBA') new_image = Image.new('RGBA', image.size,",
"min(scaled value by width, 180) # label_style: # font_size: font_size of each label",
"col_num + c] for i, im in enumerate(image_group): back_image.paste(im, ( (len(image_group) * c",
"'back_catalogue') def merge_image(rsn, rarity, attribute, band_id, thumbnail=True, trained=False, return_fn=False): if thumbnail: try: if",
"// 5) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height = real_width + SPACING im",
"sys sys.excepthook(*sys.exc_info()) return None else: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/m_{rsn}_{\"normal\" if not trained",
"Image.ANTIALIAS) if not trained: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((STAR_SIZE, STAR_SIZE),",
"of Image objects # labels: a list of strings shown at the bottom",
"row_num * row_space, ), (255, 255, 255)) draw = ImageDraw.Draw(back_image) labels = options['labels']",
"150 TOP_OFFSET, RIGHT_OFFSET, BOTTOM_OFFSET, LEFT_OFFSET = 22, 165, 20, 10 STAT_STEP = 95",
"back_pic_set.add(num) cur_back_pic_nums = len(back_pic_set) if cur_back_pic_nums == 0: return im = Image.new('RGB', (BACK_PIC_NUM_EACH_LINE",
"if not trained: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS)",
"y), s, fill=(245, 255, 250), font=font) elif back_number in [f'back_{n}' for n in",
"180) # height: height of each image, if not assigned, will be min(scaled",
"c * box_width + (len(image_group) * box_width - sz[0]) // 2 + c",
"return new_image except: pass def manual(): raw = ImageAsset.get('manual') if raw: return raw",
"else: raise Exception('images must be a list of Image objects, or a list",
"f'band_{band_id}.png')) if not trained: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((32, 32),",
"0), mask=frame) back_image.paste(band_icon, (LEFT_OFFSET, TOP_OFFSET), mask=band_icon) back_image.paste(attribute_icon, (OUT_WIDTH - RIGHT_OFFSET, TOP_OFFSET), mask=attribute_icon) for",
"new_image.paste(image, (0, 0), image) return new_image except: pass def manual(): raw = ImageAsset.get('manual')",
"= os.path.join(globals.datapath, 'image', outfile) if os.path.exists(absoutfile): return outfile if mb is None: im",
"sz[0]) / 2 y = im_src.height - real_height draw.text((x, y), s, fill=(245, 255,",
"or a list of lists(tuples) of Image objects # labels: a list of",
"trained: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((32, 32), Image.ANTIALIAS) else: back_image",
"(space between two rows, if labels exist, it means the space between the",
"'活动+数字 [服务器]: 按id查询单活动信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '卡池列表 [卡池类型]: 按条件筛选符合要求的卡池,卡池类型包括“常驻”或“无期限”,“限时”或“限定”或“期间限定”,“特殊”(该条件慎加,因为没啥特别的卡池),“必4”', '卡池+数字 [服务器]: 按id查询单卡池信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '', '以下查询功能数据来源bilibili开放的豹跳接口,慎用', '查抽卡名字 名字:",
"mb: return infile while o_size > mb: im = Image.open(absinfile) im = im.convert('RGB')",
"step < 0: break quality -= step o_size = os.path.getsize(absoutfile) / 1024 return",
"OUT_HEIGHT - BOTTOM_OFFSET - STAT_STEP * (i + 1)), mask=star) back_image.save(fn) return fn",
"real_width + SPACING im = Image.new('RGB', (im_src.width, im_src.height + real_height), (255, 255, 255))",
"back_image except: import sys sys.excepthook(*sys.exc_info()) return None else: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/m_{rsn}_{\"normal\"",
"col_num * len(images[0]) * box_width + (col_num - 1) * col_space, box_height *",
"0: return im = Image.new('RGB', (BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT * (((cur_back_pic_nums - 1)",
"# height: height of each image, if not assigned, will be min(scaled value",
"c * col_space * int(i == len(image_group) - 1), r * (box_height +",
"of Image objects') else: raise Exception('images must be a list of Image objects,",
"in im_list] for im_list in images] box_width, box_height = max([im.size[0] for im_list in",
"of lists(tuples) of Image objects') else: images = [[im] for im in images]",
"INNER_WIDTH, INNER_HEIGHT = 1334, 1002 STAR_SIZE, ICON_SIZE = 100, 150 TOP_OFFSET, RIGHT_OFFSET, BOTTOM_OFFSET,",
"back_number in [f'back_{n}' for n in [50]]: real_width = max(3, im_src.width // max(6,",
"Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) else: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_after_training.png\")}')",
"shown at the bottom # image_style: if not assigned, take the params of",
"of each image, if not assigned, will be min(scaled value by width, 180)",
"exist, it means the space between the label of row1 and the image",
"range(col_num): if r * col_num + c >= len(images): break image_group = images[r",
"fill=(245, 255, 250), font=font) elif back_number in [f'back_{n}' for n in [50]]: real_width",
"ImageAsset.image_raw(image, 'manual') def compress(infile, mb=None, step=10, quality=80, isabs=False): if not isabs: absinfile =",
"im_list] for im_list in images] box_width, box_height = options['image_style']['width'], max([im.size[1] for im_list in",
"each image, if not assigned, will be min(scaled value by height, 180) #",
"Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) if rarity == 1: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-1-{attribute}.png')).resize((OUT_WIDTH, OUT_HEIGHT),",
"# col_num (images are arranged row by row) # col_space: (space between two",
"+ row_space) )) return ImageAsset.image_raw(back_image) def open_nontransparent(filename): try: image = Image.open(filename).convert('RGBA') new_image =",
"a list of lists(tuples) of Image objects # labels: a list of strings",
"row_num + (row_num - 1) * row_space ), (255, 255, 255)) draw =",
"<= mb: return infile while o_size > mb: im = Image.open(absinfile) im =",
"mask=band_icon) back_image.paste(attribute_icon, (OUT_WIDTH - RIGHT_OFFSET, TOP_OFFSET), mask=attribute_icon) for i in range(rarity): back_image.paste(star, (LEFT_OFFSET,",
"step=10, quality=80, isabs=False): if not isabs: absinfile = os.path.join(globals.datapath, 'image', infile) else: absinfile",
"mask=attribute_icon) for i in range(rarity): back_image.paste(star, (2, 170 - 27 * (i +",
"box_width + (len(image_group) * box_width - sz[0]) // 2 + c * col_space,",
"s): def half_en_len(s): return (len(s) + (len(s.encode(encoding='utf-8')) - len(s)) // 2) // 2",
"sz = draw.textsize(line, font=font) draw.text((col_space, line_pos), line, fill=(0, 0, 0), font=font) line_pos +=",
"fn try: OUT_WIDTH, OUT_HEIGHT = 1364, 1020 INNER_WIDTH, INNER_HEIGHT = 1334, 1002 STAR_SIZE,",
"row1 and the image of row2) images = options['images'] first_image = images[0] if",
"def get_back_pics(): raw = ImageAsset.get('back_catalogue') if raw: return raw back_pic_set = set() for",
"im.size[1] // im.size[0])) for im in im_list] for im_list in images] box_width, box_height",
"0))).textsize(max(lines, key=lambda line: len(line)), font=font)[0] + 2 * col_space, (line_height + row_space) *",
"im.convert('RGB') im.save(absoutfile, quality=quality) if quality - step < 0: break quality -= step",
"else: real_width = max(3, im_src.width // max(6, half_en_len(s))) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width)",
"not assigned, will be min(scaled value by height, 180) # height: height of",
"isinstance(first_image, (list, tuple)): first_image = first_image[0] if not isinstance(first_image, Image.Image): raise Exception('images must",
"not trained: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) else:",
"from utils.Asset import ImageAsset SPACING = 5 back_regex = re.compile(r'back_([0-9]*)\\.jpg') BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT =",
"= ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize('底图目录', font=font)[1] image = Image.new('RGB', (ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(max(lines, key=lambda line:",
"im_src.height), (255, 255, 255)) im.paste(im_src) text_width = im_src.width draw = ImageDraw.Draw(im) sz =",
"draw.text((x, y), s, fill=(23, 0, 0), font=font) else: real_width = max(3, im_src.width //",
"= ImageDraw.Draw(back_image) labels = options['labels'] for r in range(row_num): for c in range(col_num):",
"Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) if rarity == 1: frame",
"take the params of the first image; if both assigned, will be forced",
"cur_back_pic_nums = len(back_pic_set) if cur_back_pic_nums == 0: return im = Image.new('RGB', (BACK_PIC_NUM_EACH_LINE *",
"= Image.new('RGB', (im_src.width, im_src.height + real_height), (255, 255, 255)) im.paste(im_src) text_width = im_src.width",
"255)) new_image.paste(image, (0, 0), image) return new_image except: pass def manual(): raw =",
"_, files in os.walk(os.path.join(globals.staticpath, 'bg')): for f in files: if f.startswith('back_') and f.endswith('.jpg'):",
"'image', outfile) if os.path.exists(absoutfile): return outfile if mb is None: im = Image.open(absinfile)",
"lists(tuples) of Image objects # labels: a list of strings shown at the",
"STAR_SIZE, ICON_SIZE = 100, 150 TOP_OFFSET, RIGHT_OFFSET, BOTTOM_OFFSET, LEFT_OFFSET = 22, 165, 20,",
"font=font)[0]) all_chars |= set(label) label_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(''.join(all_chars), font=font)[1] box_width = max(box_width",
"thumbnail=True, trained=False, return_fn=False): if thumbnail: try: if return_fn: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\"",
"return (len(s) + (len(s.encode(encoding='utf-8')) - len(s)) // 2) // 2 back_number = f'back_{back_number}'",
"= options.get('col_space', 0) row_space = options.get('row_space', 0) if options.get('labels'): font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'),",
"trained else \"after_training\"}.png') if os.access(fn, os.R_OK): return fn try: OUT_WIDTH, OUT_HEIGHT = 1364,",
"for c in range(col_num): if r * col_num + c >= len(images): break",
"= options.get('col_num', 4) row_num = (len(images) - 1) // col_num + 1 col_space",
"label_style: # font_size: font_size of each label # col_num (images are arranged row",
"(255, 255, 255)) draw = ImageDraw.Draw(back_image) for r in range(row_num): for c in",
"if o_size <= mb: return infile while o_size > mb: im = Image.open(absinfile)",
"box_height = options['image_style']['width'], options['image_style']['height'] images = [[im.resize((box_width, box_height)) for im in im_list] for",
"(text_width - sz[0]) / 2 y = im_src.height - 2 * real_height draw.text((x,",
"= os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') if os.access(fn, os.R_OK): return",
"if not trained else \"after_training\"}.png') if os.access(fn, os.R_OK): return fn attribute_icon = Image.open(os.path.join(globals.asset_resource_path,",
"quality - step < 0: break quality -= step o_size = os.path.getsize(absoutfile) /",
"= 100, 150 TOP_OFFSET, RIGHT_OFFSET, BOTTOM_OFFSET, LEFT_OFFSET = 22, 165, 20, 10 STAT_STEP",
"f.endswith('.jpg'): num = int(back_regex.findall(f)[0]) back_pic_set.add(num) cur_back_pic_nums = len(back_pic_set) if cur_back_pic_nums == 0: return",
"if options['image_style'].get('width') and options['image_style'].get('height'): box_width, box_height = options['image_style']['width'], options['image_style']['height'] images = [[im.resize((box_width, box_height))",
"/ 2 y = 5 draw.text((x, y), s, fill=(23, 0, 0), font=font) else:",
"both assigned, will be forced to resize # width: width of each image,",
"按id查询单活动信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '卡池列表 [卡池类型]: 按条件筛选符合要求的卡池,卡池类型包括“常驻”或“无期限”,“限时”或“限定”或“期间限定”,“特殊”(该条件慎加,因为没啥特别的卡池),“必4”', '卡池+数字 [服务器]: 按id查询单卡池信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '', '以下查询功能数据来源bilibili开放的豹跳接口,慎用', '查抽卡名字 名字: 查用户名称包含该名字的玩家出的4星', ]",
"import os import re import uuid import globals from PIL import Image, ImageDraw,",
"- 2 * real_height draw.text((x, y), s, fill=(245, 255, 250), font=font) elif back_number",
"c >= len(images): break image_group = images[r * col_num + c] for i,",
"(im_src.width, im_src.height + real_height), (255, 255, 255)) im.paste(im_src) text_width = im_src.width draw =",
"f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') if os.access(fn, os.R_OK): return fn attribute_icon =",
"return outfile if mb is None: im = Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile,",
"len(back_pic_set) if cur_back_pic_nums == 0: return im = Image.new('RGB', (BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT",
"the bottom # image_style: if not assigned, take the params of the first",
"2, (OUT_HEIGHT - INNER_HEIGHT) // 2), mask=card) back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon, (LEFT_OFFSET,",
"else: if options['image_style'].get('width') and options['image_style'].get('height'): box_width, box_height = options['image_style']['width'], options['image_style']['height'] images = [[im.resize((box_width,",
"utils.Asset import ImageAsset SPACING = 5 back_regex = re.compile(r'back_([0-9]*)\\.jpg') BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT = 140,",
"RIGHT_OFFSET, BOTTOM_OFFSET, LEFT_OFFSET = 22, 165, 20, 10 STAT_STEP = 95 back_image =",
"list of Image objects, or a list of lists(tuples) of Image objects') else:",
"im_src.height draw.text((x, y), s, fill=(23, 0, 0), font=font) return im def get_back_pics(): raw",
"import globals from PIL import Image, ImageDraw, ImageFont from utils.Asset import ImageAsset SPACING",
"im_o = im_o.resize((BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT)) box = (i % BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, i //",
"Image objects # labels: a list of strings shown at the bottom #",
"image; if both assigned, will be forced to resize # width: width of",
"bg_image_gen(back_number, s): def half_en_len(s): return (len(s) + (len(s.encode(encoding='utf-8')) - len(s)) // 2) //",
"= ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), options.get('label_style', {}).get('font_size', 20)) all_chars = set() max_label_width = 0 for",
"sz[0]) / 2 y = 5 draw.text((x, y), s, fill=(23, 0, 0), font=font)",
"1)), (255, 255, 255)) for i, num in enumerate(back_pic_set): im_o = bg_image_gen(num, f'底图",
"- sz[0]) // 2 + c * col_space, r * (box_height + label_height",
"* (i + 1)), mask=star) back_image.save(fn) return fn except: return '' def white_padding(width,",
"{}).get('font_size', 20)) all_chars = set() max_label_width = 0 for label in options['labels']: max_label_width",
"os.path.getsize(absinfile) / 1024 if o_size <= mb: return infile while o_size > mb:",
"TOP_OFFSET), mask=attribute_icon) for i in range(rarity): back_image.paste(star, (LEFT_OFFSET, OUT_HEIGHT - BOTTOM_OFFSET - STAT_STEP",
"not options['image_style'].get('width') and options['image_style'].get('height'): images = [[im.resize((options['image_style']['height'] * im.size[0] // im.size[1], options['image_style']['height'])) for",
"re import uuid import globals from PIL import Image, ImageDraw, ImageFont from utils.Asset",
"SPACING = 5 back_regex = re.compile(r'back_([0-9]*)\\.jpg') BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT = 140, 130 BACK_PIC_NUM_EACH_LINE =",
"return ImageAsset.image_raw(image, 'manual') def compress(infile, mb=None, step=10, quality=80, isabs=False): if not isabs: absinfile",
"options['image_style'].get('height'): images = [[im.resize((options['image_style']['width'], options['image_style']['width'] * im.size[1] // im.size[0])) for im in im_list]",
"= Image.open(filename).convert('RGBA') new_image = Image.new('RGBA', image.size, (255, 255, 255, 255)) new_image.paste(image, (0, 0),",
"[人物] [乐团] [技能类型]: 按条件筛选符合要求的卡片,同类条件取并集,不同类条件取交集。例如: 查卡 4x pure ksm 分', '查卡+数字: 按id查询单卡信息', '无框+数字: 按id查询单卡无框卡面',",
"list of strings shown at the bottom # image_style: if not assigned, take",
"= Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) if rarity == 1:",
"* col_space, box_height * row_num + (row_num - 1) * row_space ), (255,",
"按id查询单卡池信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '', '以下查询功能数据来源bilibili开放的豹跳接口,慎用', '查抽卡名字 名字: 查用户名称包含该名字的玩家出的4星', ] line_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize('底图目录', font=font)[1]",
"the params of the first image; if both assigned, will be forced to",
"mask=band_icon) back_image.paste(attribute_icon, (180 - 50, 0), mask=attribute_icon) for i in range(rarity): back_image.paste(star, (2,",
"set(label) label_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(''.join(all_chars), font=font)[1] box_width = max(box_width * len(images[0]), max_label_width)",
"2 y = im_src.height - real_height draw.text((x, y), s, fill=(245, 255, 250), font=font)",
"* len(images[0]) * box_width + (col_num - 1) * col_space, (box_height + label_height)",
"by width, 180) # label_style: # font_size: font_size of each label # col_num",
"c + i) * box_width + (box_width - im.size[0]) // 2 + c",
"+ row_space) )) sz = draw.textsize(labels[r * col_num + c], font=font) draw.text(( len(image_group)",
"BOTTOM_OFFSET, LEFT_OFFSET = 22, 165, 20, 10 STAT_STEP = 95 back_image = Image.new('RGB',",
"in images] box_width, box_height = options['image_style']['width'], max([im.size[1] for im_list in images for im",
"- sz[0]) / 2 y = 5 draw.text((x, y), s, fill=(23, 0, 0),",
"a list of Image objects, or a list of lists(tuples) of Image objects')",
"line_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize('底图目录', font=font)[1] image = Image.new('RGB', (ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(max(lines, key=lambda",
"images] box_width, box_height = max([im.size[0] for im_list in images for im in im_list]),",
"= Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile, quality=quality) if quality - step < 0:",
"ImageDraw.Draw(back_image) for r in range(row_num): for c in range(col_num): if r * col_num",
"BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT = 140, 130 BACK_PIC_NUM_EACH_LINE = 5 def bg_image_gen(back_number, s): def half_en_len(s):",
"font=font) else: back_image = Image.new('RGB', ( col_num * len(images[0]) * box_width + (col_num",
"if r * col_num + c >= len(images): break image_group = images[r *",
"= draw.textsize(line, font=font) draw.text((col_space, line_pos), line, fill=(0, 0, 0), font=font) line_pos += sz[1]",
"max_label_width = 0 for label in options['labels']: max_label_width = max(max_label_width, ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(label,",
"line_pos += sz[1] + row_space return ImageAsset.image_raw(image, 'manual') def compress(infile, mb=None, step=10, quality=80,",
"// 2 back_number = f'back_{back_number}' img_path = os.path.join(globals.staticpath, f'bg/{back_number}.jpg') im_src = Image.open(img_path) if",
"= 1334, 1002 STAR_SIZE, ICON_SIZE = 100, 150 TOP_OFFSET, RIGHT_OFFSET, BOTTOM_OFFSET, LEFT_OFFSET =",
"ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(label, font=font)[0]) all_chars |= set(label) label_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(''.join(all_chars), font=font)[1]",
"s, fill=(245, 255, 250), font=font) elif back_number in [f'back_{n}' for n in [33]]:",
"options.get('image_style'): box_width, box_height = first_image.size else: if options['image_style'].get('width') and options['image_style'].get('height'): box_width, box_height =",
"= Image.new('RGB', (OUT_WIDTH, OUT_HEIGHT)) attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) band_icon = Image.open(os.path.join(globals.asset_resource_path,",
"Image.new('RGB', (width, height), (255, 255, 255)) def thumbnail(**options): # images: a list of",
"2 y = im_src.height draw.text((x, y), s, fill=(23, 0, 0), font=font) return im",
"len(images[0]) * box_width + (col_num - 1) * col_space, box_height * row_num +",
"outfile) if os.path.exists(absoutfile): return outfile if mb is None: im = Image.open(absinfile) im",
"1364, 1020 INNER_WIDTH, INNER_HEIGHT = 1334, 1002 STAR_SIZE, ICON_SIZE = 100, 150 TOP_OFFSET,",
"options['labels'] for r in range(row_num): for c in range(col_num): if r * col_num",
"os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') if os.access(fn, os.R_OK): return fn",
"back_image.paste(attribute_icon, (OUT_WIDTH - RIGHT_OFFSET, TOP_OFFSET), mask=attribute_icon) for i in range(rarity): back_image.paste(star, (LEFT_OFFSET, OUT_HEIGHT",
"sz[0]) // 2 + c * col_space, r * (box_height + label_height +",
"draw.textsize(s, font=font) x = (text_width - sz[0]) / 2 y = im_src.height -",
"f in files: if f.startswith('back_') and f.endswith('.jpg'): num = int(back_regex.findall(f)[0]) back_pic_set.add(num) cur_back_pic_nums =",
"fill=(245, 255, 250), font=font) elif back_number in [f'back_{n}' for n in [33]]: real_width",
"in [50]]: real_width = max(3, im_src.width // max(6, half_en_len(s)) * 4 // 5)",
"import sys sys.excepthook(*sys.exc_info()) return None else: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/m_{rsn}_{\"normal\" if not",
"back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((32, 32), Image.ANTIALIAS) else: back_image =",
"return raw back_pic_set = set() for _, _, files in os.walk(os.path.join(globals.staticpath, 'bg')): for",
"not trained else \"after_training\"}.png') back_image.save(fn) return fn return back_image except: import sys sys.excepthook(*sys.exc_info())",
"None: im = Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile, quality=quality) return absoutfile o_size =",
"real_width) real_height = real_width + SPACING im = Image.new('RGB', (im_src.width, im_src.height), (255, 255,",
"= first_image.size else: if options['image_style'].get('width') and options['image_style'].get('height'): box_width, box_height = options['image_style']['width'], options['image_style']['height'] images",
"in enumerate(back_pic_set): im_o = bg_image_gen(num, f'底图 {num}') im_o = im_o.resize((BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT)) box =",
"255, 255)) draw = ImageDraw.Draw(back_image) for r in range(row_num): for c in range(col_num):",
"= Image.new('RGB', (im_src.width, im_src.height), (255, 255, 255)) im.paste(im_src) text_width = im_src.width draw =",
"options['image_style']['width'] * im.size[1] // im.size[0])) for im in im_list] for im_list in images]",
"col_space: (space between two columns) # row_space (space between two rows, if labels",
"= max(3, im_src.width // max(6, half_en_len(s)) * 4 // 5) font = ImageFont.truetype(os.path.join(globals.staticpath,",
"(255, 255, 255)) def thumbnail(**options): # images: a list of Image objects, or",
"all_chars |= set(label) label_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(''.join(all_chars), font=font)[1] box_width = max(box_width *",
"[服务器]: 按id查询单活动信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '卡池列表 [卡池类型]: 按条件筛选符合要求的卡池,卡池类型包括“常驻”或“无期限”,“限时”或“限定”或“期间限定”,“特殊”(该条件慎加,因为没啥特别的卡池),“必4”', '卡池+数字 [服务器]: 按id查询单卡池信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '', '以下查询功能数据来源bilibili开放的豹跳接口,慎用', '查抽卡名字 名字: 查用户名称包含该名字的玩家出的4星',",
"images = [[im.resize((box_width, box_height)) for im in im_list] for im_list in images] elif",
"c, r * (box_height + label_height + row_space) )) sz = draw.textsize(labels[r *",
"in images] elif options['image_style'].get('width') and not options['image_style'].get('height'): images = [[im.resize((options['image_style']['width'], options['image_style']['width'] * im.size[1]",
"+ col_space * c, r * (box_height + label_height + row_space) )) sz",
"im in im_list]) elif not options['image_style'].get('width') and options['image_style'].get('height'): images = [[im.resize((options['image_style']['height'] * im.size[0]",
"(len(s) + (len(s.encode(encoding='utf-8')) - len(s)) // 2) // 2 back_number = f'back_{back_number}' img_path",
"card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) else: card =",
"len(s)) // 2) // 2 back_number = f'back_{back_number}' img_path = os.path.join(globals.staticpath, f'bg/{back_number}.jpg') im_src",
"255)) for i, num in enumerate(back_pic_set): im_o = bg_image_gen(num, f'底图 {num}') im_o =",
"= bg_image_gen(num, f'底图 {num}') im_o = im_o.resize((BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT)) box = (i % BACK_PIC_NUM_EACH_LINE",
"ImageDraw.Draw(back_image) labels = options['labels'] for r in range(row_num): for c in range(col_num): if",
"= 20 col_space = 50 font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), 20) lines = [",
"absoutfile o_size = os.path.getsize(absinfile) / 1024 if o_size <= mb: return infile while",
"num = int(back_regex.findall(f)[0]) back_pic_set.add(num) cur_back_pic_nums = len(back_pic_set) if cur_back_pic_nums == 0: return im",
"col_space * int(i == len(image_group) - 1), r * (box_height + row_space) ))",
"labels exist, it means the space between the label of row1 and the",
"ImageDraw.Draw(im) sz = draw.textsize(s, font=font) x = (text_width - sz[0]) / 2 y",
"* (box_height + label_height + row_space) )) sz = draw.textsize(labels[r * col_num +",
"按条件筛选符合要求的卡池,卡池类型包括“常驻”或“无期限”,“限时”或“限定”或“期间限定”,“特殊”(该条件慎加,因为没啥特别的卡池),“必4”', '卡池+数字 [服务器]: 按id查询单卡池信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '', '以下查询功能数据来源bilibili开放的豹跳接口,慎用', '查抽卡名字 名字: 查用户名称包含该名字的玩家出的4星', ] line_height = ImageDraw.Draw(Image.new('RGB',",
"Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')) if not trained: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((32,",
"= Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) if rarity == 1: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-1-{attribute}.png')).resize((OUT_WIDTH,",
"255, 255)) im.paste(im_src) text_width = im_src.width draw = ImageDraw.Draw(im) sz = draw.textsize(s, font=font)",
"a list of Image objects, or a list of lists(tuples) of Image objects",
"or a list of lists(tuples) of Image objects') else: raise Exception('images must be",
"i, num in enumerate(back_pic_set): im_o = bg_image_gen(num, f'底图 {num}') im_o = im_o.resize((BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT))",
"len(images[0]) back_image = Image.new('RGB', ( col_num * len(images[0]) * box_width + (col_num -",
"= Image.open(os.path.join(globals.asset_resource_path, f'card-1-{attribute}.png')) else: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-{rarity}.png')) back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon,",
"= os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') back_image.save(fn) return fn return",
"= first_image[0] if not isinstance(first_image, Image.Image): raise Exception('images must be a list of",
"box = (i % BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, i // BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_HEIGHT) im.paste(im_o,",
"if not assigned, take the params of the first image; if both assigned,",
"* col_num + c], font=font) draw.text(( len(image_group) * c * box_width + (len(image_group)",
"+ label_height) * row_num + row_num * row_space, ), (255, 255, 255)) draw",
"at the bottom # image_style: if not assigned, take the params of the",
"os.path.join(globals.datapath, 'image', outfile) if os.path.exists(absoutfile): return outfile if mb is None: im =",
"= 0 for label in options['labels']: max_label_width = max(max_label_width, ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(label, font=font)[0])",
"# label_style: # font_size: font_size of each label # col_num (images are arranged",
"font=font) elif back_number in [f'back_{n}' for n in [50]]: real_width = max(3, im_src.width",
"* (i + 1)), mask=star) if return_fn: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if",
"1), r * (box_height + row_space) )) return ImageAsset.image_raw(back_image) def open_nontransparent(filename): try: image",
"box_width, box_height = options['image_style']['width'], max([im.size[1] for im_list in images for im in im_list])",
"in im_list]), options['image_style']['height'] col_num = options.get('col_num', 4) row_num = (len(images) - 1) //",
"(BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT * (((cur_back_pic_nums - 1) // BACK_PIC_NUM_EACH_LINE) + 1)), (255,",
"// 2, (OUT_HEIGHT - INNER_HEIGHT) // 2), mask=card) back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon,",
"= draw.textsize(labels[r * col_num + c], font=font) draw.text(( len(image_group) * c * box_width",
"return fn return back_image except: import sys sys.excepthook(*sys.exc_info()) return None else: fn =",
"images = [[im.resize((options['image_style']['height'] * im.size[0] // im.size[1], options['image_style']['height'])) for im in im_list] for",
"os.path.join(globals.datapath, 'image', infile) else: absinfile = infile outfile = infile[infile.rfind('/') + 1:infile.rfind('.')] +",
"col_space, (line_height + row_space) * len(lines)), (255, 255, 255)) draw = ImageDraw.Draw(image) line_pos",
"list of lists(tuples) of Image objects # labels: a list of strings shown",
"band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) if not trained: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_normal.png\")}')",
"all_chars = set() max_label_width = 0 for label in options['labels']: max_label_width = max(max_label_width,",
"= Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')) if not trained: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path,",
"elif back_number in [f'back_{n}' for n in [33]]: real_width = max(3, im_src.width //",
"raw: return raw back_pic_set = set() for _, _, files in os.walk(os.path.join(globals.staticpath, 'bg')):",
"col_num (images are arranged row by row) # col_space: (space between two columns)",
"'manual') def compress(infile, mb=None, step=10, quality=80, isabs=False): if not isabs: absinfile = os.path.join(globals.datapath,",
"images[0] if not isinstance(first_image, Image.Image): if isinstance(first_image, (list, tuple)): first_image = first_image[0] if",
"frame = Image.open(os.path.join(globals.asset_resource_path, f'card-1-{attribute}.png')) else: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-{rarity}.png')) back_image.paste(frame, (0, 0), mask=frame)",
"card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) if rarity ==",
"* (box_height + row_space) )) return ImageAsset.image_raw(back_image) def open_nontransparent(filename): try: image = Image.open(filename).convert('RGBA')",
"] line_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize('底图目录', font=font)[1] image = Image.new('RGB', (ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(max(lines,",
"if isinstance(first_image, (list, tuple)): first_image = first_image[0] if not isinstance(first_image, Image.Image): raise Exception('images",
"= max([im.size[0] for im_list in images for im in im_list]), options['image_style']['height'] col_num =",
"f\"{rsn}_card_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) else: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_after_training.png\")}') star",
"font_size: font_size of each label # col_num (images are arranged row by row)",
"查用户名称包含该名字的玩家出的4星', ] line_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize('底图目录', font=font)[1] image = Image.new('RGB', (ImageDraw.Draw(Image.new('RGB', (0,",
"outfile = infile[infile.rfind('/') + 1:infile.rfind('.')] + '-c.jpg' absoutfile = os.path.join(globals.datapath, 'image', outfile) if",
"return im def get_back_pics(): raw = ImageAsset.get('back_catalogue') if raw: return raw back_pic_set =",
"objects # labels: a list of strings shown at the bottom # image_style:",
"Image.new('RGBA', image.size, (255, 255, 255, 255)) new_image.paste(image, (0, 0), image) return new_image except:",
"of Image objects') else: images = [[im] for im in images] if not",
"row_space return ImageAsset.image_raw(image, 'manual') def compress(infile, mb=None, step=10, quality=80, isabs=False): if not isabs:",
"col_space * c, r * (box_height + label_height + row_space) )) sz =",
"s, fill=(23, 0, 0), font=font) return im def get_back_pics(): raw = ImageAsset.get('back_catalogue') if",
"col_space, (box_height + label_height) * row_num + row_num * row_space, ), (255, 255,",
"for i, im in enumerate(image_group): back_image.paste(im, ( (len(image_group) * c + i) *",
"(255, 255, 255)) draw = ImageDraw.Draw(back_image) labels = options['labels'] for r in range(row_num):",
"// BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_HEIGHT) im.paste(im_o, box) return ImageAsset.image_raw(im, 'back_catalogue') def merge_image(rsn, rarity, attribute,",
"in os.walk(os.path.join(globals.staticpath, 'bg')): for f in files: if f.startswith('back_') and f.endswith('.jpg'): num =",
"in range(row_num): for c in range(col_num): if r * col_num + c >=",
"box_width + (col_num - 1) * col_space, box_height * row_num + (row_num -",
"return fn attribute_icon = Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')) if not trained:",
"- 50, 0), mask=attribute_icon) for i in range(rarity): back_image.paste(star, (2, 170 - 27",
"i) * box_width + (box_width - im.size[0]) // 2 + c * col_space",
"(list, tuple)): first_image = first_image[0] if not isinstance(first_image, Image.Image): raise Exception('images must be",
"im.size[0]) // 2 + col_space * c, r * (box_height + label_height +",
"not options['image_style'].get('height'): images = [[im.resize((options['image_style']['width'], options['image_style']['width'] * im.size[1] // im.size[0])) for im in",
"im in images] if not options.get('image_style'): box_width, box_height = first_image.size else: if options['image_style'].get('width')",
"None else: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') if",
"col_num * len(images[0]) * box_width + (col_num - 1) * col_space, (box_height +",
"return absoutfile o_size = os.path.getsize(absinfile) / 1024 if o_size <= mb: return infile",
"4 // 5) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height = real_width + SPACING",
"= 5 back_regex = re.compile(r'back_([0-9]*)\\.jpg') BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT = 140, 130 BACK_PIC_NUM_EACH_LINE = 5",
"'查卡 [稀有度] [颜色] [人物] [乐团] [技能类型]: 按条件筛选符合要求的卡片,同类条件取并集,不同类条件取交集。例如: 查卡 4x pure ksm 分', '查卡+数字:",
"= draw.textsize(s, font=font) x = (text_width - sz[0]) / 2 y = im_src.height",
"ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), options.get('label_style', {}).get('font_size', 20)) all_chars = set() max_label_width = 0 for label",
"'', '以下查询功能数据来源Bestdori', '查卡 [稀有度] [颜色] [人物] [乐团] [技能类型]: 按条件筛选符合要求的卡片,同类条件取并集,不同类条件取交集。例如: 查卡 4x pure ksm",
"max(3, im_src.width // max(6, half_en_len(s))) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height = real_width",
"mb: im = Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile, quality=quality) if quality - step",
"1: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-1-{attribute}.png')) else: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-{rarity}.png')) back_image.paste(frame, (0, 0),",
"first_image = images[0] if not isinstance(first_image, Image.Image): if isinstance(first_image, (list, tuple)): first_image =",
"import uuid import globals from PIL import Image, ImageDraw, ImageFont from utils.Asset import",
"Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile, quality=quality) return absoutfile o_size = os.path.getsize(absinfile) / 1024",
"and options['image_style'].get('height'): images = [[im.resize((options['image_style']['height'] * im.size[0] // im.size[1], options['image_style']['height'])) for im in",
"Image.open(os.path.join(globals.asset_resource_path, f'frame-{rarity}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) back_image.paste(card, ((OUT_WIDTH - INNER_WIDTH) // 2, (OUT_HEIGHT - INNER_HEIGHT)",
"rows, if labels exist, it means the space between the label of row1",
"quality=80, isabs=False): if not isabs: absinfile = os.path.join(globals.datapath, 'image', infile) else: absinfile =",
"= im_src.height - 2 * real_height draw.text((x, y), s, fill=(245, 255, 250), font=font)",
"if not options.get('image_style'): box_width, box_height = first_image.size else: if options['image_style'].get('width') and options['image_style'].get('height'): box_width,",
"+ (box_width - im.size[0]) // 2 + c * col_space * int(i ==",
"font=font) x = (text_width - sz[0]) / 2 y = im_src.height - real_height",
"mask=card) back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon, (LEFT_OFFSET, TOP_OFFSET), mask=band_icon) back_image.paste(attribute_icon, (OUT_WIDTH - RIGHT_OFFSET,",
"Image.ANTIALIAS) else: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_after_training.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((STAR_SIZE, STAR_SIZE), Image.ANTIALIAS) if",
"i // BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_HEIGHT) im.paste(im_o, box) return ImageAsset.image_raw(im, 'back_catalogue') def merge_image(rsn, rarity,",
"- 1) // col_num + 1 col_space = options.get('col_space', 0) row_space = options.get('row_space',",
"for im in im_list]), options['image_style']['height'] col_num = options.get('col_num', 4) row_num = (len(images) -",
"Image objects, or a list of lists(tuples) of Image objects') else: images =",
"(col_num - 1) * col_space, box_height * row_num + (row_num - 1) *",
"= row_space for i, line in enumerate(lines): sz = draw.textsize(line, font=font) draw.text((col_space, line_pos),",
"infile while o_size > mb: im = Image.open(absinfile) im = im.convert('RGB') im.save(absoutfile, quality=quality)",
"r * (box_height + label_height + row_space) + box_height ), labels[r * col_num",
"4) row_num = (len(images) - 1) // col_num + 1 col_space = options.get('col_space',",
"im_src.height - 2 * real_height draw.text((x, y), s, fill=(245, 255, 250), font=font) elif",
"rarity, attribute, band_id, thumbnail=True, trained=False, return_fn=False): if thumbnail: try: if return_fn: fn =",
"assigned, will be forced to resize # width: width of each image, if",
"'卡池+数字 [服务器]: 按id查询单卡池信息,默认国服,可选“日服”,“国际服”,“台服”,“国服”,“韩服”', '', '以下查询功能数据来源bilibili开放的豹跳接口,慎用', '查抽卡名字 名字: 查用户名称包含该名字的玩家出的4星', ] line_height = ImageDraw.Draw(Image.new('RGB', (0,",
"2 + c * col_space * int(i == len(image_group) - 1), r *",
"255, 255, 255)) new_image.paste(image, (0, 0), image) return new_image except: pass def manual():",
"row_num + row_num * row_space, ), (255, 255, 255)) draw = ImageDraw.Draw(back_image) labels",
"+ 2 * col_space, (line_height + row_space) * len(lines)), (255, 255, 255)) draw",
"will be min(scaled value by width, 180) # label_style: # font_size: font_size of",
"range(row_num): for c in range(col_num): if r * col_num + c >= len(images):",
"BACK_PIC_NUM_EACH_LINE * BACK_PIC_UNIT_HEIGHT) im.paste(im_o, box) return ImageAsset.image_raw(im, 'back_catalogue') def merge_image(rsn, rarity, attribute, band_id,",
"in [38, 46, 47, 51, 52, 53]]: real_width = max(3, im_src.width // max(6,",
"Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) if not trained: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_normal.png\")}') star =",
"col_num + c >= len(images): break image_group = images[r * col_num + c]",
"of each image, if not assigned, will be min(scaled value by height, 180)",
"fn except: return '' def white_padding(width, height): return Image.new('RGB', (width, height), (255, 255,",
"ImageAsset SPACING = 5 back_regex = re.compile(r'back_([0-9]*)\\.jpg') BACK_PIC_UNIT_WIDTH, BACK_PIC_UNIT_HEIGHT = 140, 130 BACK_PIC_NUM_EACH_LINE",
"be forced to resize # width: width of each image, if not assigned,",
"'bg')): for f in files: if f.startswith('back_') and f.endswith('.jpg'): num = int(back_regex.findall(f)[0]) back_pic_set.add(num)",
"= ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(''.join(all_chars), font=font)[1] box_width = max(box_width * len(images[0]), max_label_width) // len(images[0])",
"if back_number in [f'back_{n}' for n in [38, 46, 47, 51, 52, 53]]:",
"Image.new('RGB', ( col_num * len(images[0]) * box_width + (col_num - 1) * col_space,",
"* im.size[0] // im.size[1], options['image_style']['height'])) for im in im_list] for im_list in images]",
"Image.open(os.path.join(globals.asset_resource_path, f'{attribute}.png')) band_icon = Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')) if not trained: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_normal.png\")}')",
"in im_list] for im_list in images] elif options['image_style'].get('width') and not options['image_style'].get('height'): images =",
"def white_padding(width, height): return Image.new('RGB', (width, height), (255, 255, 255)) def thumbnail(**options): #",
"+ (len(s.encode(encoding='utf-8')) - len(s)) // 2) // 2 back_number = f'back_{back_number}' img_path =",
"Image.open(os.path.join(globals.asset_resource_path, 'star_trained.png')).resize((32, 32), Image.ANTIALIAS) if rarity == 1: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-1-{attribute}.png')) else:",
"in files: if f.startswith('back_') and f.endswith('.jpg'): num = int(back_regex.findall(f)[0]) back_pic_set.add(num) cur_back_pic_nums = len(back_pic_set)",
"def manual(): raw = ImageAsset.get('manual') if raw: return raw row_space = 20 col_space",
"image = Image.open(filename).convert('RGBA') new_image = Image.new('RGBA', image.size, (255, 255, 255, 255)) new_image.paste(image, (0,",
"* col_num + c >= len(images): break image_group = images[r * col_num +",
"0, 0), font=font) return im def get_back_pics(): raw = ImageAsset.get('back_catalogue') if raw: return",
"row2) images = options['images'] first_image = images[0] if not isinstance(first_image, Image.Image): if isinstance(first_image,",
"in [f'back_{n}' for n in [38, 46, 47, 51, 52, 53]]: real_width =",
"rarity == 1: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-1-{attribute}.png')) else: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-{rarity}.png')) back_image.paste(frame,",
"Image.ANTIALIAS) else: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-{rarity}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) back_image.paste(card, ((OUT_WIDTH - INNER_WIDTH) //",
"options.get('labels'): font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), options.get('label_style', {}).get('font_size', 20)) all_chars = set() max_label_width =",
"not trained: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path, 'star.png')).resize((32, 32), Image.ANTIALIAS) else:",
"(0, 0))).textsize(max(lines, key=lambda line: len(line)), font=font)[0] + 2 * col_space, (line_height + row_space)",
"- BOTTOM_OFFSET - STAT_STEP * (i + 1)), mask=star) back_image.save(fn) return fn except:",
"* col_space, r * (box_height + label_height + row_space) + box_height ), labels[r",
"return raw row_space = 20 col_space = 50 font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), 20)",
"= Image.open(img_path) if back_number in [f'back_{n}' for n in [38, 46, 47, 51,",
"* im.size[1] // im.size[0])) for im in im_list] for im_list in images] box_width,",
"- sz[0]) / 2 y = im_src.height - 2 * real_height draw.text((x, y),",
"( (len(image_group) * c + i) * box_width + (box_width - im.size[0]) //",
"'底图目录: 查询底图目录(是的,不仅功能一样,连图都盗过来了,虽然还没更新。底图31,Tsugu!.jpg)', '底图+数字: 切换底图', 'xx.jpg: 图片合成', '', '以下查询功能数据来源Bestdori', '查卡 [稀有度] [颜色] [人物] [乐团]",
"5) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height = real_width + SPACING im =",
"fn return back_image except: import sys sys.excepthook(*sys.exc_info()) return None else: fn = os.path.join(globals.datapath,",
"= [[im] for im in images] if not options.get('image_style'): box_width, box_height = first_image.size",
"// BACK_PIC_NUM_EACH_LINE) + 1)), (255, 255, 255)) for i, num in enumerate(back_pic_set): im_o",
"1020 INNER_WIDTH, INNER_HEIGHT = 1334, 1002 STAR_SIZE, ICON_SIZE = 100, 150 TOP_OFFSET, RIGHT_OFFSET,",
"import Image, ImageDraw, ImageFont from utils.Asset import ImageAsset SPACING = 5 back_regex =",
"options['labels']: max_label_width = max(max_label_width, ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(label, font=font)[0]) all_chars |= set(label) label_height =",
"// 2), mask=card) back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon, (LEFT_OFFSET, TOP_OFFSET), mask=band_icon) back_image.paste(attribute_icon, (OUT_WIDTH",
"= images[r * col_num + c] for i, im in enumerate(image_group): back_image.paste(im, (",
"n in [33]]: real_width = max(3, im_src.width // max(6, half_en_len(s)) * 4 //",
"50, 0), mask=attribute_icon) for i in range(rarity): back_image.paste(star, (2, 170 - 27 *",
"// max(6, half_en_len(s))) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height = real_width + SPACING",
"a list of strings shown at the bottom # image_style: if not assigned,",
"255, 255)) for i, num in enumerate(back_pic_set): im_o = bg_image_gen(num, f'底图 {num}') im_o",
"box_width + (box_width - im.size[0]) // 2 + c * col_space * int(i",
"im.size[0]) // 2 + c * col_space * int(i == len(image_group) - 1),",
"BACK_PIC_NUM_EACH_LINE = 5 def bg_image_gen(back_number, s): def half_en_len(s): return (len(s) + (len(s.encode(encoding='utf-8')) -",
"options['images'] first_image = images[0] if not isinstance(first_image, Image.Image): if isinstance(first_image, (list, tuple)): first_image",
"= [[im.resize((options['image_style']['height'] * im.size[0] // im.size[1], options['image_style']['height'])) for im in im_list] for im_list",
"label in options['labels']: max_label_width = max(max_label_width, ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(label, font=font)[0]) all_chars |= set(label)",
"+ (col_num - 1) * col_space, (box_height + label_height) * row_num + row_num",
"font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), options.get('label_style', {}).get('font_size', 20)) all_chars = set() max_label_width = 0",
"ImageAsset.image_raw(im, 'back_catalogue') def merge_image(rsn, rarity, attribute, band_id, thumbnail=True, trained=False, return_fn=False): if thumbnail: try:",
"ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(''.join(all_chars), font=font)[1] box_width = max(box_width * len(images[0]), max_label_width) // len(images[0]) back_image",
"im_list]) elif not options['image_style'].get('width') and options['image_style'].get('height'): images = [[im.resize((options['image_style']['height'] * im.size[0] // im.size[1],",
"max(6, half_en_len(s))) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'), real_width) real_height = real_width + SPACING im",
"f'band_{band_id}.png')).resize((ICON_SIZE, ICON_SIZE), Image.ANTIALIAS) if not trained: card = Image.open(f'{os.path.join(globals.asset_card_path, f\"{rsn}_card_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path,",
"trained else \"after_training\"}.png') back_image.save(fn) return fn return back_image except: import sys sys.excepthook(*sys.exc_info()) return",
"key=lambda line: len(line)), font=font)[0] + 2 * col_space, (line_height + row_space) * len(lines)),",
"= (text_width - sz[0]) / 2 y = im_src.height - real_height draw.text((x, y),",
"* c, r * (box_height + label_height + row_space) )) sz = draw.textsize(labels[r",
"- len(s)) // 2) // 2 back_number = f'back_{back_number}' img_path = os.path.join(globals.staticpath, f'bg/{back_number}.jpg')",
"else: absinfile = infile outfile = infile[infile.rfind('/') + 1:infile.rfind('.')] + '-c.jpg' absoutfile =",
"= os.path.join(globals.staticpath, f'bg/{back_number}.jpg') im_src = Image.open(img_path) if back_number in [f'back_{n}' for n in",
"), labels[r * col_num + c], fill=(0, 0, 0), font=font) else: back_image =",
"x = (text_width - sz[0]) / 2 y = im_src.height draw.text((x, y), s,",
"font=font) else: real_width = max(3, im_src.width // max(6, half_en_len(s))) font = ImageFont.truetype(os.path.join(globals.staticpath, 'simhei.ttf'),",
"|= set(label) label_height = ImageDraw.Draw(Image.new('RGB', (0, 0))).textsize(''.join(all_chars), font=font)[1] box_width = max(box_width * len(images[0]),",
"if os.path.exists(absoutfile): return outfile if mb is None: im = Image.open(absinfile) im =",
"- sz[0]) / 2 y = im_src.height - real_height draw.text((x, y), s, fill=(245,",
"0), font=font) line_pos += sz[1] + row_space return ImageAsset.image_raw(image, 'manual') def compress(infile, mb=None,",
"assigned, will be min(scaled value by height, 180) # height: height of each",
"+ 1)), mask=star) if return_fn: fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained",
"= Image.open(os.path.join(globals.asset_resource_path, f'band_{band_id}.png')) if not trained: back_image = Image.open(f'{os.path.join(globals.asset_card_thumb_path, f\"{rsn}_normal.png\")}') star = Image.open(os.path.join(globals.asset_resource_path,",
"font=font) x = (text_width - sz[0]) / 2 y = im_src.height - 2",
"im.size[0])) for im in im_list] for im_list in images] box_width, box_height = options['image_style']['width'],",
"== len(image_group) - 1), r * (box_height + row_space) )) return ImageAsset.image_raw(back_image) def",
"back_image.paste(star, (2, 170 - 27 * (i + 1)), mask=star) if return_fn: fn",
"(box_height + label_height + row_space) )) sz = draw.textsize(labels[r * col_num + c],",
"of strings shown at the bottom # image_style: if not assigned, take the",
"else: frame = Image.open(os.path.join(globals.asset_resource_path, f'card-{rarity}.png')) back_image.paste(frame, (0, 0), mask=frame) back_image.paste(band_icon, (0, 0), mask=band_icon)",
"(0, 0), mask=band_icon) back_image.paste(attribute_icon, (180 - 50, 0), mask=attribute_icon) for i in range(rarity):",
"255, 255)) draw = ImageDraw.Draw(back_image) labels = options['labels'] for r in range(row_num): for",
"absinfile = infile outfile = infile[infile.rfind('/') + 1:infile.rfind('.')] + '-c.jpg' absoutfile = os.path.join(globals.datapath,",
"fn = os.path.join(globals.datapath, 'image', f'auto_reply/cards/thumb/m_{rsn}_{\"normal\" if not trained else \"after_training\"}.png') if os.access(fn, os.R_OK):",
"im_list in images] box_width, box_height = options['image_style']['width'], max([im.size[1] for im_list in images for",
"if rarity == 1: frame = Image.open(os.path.join(globals.asset_resource_path, f'frame-1-{attribute}.png')).resize((OUT_WIDTH, OUT_HEIGHT), Image.ANTIALIAS) else: frame =",
"height: height of each image, if not assigned, will be min(scaled value by",
"255, 250), font=font) elif back_number in [f'back_{n}' for n in [33]]: real_width ="
] |
[
"x: int) -> int: f=False if x<0: f=True y=str(abs(x)) y=y[::-1] x=int(y) if -2147483648<=x",
"-> int: f=False if x<0: f=True y=str(abs(x)) y=y[::-1] x=int(y) if -2147483648<=x and x<=2147483647:",
"int) -> int: f=False if x<0: f=True y=str(abs(x)) y=y[::-1] x=int(y) if -2147483648<=x and",
"f=False if x<0: f=True y=str(abs(x)) y=y[::-1] x=int(y) if -2147483648<=x and x<=2147483647: if f==False:",
"f=True y=str(abs(x)) y=y[::-1] x=int(y) if -2147483648<=x and x<=2147483647: if f==False: return x return",
"y=str(abs(x)) y=y[::-1] x=int(y) if -2147483648<=x and x<=2147483647: if f==False: return x return -x",
"y=y[::-1] x=int(y) if -2147483648<=x and x<=2147483647: if f==False: return x return -x return",
"Solution: def reverse(self, x: int) -> int: f=False if x<0: f=True y=str(abs(x)) y=y[::-1]",
"x=int(y) if -2147483648<=x and x<=2147483647: if f==False: return x return -x return 0",
"x<0: f=True y=str(abs(x)) y=y[::-1] x=int(y) if -2147483648<=x and x<=2147483647: if f==False: return x",
"if x<0: f=True y=str(abs(x)) y=y[::-1] x=int(y) if -2147483648<=x and x<=2147483647: if f==False: return",
"def reverse(self, x: int) -> int: f=False if x<0: f=True y=str(abs(x)) y=y[::-1] x=int(y)",
"reverse(self, x: int) -> int: f=False if x<0: f=True y=str(abs(x)) y=y[::-1] x=int(y) if",
"class Solution: def reverse(self, x: int) -> int: f=False if x<0: f=True y=str(abs(x))",
"int: f=False if x<0: f=True y=str(abs(x)) y=y[::-1] x=int(y) if -2147483648<=x and x<=2147483647: if"
] |
[
"'ROCK' or player.upper() != 'PAPER' or player.upper() != 'SCISSORS': # print(\"Syntax error. Please",
"2: 'PAPER', 3: 'SCISSORS'} def cpu_move(): cpu_rand = randint(1, 3) return cpu_rand def",
"3) return cpu_rand def player_move(): player = input(\"Choose a move: ('ROCK', 'PAPER', or",
"print(\"Oh no! You lose!\") if player_tally == 2: print(\"Congratulations! You win!\") def play_again():",
"'You lose!' elif cpu == 3: return 'You win!' else: return 'Draw!' while",
"your move; either 'ROCK', 'PAPER', or 'SCISSORS'...\") # player_move() # else: return player.upper()",
"else: return 'Draw!' def main(): print(\"This game will be played best two out",
"move; either 'ROCK', 'PAPER', or 'SCISSORS'...\") # player_move() # else: return player.upper() def",
"while player == 'ROCK': if cpu == 2: return 'You lose!' elif cpu",
"player_tally != 2: print(\"Round {}...\".format(match)) player = player_move() cpu = cpu_move() print(\"CPU chose",
"'You win!' else: return 'Draw!' while player == 'PAPER': if cpu == 3:",
"1 if cpu_tally == 2: print(\"Oh no! You lose!\") if player_tally == 2:",
"cpu == 1: return 'You win!' else: return 'Draw!' while player == 'SCISSORS':",
"'PAPER', 3: 'SCISSORS'} def cpu_move(): cpu_rand = randint(1, 3) return cpu_rand def player_move():",
"!= 2: print(\"Round {}...\".format(match)) player = player_move() cpu = cpu_move() print(\"CPU chose {}!\".format(options[cpu]))",
"'SCISSORS'): \") # if player.upper() != 'ROCK' or player.upper() != 'PAPER' or player.upper()",
"main(): print(\"This game will be played best two out of three.\") match =",
"'PAPER', or 'SCISSORS'...\") # player_move() # else: return player.upper() def results(cpu, player): while",
"'SCISSORS'...\") # player_move() # else: return player.upper() def results(cpu, player): while player ==",
"cpu_tally = 0 player_tally = 0 while cpu_tally != 2 and player_tally !=",
"# print(\"Syntax error. Please re-enter your move; either 'ROCK', 'PAPER', or 'SCISSORS'...\") #",
"if cpu == 3: return 'You lose!' elif cpu == 1: return 'You",
"cpu == 2: return 'You lose!' elif cpu == 3: return 'You win!'",
"if player_tally == 2: print(\"Congratulations! You win!\") def play_again(): confirm = input(\"Would you",
"of three.\") match = 1 cpu_tally = 0 player_tally = 0 while cpu_tally",
"\") if confirm.upper() == 'YES': main() else: SystemExit() print(\"Are you ready to play",
"'PAPER' or player.upper() != 'SCISSORS': # print(\"Syntax error. Please re-enter your move; either",
"player_move(): player = input(\"Choose a move: ('ROCK', 'PAPER', or 'SCISSORS'): \") # if",
"= 1 cpu_tally = 0 player_tally = 0 while cpu_tally != 2 and",
"!= 'PAPER' or player.upper() != 'SCISSORS': # print(\"Syntax error. Please re-enter your move;",
"= 0 player_tally = 0 while cpu_tally != 2 and player_tally != 2:",
"!= 'ROCK' or player.upper() != 'PAPER' or player.upper() != 'SCISSORS': # print(\"Syntax error.",
"cpu == 3: return 'You lose!' elif cpu == 1: return 'You win!'",
"to continue or 'NO' to exit program: \") if confirm.upper() == 'YES': main()",
"or player.upper() != 'PAPER' or player.upper() != 'SCISSORS': # print(\"Syntax error. Please re-enter",
"'Draw!' while player == 'SCISSORS': if cpu == 1: return 'You lose!' elif",
"1 cpu_tally += 1 else: print('Draw!') match += 1 if cpu_tally == 2:",
"or player.upper() != 'SCISSORS': # print(\"Syntax error. Please re-enter your move; either 'ROCK',",
"be played best two out of three.\") match = 1 cpu_tally = 0",
"'You lose!' elif cpu == 1: return 'You win!' else: return 'Draw!' while",
"'You lose!' elif cpu == 2: return 'You win!' else: return 'Draw!' def",
"match = 1 cpu_tally = 0 player_tally = 0 while cpu_tally != 2",
"return 'You win!' else: return 'Draw!' while player == 'PAPER': if cpu ==",
"main() else: SystemExit() print(\"Are you ready to play Rock Paper Scissors?\") confirm =",
"<filename>rockpaperscissors.py from random import randint options = {1: 'ROCK', 2: 'PAPER', 3: 'SCISSORS'}",
"2: print(\"Oh no! You lose!\") if player_tally == 2: print(\"Congratulations! You win!\") def",
"= {1: 'ROCK', 2: 'PAPER', 3: 'SCISSORS'} def cpu_move(): cpu_rand = randint(1, 3)",
"while player == 'SCISSORS': if cpu == 1: return 'You lose!' elif cpu",
"print(\"Are you ready to play Rock Paper Scissors?\") confirm = input(\"Enter 'YES' to",
"three.\") match = 1 cpu_tally = 0 player_tally = 0 while cpu_tally !=",
"score == 'You win!': print('You win!') match += 1 player_tally += 1 elif",
"cpu == 1: return 'You lose!' elif cpu == 2: return 'You win!'",
"2: return 'You win!' else: return 'Draw!' def main(): print(\"This game will be",
"1 player_tally += 1 elif score == 'You lose!': print('You lose!') match +=",
"def main(): print(\"This game will be played best two out of three.\") match",
"two out of three.\") match = 1 cpu_tally = 0 player_tally = 0",
"cpu_tally == 2: print(\"Oh no! You lose!\") if player_tally == 2: print(\"Congratulations! You",
"print('Draw!') match += 1 if cpu_tally == 2: print(\"Oh no! You lose!\") if",
"best two out of three.\") match = 1 cpu_tally = 0 player_tally =",
"results(cpu, player) if score == 'You win!': print('You win!') match += 1 player_tally",
"player.upper() != 'PAPER' or player.upper() != 'SCISSORS': # print(\"Syntax error. Please re-enter your",
"Rock Paper Scissors?\") confirm = input(\"Enter 'YES' to continue or 'NO' to exit",
"== 1: return 'You lose!' elif cpu == 2: return 'You win!' else:",
"options = {1: 'ROCK', 2: 'PAPER', 3: 'SCISSORS'} def cpu_move(): cpu_rand = randint(1,",
"or 'SCISSORS'...\") # player_move() # else: return player.upper() def results(cpu, player): while player",
"== 'ROCK': if cpu == 2: return 'You lose!' elif cpu == 3:",
"will be played best two out of three.\") match = 1 cpu_tally =",
"= cpu_move() print(\"CPU chose {}!\".format(options[cpu])) score = results(cpu, player) if score == 'You",
"# if player.upper() != 'ROCK' or player.upper() != 'PAPER' or player.upper() != 'SCISSORS':",
"lose!') match += 1 cpu_tally += 1 else: print('Draw!') match += 1 if",
"you ready to play Rock Paper Scissors?\") confirm = input(\"Enter 'YES' to continue",
"'YES' to continue or 'NO' to exit program: \") if confirm.upper() == 'YES':",
"\") # if player.upper() != 'ROCK' or player.upper() != 'PAPER' or player.upper() !=",
"elif cpu == 1: return 'You win!' else: return 'Draw!' while player ==",
"again?: ('YES' or 'NO') \") if confirm.upper() == 'YES': main() else: SystemExit() print(\"Are",
"== 'You win!': print('You win!') match += 1 player_tally += 1 elif score",
"== 'You lose!': print('You lose!') match += 1 cpu_tally += 1 else: print('Draw!')",
"else: return player.upper() def results(cpu, player): while player == 'ROCK': if cpu ==",
"player_tally = 0 while cpu_tally != 2 and player_tally != 2: print(\"Round {}...\".format(match))",
"print(\"Congratulations! You win!\") def play_again(): confirm = input(\"Would you like to play again?:",
"== 2: return 'You lose!' elif cpu == 3: return 'You win!' else:",
"win!\") def play_again(): confirm = input(\"Would you like to play again?: ('YES' or",
"like to play again?: ('YES' or 'NO') \") if confirm.upper() == 'YES': main()",
"while cpu_tally != 2 and player_tally != 2: print(\"Round {}...\".format(match)) player = player_move()",
"= results(cpu, player) if score == 'You win!': print('You win!') match += 1",
"no! You lose!\") if player_tally == 2: print(\"Congratulations! You win!\") def play_again(): confirm",
"and player_tally != 2: print(\"Round {}...\".format(match)) player = player_move() cpu = cpu_move() print(\"CPU",
"confirm.upper() == 'YES': main() else: SystemExit() print(\"Are you ready to play Rock Paper",
"= input(\"Choose a move: ('ROCK', 'PAPER', or 'SCISSORS'): \") # if player.upper() !=",
"print('You win!') match += 1 player_tally += 1 elif score == 'You lose!':",
"move: ('ROCK', 'PAPER', or 'SCISSORS'): \") # if player.upper() != 'ROCK' or player.upper()",
"cpu_rand = randint(1, 3) return cpu_rand def player_move(): player = input(\"Choose a move:",
"'ROCK': if cpu == 2: return 'You lose!' elif cpu == 3: return",
"SystemExit() print(\"Are you ready to play Rock Paper Scissors?\") confirm = input(\"Enter 'YES'",
"3: 'SCISSORS'} def cpu_move(): cpu_rand = randint(1, 3) return cpu_rand def player_move(): player",
"'SCISSORS': if cpu == 1: return 'You lose!' elif cpu == 2: return",
"win!' else: return 'Draw!' while player == 'SCISSORS': if cpu == 1: return",
"if cpu_tally == 2: print(\"Oh no! You lose!\") if player_tally == 2: print(\"Congratulations!",
"!= 2 and player_tally != 2: print(\"Round {}...\".format(match)) player = player_move() cpu =",
"return cpu_rand def player_move(): player = input(\"Choose a move: ('ROCK', 'PAPER', or 'SCISSORS'):",
"play again?: ('YES' or 'NO') \") if confirm.upper() == 'YES': main() else: SystemExit()",
"'NO') \") if confirm.upper() == 'YES': main() else: SystemExit() print(\"Are you ready to",
"to play again?: ('YES' or 'NO') \") if confirm.upper() == 'YES': main() else:",
"to play Rock Paper Scissors?\") confirm = input(\"Enter 'YES' to continue or 'NO'",
"win!': print('You win!') match += 1 player_tally += 1 elif score == 'You",
"1 elif score == 'You lose!': print('You lose!') match += 1 cpu_tally +=",
"if confirm.upper() == 'YES': main() else: SystemExit() print(\"Are you ready to play Rock",
"player.upper() != 'ROCK' or player.upper() != 'PAPER' or player.upper() != 'SCISSORS': # print(\"Syntax",
"if score == 'You win!': print('You win!') match += 1 player_tally += 1",
"if cpu == 2: return 'You lose!' elif cpu == 3: return 'You",
"return 'You win!' else: return 'Draw!' def main(): print(\"This game will be played",
"Paper Scissors?\") confirm = input(\"Enter 'YES' to continue or 'NO' to exit program:",
"randint options = {1: 'ROCK', 2: 'PAPER', 3: 'SCISSORS'} def cpu_move(): cpu_rand =",
"2 and player_tally != 2: print(\"Round {}...\".format(match)) player = player_move() cpu = cpu_move()",
"+= 1 if cpu_tally == 2: print(\"Oh no! You lose!\") if player_tally ==",
"elif cpu == 3: return 'You win!' else: return 'Draw!' while player ==",
"win!' else: return 'Draw!' def main(): print(\"This game will be played best two",
"You lose!\") if player_tally == 2: print(\"Congratulations! You win!\") def play_again(): confirm =",
"= randint(1, 3) return cpu_rand def player_move(): player = input(\"Choose a move: ('ROCK',",
"return 'Draw!' def main(): print(\"This game will be played best two out of",
"+= 1 elif score == 'You lose!': print('You lose!') match += 1 cpu_tally",
"played best two out of three.\") match = 1 cpu_tally = 0 player_tally",
"results(cpu, player): while player == 'ROCK': if cpu == 2: return 'You lose!'",
"lose!' elif cpu == 2: return 'You win!' else: return 'Draw!' def main():",
"!= 'SCISSORS': # print(\"Syntax error. Please re-enter your move; either 'ROCK', 'PAPER', or",
"cpu_move() print(\"CPU chose {}!\".format(options[cpu])) score = results(cpu, player) if score == 'You win!':",
"'You lose!': print('You lose!') match += 1 cpu_tally += 1 else: print('Draw!') match",
"== 2: print(\"Congratulations! You win!\") def play_again(): confirm = input(\"Would you like to",
"{}!\".format(options[cpu])) score = results(cpu, player) if score == 'You win!': print('You win!') match",
"== 3: return 'You win!' else: return 'Draw!' while player == 'PAPER': if",
"else: SystemExit() print(\"Are you ready to play Rock Paper Scissors?\") confirm = input(\"Enter",
"match += 1 if cpu_tally == 2: print(\"Oh no! You lose!\") if player_tally",
"cpu == 3: return 'You win!' else: return 'Draw!' while player == 'PAPER':",
"== 3: return 'You lose!' elif cpu == 1: return 'You win!' else:",
"== 'YES': main() else: SystemExit() print(\"Are you ready to play Rock Paper Scissors?\")",
"'ROCK', 2: 'PAPER', 3: 'SCISSORS'} def cpu_move(): cpu_rand = randint(1, 3) return cpu_rand",
"# player_move() # else: return player.upper() def results(cpu, player): while player == 'ROCK':",
"'YES': main() else: SystemExit() print(\"Are you ready to play Rock Paper Scissors?\") confirm",
"player_move() # else: return player.upper() def results(cpu, player): while player == 'ROCK': if",
"'PAPER': if cpu == 3: return 'You lose!' elif cpu == 1: return",
"game will be played best two out of three.\") match = 1 cpu_tally",
"return 'You lose!' elif cpu == 2: return 'You win!' else: return 'Draw!'",
"you like to play again?: ('YES' or 'NO') \") if confirm.upper() == 'YES':",
"player_move() cpu = cpu_move() print(\"CPU chose {}!\".format(options[cpu])) score = results(cpu, player) if score",
"player_tally == 2: print(\"Congratulations! You win!\") def play_again(): confirm = input(\"Would you like",
"'SCISSORS': # print(\"Syntax error. Please re-enter your move; either 'ROCK', 'PAPER', or 'SCISSORS'...\")",
"return 'You lose!' elif cpu == 3: return 'You win!' else: return 'Draw!'",
"re-enter your move; either 'ROCK', 'PAPER', or 'SCISSORS'...\") # player_move() # else: return",
"score = results(cpu, player) if score == 'You win!': print('You win!') match +=",
"1 cpu_tally = 0 player_tally = 0 while cpu_tally != 2 and player_tally",
"return 'You win!' else: return 'Draw!' while player == 'SCISSORS': if cpu ==",
"ready to play Rock Paper Scissors?\") confirm = input(\"Enter 'YES' to continue or",
"input(\"Would you like to play again?: ('YES' or 'NO') \") if confirm.upper() ==",
"player = input(\"Choose a move: ('ROCK', 'PAPER', or 'SCISSORS'): \") # if player.upper()",
"while player == 'PAPER': if cpu == 3: return 'You lose!' elif cpu",
"'You win!' else: return 'Draw!' while player == 'SCISSORS': if cpu == 1:",
"== 'SCISSORS': if cpu == 1: return 'You lose!' elif cpu == 2:",
"return player.upper() def results(cpu, player): while player == 'ROCK': if cpu == 2:",
"out of three.\") match = 1 cpu_tally = 0 player_tally = 0 while",
"print(\"CPU chose {}!\".format(options[cpu])) score = results(cpu, player) if score == 'You win!': print('You",
"'You win!': print('You win!') match += 1 player_tally += 1 elif score ==",
"a move: ('ROCK', 'PAPER', or 'SCISSORS'): \") # if player.upper() != 'ROCK' or",
"3: return 'You lose!' elif cpu == 1: return 'You win!' else: return",
"player_tally += 1 elif score == 'You lose!': print('You lose!') match += 1",
"return 'You lose!' elif cpu == 1: return 'You win!' else: return 'Draw!'",
"cpu_tally != 2 and player_tally != 2: print(\"Round {}...\".format(match)) player = player_move() cpu",
"lose!' elif cpu == 3: return 'You win!' else: return 'Draw!' while player",
"2: print(\"Round {}...\".format(match)) player = player_move() cpu = cpu_move() print(\"CPU chose {}!\".format(options[cpu])) score",
"player == 'PAPER': if cpu == 3: return 'You lose!' elif cpu ==",
"== 'PAPER': if cpu == 3: return 'You lose!' elif cpu == 1:",
"0 while cpu_tally != 2 and player_tally != 2: print(\"Round {}...\".format(match)) player =",
"+= 1 else: print('Draw!') match += 1 if cpu_tally == 2: print(\"Oh no!",
"win!') match += 1 player_tally += 1 elif score == 'You lose!': print('You",
"cpu == 2: return 'You win!' else: return 'Draw!' def main(): print(\"This game",
"def play_again(): confirm = input(\"Would you like to play again?: ('YES' or 'NO')",
"# else: return player.upper() def results(cpu, player): while player == 'ROCK': if cpu",
"if cpu == 1: return 'You lose!' elif cpu == 2: return 'You",
"== 2: return 'You win!' else: return 'Draw!' def main(): print(\"This game will",
"lose!': print('You lose!') match += 1 cpu_tally += 1 else: print('Draw!') match +=",
"if player.upper() != 'ROCK' or player.upper() != 'PAPER' or player.upper() != 'SCISSORS': #",
"player.upper() != 'SCISSORS': # print(\"Syntax error. Please re-enter your move; either 'ROCK', 'PAPER',",
"cpu_rand def player_move(): player = input(\"Choose a move: ('ROCK', 'PAPER', or 'SCISSORS'): \")",
"1: return 'You win!' else: return 'Draw!' while player == 'SCISSORS': if cpu",
"randint(1, 3) return cpu_rand def player_move(): player = input(\"Choose a move: ('ROCK', 'PAPER',",
"3: return 'You win!' else: return 'Draw!' while player == 'PAPER': if cpu",
"from random import randint options = {1: 'ROCK', 2: 'PAPER', 3: 'SCISSORS'} def",
"score == 'You lose!': print('You lose!') match += 1 cpu_tally += 1 else:",
"either 'ROCK', 'PAPER', or 'SCISSORS'...\") # player_move() # else: return player.upper() def results(cpu,",
"def results(cpu, player): while player == 'ROCK': if cpu == 2: return 'You",
"'Draw!' def main(): print(\"This game will be played best two out of three.\")",
"def player_move(): player = input(\"Choose a move: ('ROCK', 'PAPER', or 'SCISSORS'): \") #",
"'Draw!' while player == 'PAPER': if cpu == 3: return 'You lose!' elif",
"else: return 'Draw!' while player == 'SCISSORS': if cpu == 1: return 'You",
"print(\"Round {}...\".format(match)) player = player_move() cpu = cpu_move() print(\"CPU chose {}!\".format(options[cpu])) score =",
"player) if score == 'You win!': print('You win!') match += 1 player_tally +=",
"print('You lose!') match += 1 cpu_tally += 1 else: print('Draw!') match += 1",
"else: print('Draw!') match += 1 if cpu_tally == 2: print(\"Oh no! You lose!\")",
"input(\"Enter 'YES' to continue or 'NO' to exit program: \") if confirm.upper() ==",
"+= 1 player_tally += 1 elif score == 'You lose!': print('You lose!') match",
"random import randint options = {1: 'ROCK', 2: 'PAPER', 3: 'SCISSORS'} def cpu_move():",
"or 'NO' to exit program: \") if confirm.upper() == 'YES': main() else: SystemExit()",
"player == 'ROCK': if cpu == 2: return 'You lose!' elif cpu ==",
"'NO' to exit program: \") if confirm.upper() == 'YES': main() else: SystemExit() play_again()",
"error. Please re-enter your move; either 'ROCK', 'PAPER', or 'SCISSORS'...\") # player_move() #",
"{1: 'ROCK', 2: 'PAPER', 3: 'SCISSORS'} def cpu_move(): cpu_rand = randint(1, 3) return",
"lose!\") if player_tally == 2: print(\"Congratulations! You win!\") def play_again(): confirm = input(\"Would",
"('YES' or 'NO') \") if confirm.upper() == 'YES': main() else: SystemExit() print(\"Are you",
"'PAPER', or 'SCISSORS'): \") # if player.upper() != 'ROCK' or player.upper() != 'PAPER'",
"or 'SCISSORS'): \") # if player.upper() != 'ROCK' or player.upper() != 'PAPER' or",
"or 'NO') \") if confirm.upper() == 'YES': main() else: SystemExit() print(\"Are you ready",
"match += 1 player_tally += 1 elif score == 'You lose!': print('You lose!')",
"cpu_move(): cpu_rand = randint(1, 3) return cpu_rand def player_move(): player = input(\"Choose a",
"1 else: print('Draw!') match += 1 if cpu_tally == 2: print(\"Oh no! You",
"1: return 'You lose!' elif cpu == 2: return 'You win!' else: return",
"continue or 'NO' to exit program: \") if confirm.upper() == 'YES': main() else:",
"import randint options = {1: 'ROCK', 2: 'PAPER', 3: 'SCISSORS'} def cpu_move(): cpu_rand",
"'SCISSORS'} def cpu_move(): cpu_rand = randint(1, 3) return cpu_rand def player_move(): player =",
"else: return 'Draw!' while player == 'PAPER': if cpu == 3: return 'You",
"2: return 'You lose!' elif cpu == 3: return 'You win!' else: return",
"win!' else: return 'Draw!' while player == 'PAPER': if cpu == 3: return",
"elif cpu == 2: return 'You win!' else: return 'Draw!' def main(): print(\"This",
"('ROCK', 'PAPER', or 'SCISSORS'): \") # if player.upper() != 'ROCK' or player.upper() !=",
"print(\"Syntax error. Please re-enter your move; either 'ROCK', 'PAPER', or 'SCISSORS'...\") # player_move()",
"print(\"This game will be played best two out of three.\") match = 1",
"cpu_tally += 1 else: print('Draw!') match += 1 if cpu_tally == 2: print(\"Oh",
"= input(\"Would you like to play again?: ('YES' or 'NO') \") if confirm.upper()",
"return 'Draw!' while player == 'SCISSORS': if cpu == 1: return 'You lose!'",
"player == 'SCISSORS': if cpu == 1: return 'You lose!' elif cpu ==",
"'You win!' else: return 'Draw!' def main(): print(\"This game will be played best",
"player = player_move() cpu = cpu_move() print(\"CPU chose {}!\".format(options[cpu])) score = results(cpu, player)",
"cpu = cpu_move() print(\"CPU chose {}!\".format(options[cpu])) score = results(cpu, player) if score ==",
"play Rock Paper Scissors?\") confirm = input(\"Enter 'YES' to continue or 'NO' to",
"confirm = input(\"Enter 'YES' to continue or 'NO' to exit program: \") if",
"input(\"Choose a move: ('ROCK', 'PAPER', or 'SCISSORS'): \") # if player.upper() != 'ROCK'",
"return 'Draw!' while player == 'PAPER': if cpu == 3: return 'You lose!'",
"0 player_tally = 0 while cpu_tally != 2 and player_tally != 2: print(\"Round",
"match += 1 cpu_tally += 1 else: print('Draw!') match += 1 if cpu_tally",
"== 2: print(\"Oh no! You lose!\") if player_tally == 2: print(\"Congratulations! You win!\")",
"confirm = input(\"Would you like to play again?: ('YES' or 'NO') \") if",
"player.upper() def results(cpu, player): while player == 'ROCK': if cpu == 2: return",
"+= 1 cpu_tally += 1 else: print('Draw!') match += 1 if cpu_tally ==",
"player): while player == 'ROCK': if cpu == 2: return 'You lose!' elif",
"'ROCK', 'PAPER', or 'SCISSORS'...\") # player_move() # else: return player.upper() def results(cpu, player):",
"def cpu_move(): cpu_rand = randint(1, 3) return cpu_rand def player_move(): player = input(\"Choose",
"{}...\".format(match)) player = player_move() cpu = cpu_move() print(\"CPU chose {}!\".format(options[cpu])) score = results(cpu,",
"elif score == 'You lose!': print('You lose!') match += 1 cpu_tally += 1",
"= input(\"Enter 'YES' to continue or 'NO' to exit program: \") if confirm.upper()",
"Please re-enter your move; either 'ROCK', 'PAPER', or 'SCISSORS'...\") # player_move() # else:",
"2: print(\"Congratulations! You win!\") def play_again(): confirm = input(\"Would you like to play",
"== 1: return 'You win!' else: return 'Draw!' while player == 'SCISSORS': if",
"You win!\") def play_again(): confirm = input(\"Would you like to play again?: ('YES'",
"= 0 while cpu_tally != 2 and player_tally != 2: print(\"Round {}...\".format(match)) player",
"= player_move() cpu = cpu_move() print(\"CPU chose {}!\".format(options[cpu])) score = results(cpu, player) if",
"Scissors?\") confirm = input(\"Enter 'YES' to continue or 'NO' to exit program: \")",
"chose {}!\".format(options[cpu])) score = results(cpu, player) if score == 'You win!': print('You win!')",
"lose!' elif cpu == 1: return 'You win!' else: return 'Draw!' while player",
"play_again(): confirm = input(\"Would you like to play again?: ('YES' or 'NO') \")"
] |
[
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"StartInstanceError(RuntimeError): \"\"\"Instance could not be started\"\"\" # StartInstanceError class ComponentProbeError(RuntimeError): \"\"\"Component returned an",
"# # CONSTANTS AND DEFINITIONS # # # CODE # class StartInstanceError(RuntimeError): \"\"\"Instance",
"KIND, either express or implied. # See the License for the specific language",
"Unless required by applicable law or agreed to in writing, software # distributed",
"layer errors that should be differentiated \"\"\" # # IMPORTS # # #",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"# See the License for the specific language governing permissions and # limitations",
"License. # You may obtain a copy of the License at # #",
"IBM Corp. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"\"\"\"Component returned an erroneous response\"\"\" # ComponentProbeError class ConfigurationError(ValueError): \"\"\"Invalid configuration values\"\"\" #",
"the specific language governing permissions and # limitations under the License. \"\"\" Custom",
"law or agreed to in writing, software # distributed under the License is",
"the License for the specific language governing permissions and # limitations under the",
"compliance with the License. # You may obtain a copy of the License",
"def __init__(self, error_iterator) -> None: errors = [f'{\"/\".join(map(str, item.path))}: {item.message}' for item in",
"# # # CONSTANTS AND DEFINITIONS # # # CODE # class StartInstanceError(RuntimeError):",
"specific language governing permissions and # limitations under the License. \"\"\" Custom service",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"this file except in compliance with the License. # You may obtain a",
"None: errors = [f'{\"/\".join(map(str, item.path))}: {item.message}' for item in error_iterator] super().__init__(f'Task validation failed:",
"StartInstanceError class ComponentProbeError(RuntimeError): \"\"\"Component returned an erroneous response\"\"\" # ComponentProbeError class ConfigurationError(ValueError): \"\"\"Invalid",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"you may not use this file except in compliance with the License. #",
"an erroneous response\"\"\" # ComponentProbeError class ConfigurationError(ValueError): \"\"\"Invalid configuration values\"\"\" # ConfigurationError class",
"# StartInstanceError class ComponentProbeError(RuntimeError): \"\"\"Component returned an erroneous response\"\"\" # ComponentProbeError class ConfigurationError(ValueError):",
"under the License. \"\"\" Custom service layer errors that should be differentiated \"\"\"",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"ANY KIND, either express or implied. # See the License for the specific",
"limitations under the License. \"\"\" Custom service layer errors that should be differentiated",
"\"\"\" Custom service layer errors that should be differentiated \"\"\" # # IMPORTS",
"# IMPORTS # # # CONSTANTS AND DEFINITIONS # # # CODE #",
"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",
"# # IMPORTS # # # CONSTANTS AND DEFINITIONS # # # CODE",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"use this file except in compliance with the License. # You may obtain",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"for the specific language governing permissions and # limitations under the License. \"\"\"",
"error\"\"\" def __init__(self, error_iterator) -> None: errors = [f'{\"/\".join(map(str, item.path))}: {item.message}' for item",
"not use this file except in compliance with the License. # You may",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"the License. \"\"\" Custom service layer errors that should be differentiated \"\"\" #",
"See the License for the specific language governing permissions and # limitations under",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"class ConfigurationError(ValueError): \"\"\"Invalid configuration values\"\"\" # ConfigurationError class ValidationError(ValueError): \"\"\"JSON Schema validation error\"\"\"",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"ConfigurationError(ValueError): \"\"\"Invalid configuration values\"\"\" # ConfigurationError class ValidationError(ValueError): \"\"\"JSON Schema validation error\"\"\" def",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"be started\"\"\" # StartInstanceError class ComponentProbeError(RuntimeError): \"\"\"Component returned an erroneous response\"\"\" # ComponentProbeError",
"\"\"\"JSON Schema validation error\"\"\" def __init__(self, error_iterator) -> None: errors = [f'{\"/\".join(map(str, item.path))}:",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"and # limitations under the License. \"\"\" Custom service layer errors that should",
"permissions and # limitations under the License. \"\"\" Custom service layer errors that",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"{item.message}' for item in error_iterator] super().__init__(f'Task validation failed: {\", \".join(errors)}') # __init__() #",
"License. \"\"\" Custom service layer errors that should be differentiated \"\"\" # #",
"# CONSTANTS AND DEFINITIONS # # # CODE # class StartInstanceError(RuntimeError): \"\"\"Instance could",
"for item in error_iterator] super().__init__(f'Task validation failed: {\", \".join(errors)}') # __init__() # ValidationError",
"item.path))}: {item.message}' for item in error_iterator] super().__init__(f'Task validation failed: {\", \".join(errors)}') # __init__()",
"OF ANY KIND, either express or implied. # See the License for the",
"ConfigurationError class ValidationError(ValueError): \"\"\"JSON Schema validation error\"\"\" def __init__(self, error_iterator) -> None: errors",
"class ComponentProbeError(RuntimeError): \"\"\"Component returned an erroneous response\"\"\" # ComponentProbeError class ConfigurationError(ValueError): \"\"\"Invalid configuration",
"ValidationError(ValueError): \"\"\"JSON Schema validation error\"\"\" def __init__(self, error_iterator) -> None: errors = [f'{\"/\".join(map(str,",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"CODE # class StartInstanceError(RuntimeError): \"\"\"Instance could not be started\"\"\" # StartInstanceError class ComponentProbeError(RuntimeError):",
"\"\"\"Invalid configuration values\"\"\" # ConfigurationError class ValidationError(ValueError): \"\"\"JSON Schema validation error\"\"\" def __init__(self,",
"-> None: errors = [f'{\"/\".join(map(str, item.path))}: {item.message}' for item in error_iterator] super().__init__(f'Task validation",
"# Copyright 2021 IBM Corp. # # Licensed under the Apache License, Version",
"= [f'{\"/\".join(map(str, item.path))}: {item.message}' for item in error_iterator] super().__init__(f'Task validation failed: {\", \".join(errors)}')",
"# you may not use this file except in compliance with the License.",
"ComponentProbeError(RuntimeError): \"\"\"Component returned an erroneous response\"\"\" # ComponentProbeError class ConfigurationError(ValueError): \"\"\"Invalid configuration values\"\"\"",
"agreed to in writing, software # distributed under the License is distributed on",
"Corp. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"language governing permissions and # limitations under the License. \"\"\" Custom service layer",
"\"\"\" # # IMPORTS # # # CONSTANTS AND DEFINITIONS # # #",
"DEFINITIONS # # # CODE # class StartInstanceError(RuntimeError): \"\"\"Instance could not be started\"\"\"",
"(the \"License\"); # you may not use this file except in compliance with",
"configuration values\"\"\" # ConfigurationError class ValidationError(ValueError): \"\"\"JSON Schema validation error\"\"\" def __init__(self, error_iterator)",
"# # Unless required by applicable law or agreed to in writing, software",
"governing permissions and # limitations under the License. \"\"\" Custom service layer errors",
"express or implied. # See the License for the specific language governing permissions",
"error_iterator) -> None: errors = [f'{\"/\".join(map(str, item.path))}: {item.message}' for item in error_iterator] super().__init__(f'Task",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"# Unless required by applicable law or agreed to in writing, software #",
"except in compliance with the License. # You may obtain a copy of",
"by applicable law or agreed to in writing, software # distributed under the",
"2021 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"response\"\"\" # ComponentProbeError class ConfigurationError(ValueError): \"\"\"Invalid configuration values\"\"\" # ConfigurationError class ValidationError(ValueError): \"\"\"JSON",
"either express or implied. # See the License for the specific language governing",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"validation error\"\"\" def __init__(self, error_iterator) -> None: errors = [f'{\"/\".join(map(str, item.path))}: {item.message}' for",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"# # # CODE # class StartInstanceError(RuntimeError): \"\"\"Instance could not be started\"\"\" #",
"# # CODE # class StartInstanceError(RuntimeError): \"\"\"Instance could not be started\"\"\" # StartInstanceError",
"# ComponentProbeError class ConfigurationError(ValueError): \"\"\"Invalid configuration values\"\"\" # ConfigurationError class ValidationError(ValueError): \"\"\"JSON Schema",
"differentiated \"\"\" # # IMPORTS # # # CONSTANTS AND DEFINITIONS # #",
"started\"\"\" # StartInstanceError class ComponentProbeError(RuntimeError): \"\"\"Component returned an erroneous response\"\"\" # ComponentProbeError class",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"Custom service layer errors that should be differentiated \"\"\" # # IMPORTS #",
"service layer errors that should be differentiated \"\"\" # # IMPORTS # #",
"file except in compliance with the License. # You may obtain a copy",
"# class StartInstanceError(RuntimeError): \"\"\"Instance could not be started\"\"\" # StartInstanceError class ComponentProbeError(RuntimeError): \"\"\"Component",
"CONSTANTS AND DEFINITIONS # # # CODE # class StartInstanceError(RuntimeError): \"\"\"Instance could not",
"IMPORTS # # # CONSTANTS AND DEFINITIONS # # # CODE # class",
"class ValidationError(ValueError): \"\"\"JSON Schema validation error\"\"\" def __init__(self, error_iterator) -> None: errors =",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"not be started\"\"\" # StartInstanceError class ComponentProbeError(RuntimeError): \"\"\"Component returned an erroneous response\"\"\" #",
"License for the specific language governing permissions and # limitations under the License.",
"\"\"\"Instance could not be started\"\"\" # StartInstanceError class ComponentProbeError(RuntimeError): \"\"\"Component returned an erroneous",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"AND DEFINITIONS # # # CODE # class StartInstanceError(RuntimeError): \"\"\"Instance could not be",
"returned an erroneous response\"\"\" # ComponentProbeError class ConfigurationError(ValueError): \"\"\"Invalid configuration values\"\"\" # ConfigurationError",
"the License. # You may obtain a copy of the License at #",
"to in writing, software # distributed under the License is distributed on an",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"implied. # See the License for the specific language governing permissions and #",
"should be differentiated \"\"\" # # IMPORTS # # # CONSTANTS AND DEFINITIONS",
"\"License\"); # you may not use this file except in compliance with the",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"[f'{\"/\".join(map(str, item.path))}: {item.message}' for item in error_iterator] super().__init__(f'Task validation failed: {\", \".join(errors)}') #",
"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",
"class StartInstanceError(RuntimeError): \"\"\"Instance could not be started\"\"\" # StartInstanceError class ComponentProbeError(RuntimeError): \"\"\"Component returned",
"# limitations under the License. \"\"\" Custom service layer errors that should be",
"applicable law or agreed to in writing, software # distributed under the License",
"# CODE # class StartInstanceError(RuntimeError): \"\"\"Instance could not be started\"\"\" # StartInstanceError class",
"be differentiated \"\"\" # # IMPORTS # # # CONSTANTS AND DEFINITIONS #",
"values\"\"\" # ConfigurationError class ValidationError(ValueError): \"\"\"JSON Schema validation error\"\"\" def __init__(self, error_iterator) ->",
"that should be differentiated \"\"\" # # IMPORTS # # # CONSTANTS AND",
"# ConfigurationError class ValidationError(ValueError): \"\"\"JSON Schema validation error\"\"\" def __init__(self, error_iterator) -> None:",
"or agreed to in writing, software # distributed under the License is distributed",
"ComponentProbeError class ConfigurationError(ValueError): \"\"\"Invalid configuration values\"\"\" # ConfigurationError class ValidationError(ValueError): \"\"\"JSON Schema validation",
"or implied. # See the License for the specific language governing permissions and",
"erroneous response\"\"\" # ComponentProbeError class ConfigurationError(ValueError): \"\"\"Invalid configuration values\"\"\" # ConfigurationError class ValidationError(ValueError):",
"errors = [f'{\"/\".join(map(str, item.path))}: {item.message}' for item in error_iterator] super().__init__(f'Task validation failed: {\",",
"Copyright 2021 IBM Corp. # # Licensed under the Apache License, Version 2.0",
"Schema validation error\"\"\" def __init__(self, error_iterator) -> None: errors = [f'{\"/\".join(map(str, item.path))}: {item.message}'",
"could not be started\"\"\" # StartInstanceError class ComponentProbeError(RuntimeError): \"\"\"Component returned an erroneous response\"\"\"",
"errors that should be differentiated \"\"\" # # IMPORTS # # # CONSTANTS",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"__init__(self, error_iterator) -> None: errors = [f'{\"/\".join(map(str, item.path))}: {item.message}' for item in error_iterator]",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"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,",
"in writing, software # distributed under the License is distributed on an \"AS",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use"
] |
[
"pair_counter = 0 prev_pair = pair if first: first = False ## Handle",
"prev_pair and not first: nodes_to_norm = set() for path in filtered_paths[prev_pair]: for node",
"pair_counter == 150_000: print(f\"{total_pairs} processed.\", flush=True) pair_counter = 0 prev_pair = pair if",
"True edge_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths = dict() with open(filename,",
"k): ''' Computes route betweenness for paths by reading file filename. Uses dictionaries",
"filtered_paths[prev_pair]: paths_to_norm = set() for i in range(0, len(path)-k): kpath = tuple(path[i:i+k+1]) path_to_pair_dict.setdefault(kpath,",
"route_node_betweenness_from_paths(G, filtered_paths): ''' Computes route betweenness for nodes starting from set of paths",
"False ## Handle the last pair for path in filtered_paths[prev_pair]: paths_to_norm = set()",
"first: paths_to_norm = set() for path in filtered_paths[prev_pair]: for i in range(0, len(path)-k):",
"dimensions len(G.nodes()) by len(filtered_paths) node_to_idx = {node:idx for idx, node in enumerate(G.nodes())} pair_to_idx",
"= {node:total_betweenness[idx] for node, idx in node_to_idx.items()} return route_betweenness def route_node_betweenness_from_file(filename): ''' Computes",
"nodes_to_norm.add(node) ## Normalize for node in nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness",
"0 first = True path_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths =",
"filtered_paths[prev_pair]: for node in path: node_to_pair_dict.setdefault(node, dict()) node_to_pair_dict[node].setdefault(prev_pair, 0) node_to_pair_dict[node][prev_pair] += 1 nodes_to_norm.add(node)",
"''' ## Zero array of dimensions len(G.nodes()) by len(filtered_paths) node_to_idx = {node:idx for",
"flush=True) pair_counter = 0 prev_pair = pair if first: first = False ##",
"nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs += 1 if pair_counter ==",
"False ## Handle the last pair for path in filtered_paths[prev_pair]: edges_to_norm = set()",
"!= prev_pair and not first: paths_to_norm = set() for path in filtered_paths[prev_pair]: for",
"the last pair for path in filtered_paths[prev_pair]: edges_to_norm = set() for i in",
"(path[0], path[-1]) filtered_paths.setdefault(pair, list()) filtered_paths[pair].append(path) if pair != prev_pair and not first: paths_to_norm",
"for node in node_to_pair_dict} return route_betweenness def route_edge_betweenness_from_paths(G, filtered_paths): ''' Computes route betweenness",
"len(G.edges()) by len(filtered_paths) edge_to_idx = {edge:idx for idx, edge in enumerate(G.edges())} pair_to_idx =",
"= False ## Handle the last pair for path in filtered_paths[prev_pair]: edges_to_norm =",
"Normalize for edge in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing",
"idx, pair in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.nodes()), len(filtered_paths))) denominator = [] for pair",
"set of paths filtered_paths. Uses G only to get the number of nodes;",
"for i in range(1, len(path)): edge = path[i-1], path[i] edge_to_pair_dict.setdefault(edge, dict()) edge_to_pair_dict[edge].setdefault(prev_pair, 0)",
"''' pair_counter = 0 total_pairs = 0 first = True path_to_pair_dict = dict()",
"edge_to_pair_dict.setdefault(edge, dict()) edge_to_pair_dict[edge].setdefault(prev_pair, 0) edge_to_pair_dict[edge][prev_pair] += 1 edges_to_norm.add(edge) ## Normalize for edge in",
"for node in path: numerator[node_to_idx[node], pair_to_idx[pair]] += 1 denominator = np.array(denominator) normalized_counts =",
"1 paths_to_norm.add(kpath) ## Normalize for path in paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute",
"Handle the last pair for path in filtered_paths[prev_pair]: paths_to_norm = set() for i",
"+= 1 edges_to_norm.add(edge) ## Normalize for edge in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter",
"## Handle the last pair for path in filtered_paths[prev_pair]: edges_to_norm = set() for",
"{node:sum(node_to_pair_dict[node].values()) for node in node_to_pair_dict} return route_betweenness def route_edge_betweenness_from_paths(G, filtered_paths): ''' Computes route",
"for computations. ''' pair_counter = 0 total_pairs = 0 first = True node_to_pair_dict",
"= line.strip().split('|') path = path.strip().split(',') pair = (path[0], path[-1]) filtered_paths.setdefault(pair, list()) filtered_paths[pair].append(path) if",
"in filtered_paths[prev_pair]: paths_to_norm = set() for i in range(0, len(path)-k): kpath = tuple(path[i:i+k+1])",
"node_to_pair_dict[node].setdefault(prev_pair, 0) node_to_pair_dict[node][prev_pair] += 1 nodes_to_norm.add(node) ## Normalize for node in nodes_to_norm: node_to_pair_dict[node][prev_pair]",
"in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.nodes()), len(filtered_paths))) denominator = [] for pair in filtered_paths:",
"denominator total_betweenness = normalized_counts.sum(axis=1) route_betweenness = {edge:total_betweenness[idx] for edge, idx in edge_to_idx.items()} return",
"in filtered_paths[prev_pair]: for i in range(1, len(path)): edge = path[i-1], path[i] edge_to_pair_dict.setdefault(edge, dict())",
"in range(1, len(path)): edge = path[i-1], path[i] edge_to_pair_dict.setdefault(edge, dict()) edge_to_pair_dict[edge].setdefault(prev_pair, 0) edge_to_pair_dict[edge][prev_pair] +=",
"in filtered_paths[pair]: for i in range(1, len(path)): numerator[edge_to_idx[(path[i-1], path[i])], pair_to_idx[pair]] += 1 denominator",
"by len(filtered_paths) node_to_idx = {node:idx for idx, node in enumerate(G.nodes())} pair_to_idx = {pair:idx",
"first = False ## Handle the last pair for path in filtered_paths[prev_pair]: nodes_to_norm",
"for nodes by reading file filename. Uses dictionaries for computations. ''' pair_counter =",
"## Compute betweenness by summing over all pairs for each node route_betweenness =",
"0 first = True edge_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths =",
"in paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all pairs",
"edge in enumerate(G.edges())} pair_to_idx = {pair:idx for idx, pair in enumerate(filtered_paths.keys())} numerator =",
"{edge:idx for idx, edge in enumerate(G.edges())} pair_to_idx = {pair:idx for idx, pair in",
"edge_to_pair_dict} return route_betweenness def route_path_betweenness_from_file(filename, k): ''' Computes route betweenness for paths by",
"filtered_paths.setdefault(pair, list()) filtered_paths[pair].append(path) if pair != prev_pair and not first: nodes_to_norm = set()",
"route betweenness for nodes by reading file filename. Uses dictionaries for computations. '''",
"path: numerator[node_to_idx[node], pair_to_idx[pair]] += 1 denominator = np.array(denominator) normalized_counts = numerator / denominator",
"for idx, edge in enumerate(G.edges())} pair_to_idx = {pair:idx for idx, pair in enumerate(filtered_paths.keys())}",
"betweenness by summing over all pairs for each edge route_betweenness = {edge:sum(edge_to_pair_dict[edge].values()) for",
"first: first = False ## Handle the last pair for path in filtered_paths[prev_pair]:",
"Computes route betweenness for edges by reading file filename. Uses dictionaries for computations.",
"set() for node in path: node_to_pair_dict.setdefault(node, dict()) node_to_pair_dict[node].setdefault(prev_pair, 0) node_to_pair_dict[node][prev_pair] += 1 nodes_to_norm.add(node)",
"path_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths = dict() with open(filename, 'r')",
"= {node:sum(node_to_pair_dict[node].values()) for node in node_to_pair_dict} return route_betweenness def route_edge_betweenness_from_paths(G, filtered_paths): ''' Computes",
"as input parameter. Uses dense numpy arrays for computations. ''' ## Zero array",
"for computations. ''' pair_counter = 0 total_pairs = 0 first = True edge_to_pair_dict",
"for path in filtered_paths[pair]: for i in range(1, len(path)): numerator[edge_to_idx[(path[i-1], path[i])], pair_to_idx[pair]] +=",
"1 nodes_to_norm.add(node) ## Normalize for node in nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute",
"first = True edge_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths = dict()",
"np.array(denominator) normalized_counts = numerator / denominator total_betweenness = normalized_counts.sum(axis=1) route_betweenness = {edge:total_betweenness[idx] for",
"def route_node_betweenness_from_paths(G, filtered_paths): ''' Computes route betweenness for nodes starting from set of",
"number of nodes; could be done by iterating over pairs of nodes in",
"def route_node_betweenness_from_file(filename): ''' Computes route betweenness for nodes by reading file filename. Uses",
"betweenness for nodes starting from set of paths filtered_paths. Uses G only to",
"node in path: node_to_pair_dict.setdefault(node, dict()) node_to_pair_dict[node].setdefault(prev_pair, 0) node_to_pair_dict[node][prev_pair] += 1 nodes_to_norm.add(node) ## Normalize",
"for edge, idx in edge_to_idx.items()} return route_betweenness def route_edge_betweenness_from_file(filename): ''' Computes route betweenness",
"## Normalize for node in nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by",
"by len(filtered_paths) edge_to_idx = {edge:idx for idx, edge in enumerate(G.edges())} pair_to_idx = {pair:idx",
"filtered_paths. Uses G only to get the number of nodes; could be done",
"## Handle the last pair for path in filtered_paths[prev_pair]: nodes_to_norm = set() for",
"not first: edges_to_norm = set() for path in filtered_paths[prev_pair]: for i in range(1,",
"filtered_paths.setdefault(pair, list()) filtered_paths[pair].append(path) if pair != prev_pair and not first: paths_to_norm = set()",
"route_edge_betweenness_from_file(filename): ''' Computes route betweenness for edges by reading file filename. Uses dictionaries",
"for path in filtered_paths[prev_pair]: for i in range(1, len(path)): edge = path[i-1], path[i]",
"numerator[node_to_idx[node], pair_to_idx[pair]] += 1 denominator = np.array(denominator) normalized_counts = numerator / denominator total_betweenness",
"summing over all pairs for each node route_betweenness = {node:sum(node_to_pair_dict[node].values()) for node in",
"for computations. ''' ## Zero array of dimensions len(G.edges()) by len(filtered_paths) edge_to_idx =",
"path.strip().split(',') pair = (path[0], path[-1]) filtered_paths.setdefault(pair, list()) filtered_paths[pair].append(path) if pair != prev_pair and",
"node in node_to_pair_dict} return route_betweenness def route_edge_betweenness_from_paths(G, filtered_paths): ''' Computes route betweenness for",
"edges starting from set of paths filtered_paths. Uses G only to get the",
"path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all pairs for each",
"1 nodes_to_norm.add(node) ## Normalize for node in nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter +=",
"filtered_paths: denominator.append(len(filtered_paths[pair])) for path in filtered_paths[pair]: for node in path: numerator[node_to_idx[node], pair_to_idx[pair]] +=",
"= False ## Handle the last pair for path in filtered_paths[prev_pair]: paths_to_norm =",
"{pair:idx for idx, pair in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.edges()), len(filtered_paths))) denominator = []",
"first: edges_to_norm = set() for path in filtered_paths[prev_pair]: for i in range(1, len(path)):",
"path in paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all",
"## Zero array of dimensions len(G.edges()) by len(filtered_paths) edge_to_idx = {edge:idx for idx,",
"node in nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all",
"filtered_paths[pair]: for i in range(1, len(path)): numerator[edge_to_idx[(path[i-1], path[i])], pair_to_idx[pair]] += 1 denominator =",
"0) path_to_pair_dict[kpath][prev_pair] += 1 paths_to_norm.add(kpath) ## Normalize for path in paths_to_norm: path_to_pair_dict[path][prev_pair] /=",
"*_ = line.strip().split('|') path = path.strip().split(',') pair = (path[0], path[-1]) filtered_paths.setdefault(pair, list()) filtered_paths[pair].append(path)",
"= 0 total_pairs = 0 first = True node_to_pair_dict = dict() prev_pair =",
"array of dimensions len(G.edges()) by len(filtered_paths) edge_to_idx = {edge:idx for idx, edge in",
"+= 1 nodes_to_norm.add(node) ## Normalize for node in nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter",
"pair in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.nodes()), len(filtered_paths))) denominator = [] for pair in",
"first = True node_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths = dict()",
"edges_to_norm = set() for path in filtered_paths[prev_pair]: for i in range(1, len(path)): edge",
"+= 1 edges_to_norm.add(edge) ## Normalize for edge in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) ##",
"!= prev_pair and not first: edges_to_norm = set() for path in filtered_paths[prev_pair]: for",
"node_to_idx = {node:idx for idx, node in enumerate(G.nodes())} pair_to_idx = {pair:idx for idx,",
"path in filtered_paths[prev_pair]: for i in range(0, len(path)-k): kpath = tuple(path[i:i+k+1]) path_to_pair_dict.setdefault(kpath, dict())",
"1 paths_to_norm.add(kpath) ## Normalize for path in paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter +=",
"denominator total_betweenness = normalized_counts.sum(axis=1) route_betweenness = {node:total_betweenness[idx] for node, idx in node_to_idx.items()} return",
"edge_to_pair_dict[edge].setdefault(prev_pair, 0) edge_to_pair_dict[edge][prev_pair] += 1 edges_to_norm.add(edge) ## Normalize for edge in edges_to_norm: edge_to_pair_dict[edge][prev_pair]",
"len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all pairs for each node route_betweenness",
"betweenness for nodes by reading file filename. Uses dictionaries for computations. ''' pair_counter",
"nodes_to_norm = set() for node in path: node_to_pair_dict.setdefault(node, dict()) node_to_pair_dict[node].setdefault(prev_pair, 0) node_to_pair_dict[node][prev_pair] +=",
"pair in filtered_paths: denominator.append(len(filtered_paths[pair])) for path in filtered_paths[pair]: for i in range(1, len(path)):",
"the last pair for path in filtered_paths[prev_pair]: nodes_to_norm = set() for node in",
"def route_path_betweenness_from_file(filename, k): ''' Computes route betweenness for paths by reading file filename.",
"in edge_to_idx.items()} return route_betweenness def route_edge_betweenness_from_file(filename): ''' Computes route betweenness for edges by",
"in nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs += 1 if pair_counter",
"= (-1, -1) filtered_paths = dict() with open(filename, 'r') as fin: for line",
"''' Computes route betweenness for edges by reading file filename. Uses dictionaries for",
"node_to_pair_dict[node][prev_pair] += 1 nodes_to_norm.add(node) ## Normalize for node in nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair])",
"node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all pairs for each",
"range(0, len(path)-k): kpath = tuple(path[i:i+k+1]) path_to_pair_dict.setdefault(kpath, dict()) path_to_pair_dict[kpath].setdefault(prev_pair, 0) path_to_pair_dict[kpath][prev_pair] += 1 paths_to_norm.add(kpath)",
"path in filtered_paths[pair]: for i in range(1, len(path)): numerator[edge_to_idx[(path[i-1], path[i])], pair_to_idx[pair]] += 1",
"edge = path[i-1], path[i] edge_to_pair_dict.setdefault(edge, dict()) edge_to_pair_dict[edge].setdefault(prev_pair, 0) edge_to_pair_dict[edge][prev_pair] += 1 edges_to_norm.add(edge) ##",
"by iterating over pairs of nodes in filtered_paths or given as input parameter.",
"in filtered_paths or given as input parameter. Uses dense numpy arrays for computations.",
"len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs += 1 if pair_counter == 150_000: print(f\"{total_pairs} processed.\",",
"prev_pair and not first: edges_to_norm = set() for path in filtered_paths[prev_pair]: for i",
"not first: nodes_to_norm = set() for path in filtered_paths[prev_pair]: for node in path:",
"the number of nodes; could be done by iterating over pairs of nodes",
"for nodes starting from set of paths filtered_paths. Uses G only to get",
"pair for path in filtered_paths[prev_pair]: nodes_to_norm = set() for node in path: node_to_pair_dict.setdefault(node,",
"numpy arrays for computations. ''' ## Zero array of dimensions len(G.edges()) by len(filtered_paths)",
"pair = (path[0], path[-1]) filtered_paths.setdefault(pair, list()) filtered_paths[pair].append(path) if pair != prev_pair and not",
"computations. ''' pair_counter = 0 total_pairs = 0 first = True edge_to_pair_dict =",
"edge_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths = dict() with open(filename, 'r')",
"in filtered_paths: denominator.append(len(filtered_paths[pair])) for path in filtered_paths[pair]: for node in path: numerator[node_to_idx[node], pair_to_idx[pair]]",
"path[i])], pair_to_idx[pair]] += 1 denominator = np.array(denominator) normalized_counts = numerator / denominator total_betweenness",
"i in range(1, len(path)): edge = path[i-1], path[i] edge_to_pair_dict.setdefault(edge, dict()) edge_to_pair_dict[edge].setdefault(prev_pair, 0) edge_to_pair_dict[edge][prev_pair]",
"pair_to_idx = {pair:idx for idx, pair in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.edges()), len(filtered_paths))) denominator",
"node in nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs += 1 if",
"len(path)): numerator[edge_to_idx[(path[i-1], path[i])], pair_to_idx[pair]] += 1 denominator = np.array(denominator) normalized_counts = numerator /",
"for each edge route_betweenness = {edge:sum(edge_to_pair_dict[edge].values()) for edge in edge_to_pair_dict} return route_betweenness def",
"= pair if first: first = False ## Handle the last pair for",
"in range(0, len(path)-k): kpath = tuple(path[i:i+k+1]) path_to_pair_dict.setdefault(kpath, dict()) path_to_pair_dict[kpath].setdefault(prev_pair, 0) path_to_pair_dict[kpath][prev_pair] += 1",
"filename. Uses dictionaries for computations. ''' pair_counter = 0 total_pairs = 0 first",
"given as input parameter. Uses dense numpy arrays for computations. ''' ## Zero",
"numerator / denominator total_betweenness = normalized_counts.sum(axis=1) route_betweenness = {node:total_betweenness[idx] for node, idx in",
"betweenness for edges starting from set of paths filtered_paths. Uses G only to",
"betweenness for edges by reading file filename. Uses dictionaries for computations. ''' pair_counter",
"pairs for each path route_betweenness = {path:sum(path_to_pair_dict[path].values()) for path in path_to_pair_dict} return route_betweenness",
"node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs += 1 if pair_counter == 150_000:",
"fin: for line in fin: path, *_ = line.strip().split('|') path = path.strip().split(',') pair",
"get the number of nodes; could be done by iterating over pairs of",
"return route_betweenness def route_node_betweenness_from_file(filename): ''' Computes route betweenness for nodes by reading file",
"np.zeros((len(G.nodes()), len(filtered_paths))) denominator = [] for pair in filtered_paths: denominator.append(len(filtered_paths[pair])) for path in",
"in filtered_paths: denominator.append(len(filtered_paths[pair])) for path in filtered_paths[pair]: for i in range(1, len(path)): numerator[edge_to_idx[(path[i-1],",
"path: node_to_pair_dict.setdefault(node, dict()) node_to_pair_dict[node].setdefault(prev_pair, 0) node_to_pair_dict[node][prev_pair] += 1 nodes_to_norm.add(node) ## Normalize for node",
"Handle the last pair for path in filtered_paths[prev_pair]: edges_to_norm = set() for i",
"if pair != prev_pair and not first: paths_to_norm = set() for path in",
"enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.edges()), len(filtered_paths))) denominator = [] for pair in filtered_paths: denominator.append(len(filtered_paths[pair]))",
"all pairs for each edge route_betweenness = {edge:sum(edge_to_pair_dict[edge].values()) for edge in edge_to_pair_dict} return",
"total_betweenness = normalized_counts.sum(axis=1) route_betweenness = {edge:total_betweenness[idx] for edge, idx in edge_to_idx.items()} return route_betweenness",
"and not first: edges_to_norm = set() for path in filtered_paths[prev_pair]: for i in",
"in node_to_idx.items()} return route_betweenness def route_node_betweenness_from_file(filename): ''' Computes route betweenness for nodes by",
"for node in nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over",
"set() for path in filtered_paths[prev_pair]: for i in range(1, len(path)): edge = path[i-1],",
"pair for path in filtered_paths[prev_pair]: edges_to_norm = set() for i in range(1, len(path)):",
"Computes route betweenness for nodes by reading file filename. Uses dictionaries for computations.",
"dense numpy arrays for computations. ''' ## Zero array of dimensions len(G.nodes()) by",
"dict()) edge_to_pair_dict[edge].setdefault(prev_pair, 0) edge_to_pair_dict[edge][prev_pair] += 1 edges_to_norm.add(edge) ## Normalize for edge in edges_to_norm:",
"= set() for path in filtered_paths[prev_pair]: for i in range(0, len(path)-k): kpath =",
"path[-1]) filtered_paths.setdefault(pair, list()) filtered_paths[pair].append(path) if pair != prev_pair and not first: edges_to_norm =",
"summing over all pairs for each path route_betweenness = {path:sum(path_to_pair_dict[path].values()) for path in",
"denominator.append(len(filtered_paths[pair])) for path in filtered_paths[pair]: for i in range(1, len(path)): numerator[edge_to_idx[(path[i-1], path[i])], pair_to_idx[pair]]",
"numerator = np.zeros((len(G.nodes()), len(filtered_paths))) denominator = [] for pair in filtered_paths: denominator.append(len(filtered_paths[pair])) for",
"Compute betweenness by summing over all pairs for each node route_betweenness = {node:sum(node_to_pair_dict[node].values())",
"''' Computes route betweenness for paths by reading file filename. Uses dictionaries for",
"nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all pairs for",
"return route_betweenness def route_edge_betweenness_from_file(filename): ''' Computes route betweenness for edges by reading file",
"route_betweenness = {edge:sum(edge_to_pair_dict[edge].values()) for edge in edge_to_pair_dict} return route_betweenness def route_path_betweenness_from_file(filename, k): '''",
"total_betweenness = normalized_counts.sum(axis=1) route_betweenness = {node:total_betweenness[idx] for node, idx in node_to_idx.items()} return route_betweenness",
"route betweenness for edges starting from set of paths filtered_paths. Uses G only",
"in enumerate(G.nodes())} pair_to_idx = {pair:idx for idx, pair in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.nodes()),",
"for edges starting from set of paths filtered_paths. Uses G only to get",
"edge_to_pair_dict[edge][prev_pair] += 1 edges_to_norm.add(edge) ## Normalize for edge in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair])",
"denominator = np.array(denominator) normalized_counts = numerator / denominator total_betweenness = normalized_counts.sum(axis=1) route_betweenness =",
"edge in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs += 1 if",
"paths_to_norm = set() for i in range(0, len(path)-k): kpath = tuple(path[i:i+k+1]) path_to_pair_dict.setdefault(kpath, dict())",
"the last pair for path in filtered_paths[prev_pair]: paths_to_norm = set() for i in",
"prev_pair = pair if first: first = False ## Handle the last pair",
"summing over all pairs for each edge route_betweenness = {edge:sum(edge_to_pair_dict[edge].values()) for edge in",
"be done by iterating over pairs of nodes in filtered_paths or given as",
"route_betweenness = {node:total_betweenness[idx] for node, idx in node_to_idx.items()} return route_betweenness def route_node_betweenness_from_file(filename): '''",
"path in filtered_paths[prev_pair]: edges_to_norm = set() for i in range(1, len(path)): edge =",
"first = False ## Handle the last pair for path in filtered_paths[prev_pair]: paths_to_norm",
"parameter. Uses dense numpy arrays for computations. ''' ## Zero array of dimensions",
"normalized_counts = numerator / denominator total_betweenness = normalized_counts.sum(axis=1) route_betweenness = {node:total_betweenness[idx] for node,",
"Computes route betweenness for paths by reading file filename. Uses dictionaries for computations.",
"path in filtered_paths[prev_pair]: for node in path: node_to_pair_dict.setdefault(node, dict()) node_to_pair_dict[node].setdefault(prev_pair, 0) node_to_pair_dict[node][prev_pair] +=",
"node in path: numerator[node_to_idx[node], pair_to_idx[pair]] += 1 denominator = np.array(denominator) normalized_counts = numerator",
"= np.array(denominator) normalized_counts = numerator / denominator total_betweenness = normalized_counts.sum(axis=1) route_betweenness = {node:total_betweenness[idx]",
"computations. ''' ## Zero array of dimensions len(G.nodes()) by len(filtered_paths) node_to_idx = {node:idx",
"filtered_paths.setdefault(pair, list()) filtered_paths[pair].append(path) if pair != prev_pair and not first: edges_to_norm = set()",
"set() for path in filtered_paths[prev_pair]: for node in path: node_to_pair_dict.setdefault(node, dict()) node_to_pair_dict[node].setdefault(prev_pair, 0)",
"edge_to_idx = {edge:idx for idx, edge in enumerate(G.edges())} pair_to_idx = {pair:idx for idx,",
"= set() for node in path: node_to_pair_dict.setdefault(node, dict()) node_to_pair_dict[node].setdefault(prev_pair, 0) node_to_pair_dict[node][prev_pair] += 1",
"edge in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all",
"Uses G only to get the number of nodes; could be done by",
"route_betweenness def route_path_betweenness_from_file(filename, k): ''' Computes route betweenness for paths by reading file",
"path in paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs += 1 if",
"as np import networkx as nx def route_node_betweenness_from_paths(G, filtered_paths): ''' Computes route betweenness",
"of paths filtered_paths. Uses G only to get the number of nodes; could",
"G only to get the number of nodes; could be done by iterating",
"## Normalize for path in paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs",
"edges_to_norm = set() for i in range(1, len(path)): edge = path[i-1], path[i] edge_to_pair_dict.setdefault(edge,",
"True path_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths = dict() with open(filename,",
"networkx as nx def route_node_betweenness_from_paths(G, filtered_paths): ''' Computes route betweenness for nodes starting",
"<gh_stars>0 import numpy as np import networkx as nx def route_node_betweenness_from_paths(G, filtered_paths): '''",
"## Compute betweenness by summing over all pairs for each path route_betweenness =",
"over pairs of nodes in filtered_paths or given as input parameter. Uses dense",
"all pairs for each node route_betweenness = {node:sum(node_to_pair_dict[node].values()) for node in node_to_pair_dict} return",
"total_pairs = 0 first = True path_to_pair_dict = dict() prev_pair = (-1, -1)",
"for path in filtered_paths[prev_pair]: for i in range(0, len(path)-k): kpath = tuple(path[i:i+k+1]) path_to_pair_dict.setdefault(kpath,",
"''' pair_counter = 0 total_pairs = 0 first = True edge_to_pair_dict = dict()",
"betweenness for paths by reading file filename. Uses dictionaries for computations. ''' pair_counter",
"= set() for i in range(1, len(path)): edge = path[i-1], path[i] edge_to_pair_dict.setdefault(edge, dict())",
"= True path_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths = dict() with",
"node_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths = dict() with open(filename, 'r')",
"1 edges_to_norm.add(edge) ## Normalize for edge in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute",
"= path.strip().split(',') pair = (path[0], path[-1]) filtered_paths.setdefault(pair, list()) filtered_paths[pair].append(path) if pair != prev_pair",
"edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs += 1 if pair_counter ==",
"route betweenness for edges by reading file filename. Uses dictionaries for computations. '''",
"/= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs += 1 if pair_counter == 150_000: print(f\"{total_pairs}",
"1 total_pairs += 1 if pair_counter == 150_000: print(f\"{total_pairs} processed.\", flush=True) pair_counter =",
"kpath = tuple(path[i:i+k+1]) path_to_pair_dict.setdefault(kpath, dict()) path_to_pair_dict[kpath].setdefault(prev_pair, 0) path_to_pair_dict[kpath][prev_pair] += 1 paths_to_norm.add(kpath) ## Normalize",
"+= 1 denominator = np.array(denominator) normalized_counts = numerator / denominator total_betweenness = normalized_counts.sum(axis=1)",
"for edge in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs += 1",
"in enumerate(G.edges())} pair_to_idx = {pair:idx for idx, pair in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.edges()),",
"filtered_paths): ''' Computes route betweenness for edges starting from set of paths filtered_paths.",
"return route_betweenness def route_path_betweenness_from_file(filename, k): ''' Computes route betweenness for paths by reading",
"for pair in filtered_paths: denominator.append(len(filtered_paths[pair])) for path in filtered_paths[pair]: for i in range(1,",
"in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs += 1 if pair_counter",
"computations. ''' pair_counter = 0 total_pairs = 0 first = True node_to_pair_dict =",
"= True node_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths = dict() with",
"all pairs for each path route_betweenness = {path:sum(path_to_pair_dict[path].values()) for path in path_to_pair_dict} return",
"numpy as np import networkx as nx def route_node_betweenness_from_paths(G, filtered_paths): ''' Computes route",
"{node:idx for idx, node in enumerate(G.nodes())} pair_to_idx = {pair:idx for idx, pair in",
"Compute betweenness by summing over all pairs for each edge route_betweenness = {edge:sum(edge_to_pair_dict[edge].values())",
"total_pairs += 1 if pair_counter == 150_000: print(f\"{total_pairs} processed.\", flush=True) pair_counter = 0",
"= True edge_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths = dict() with",
"set() for i in range(0, len(path)-k): kpath = tuple(path[i:i+k+1]) path_to_pair_dict.setdefault(kpath, dict()) path_to_pair_dict[kpath].setdefault(prev_pair, 0)",
"numpy arrays for computations. ''' ## Zero array of dimensions len(G.nodes()) by len(filtered_paths)",
"tuple(path[i:i+k+1]) path_to_pair_dict.setdefault(kpath, dict()) path_to_pair_dict[kpath].setdefault(prev_pair, 0) path_to_pair_dict[kpath][prev_pair] += 1 paths_to_norm.add(kpath) ## Normalize for path",
"reading file filename. Uses dictionaries for computations. ''' pair_counter = 0 total_pairs =",
"for path in filtered_paths[prev_pair]: edges_to_norm = set() for i in range(1, len(path)): edge",
"## Normalize for edge in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs",
"idx in node_to_idx.items()} return route_betweenness def route_node_betweenness_from_file(filename): ''' Computes route betweenness for nodes",
"pair_to_idx = {pair:idx for idx, pair in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.nodes()), len(filtered_paths))) denominator",
"range(1, len(path)): edge = path[i-1], path[i] edge_to_pair_dict.setdefault(edge, dict()) edge_to_pair_dict[edge].setdefault(prev_pair, 0) edge_to_pair_dict[edge][prev_pair] += 1",
"= tuple(path[i:i+k+1]) path_to_pair_dict.setdefault(kpath, dict()) path_to_pair_dict[kpath].setdefault(prev_pair, 0) path_to_pair_dict[kpath][prev_pair] += 1 paths_to_norm.add(kpath) ## Normalize for",
"route_node_betweenness_from_file(filename): ''' Computes route betweenness for nodes by reading file filename. Uses dictionaries",
"Computes route betweenness for nodes starting from set of paths filtered_paths. Uses G",
"filtered_paths: denominator.append(len(filtered_paths[pair])) for path in filtered_paths[pair]: for i in range(1, len(path)): numerator[edge_to_idx[(path[i-1], path[i])],",
"for computations. ''' pair_counter = 0 total_pairs = 0 first = True path_to_pair_dict",
"if pair != prev_pair and not first: nodes_to_norm = set() for path in",
"for idx, pair in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.nodes()), len(filtered_paths))) denominator = [] for",
"= {edge:total_betweenness[idx] for edge, idx in edge_to_idx.items()} return route_betweenness def route_edge_betweenness_from_file(filename): ''' Computes",
"filtered_paths = dict() with open(filename, 'r') as fin: for line in fin: path,",
"return route_betweenness def route_edge_betweenness_from_paths(G, filtered_paths): ''' Computes route betweenness for edges starting from",
"== 150_000: print(f\"{total_pairs} processed.\", flush=True) pair_counter = 0 prev_pair = pair if first:",
"i in range(0, len(path)-k): kpath = tuple(path[i:i+k+1]) path_to_pair_dict.setdefault(kpath, dict()) path_to_pair_dict[kpath].setdefault(prev_pair, 0) path_to_pair_dict[kpath][prev_pair] +=",
"by reading file filename. Uses dictionaries for computations. ''' pair_counter = 0 total_pairs",
"list()) filtered_paths[pair].append(path) if pair != prev_pair and not first: paths_to_norm = set() for",
"in filtered_paths[pair]: for node in path: numerator[node_to_idx[node], pair_to_idx[pair]] += 1 denominator = np.array(denominator)",
"idx in edge_to_idx.items()} return route_betweenness def route_edge_betweenness_from_file(filename): ''' Computes route betweenness for edges",
"1 denominator = np.array(denominator) normalized_counts = numerator / denominator total_betweenness = normalized_counts.sum(axis=1) route_betweenness",
"len(filtered_paths))) denominator = [] for pair in filtered_paths: denominator.append(len(filtered_paths[pair])) for path in filtered_paths[pair]:",
"Handle the last pair for path in filtered_paths[prev_pair]: nodes_to_norm = set() for node",
"pair != prev_pair and not first: paths_to_norm = set() for path in filtered_paths[prev_pair]:",
"for computations. ''' ## Zero array of dimensions len(G.nodes()) by len(filtered_paths) node_to_idx =",
"node, idx in node_to_idx.items()} return route_betweenness def route_node_betweenness_from_file(filename): ''' Computes route betweenness for",
"only to get the number of nodes; could be done by iterating over",
"dict() with open(filename, 'r') as fin: for line in fin: path, *_ =",
"''' Computes route betweenness for edges starting from set of paths filtered_paths. Uses",
"= 0 first = True path_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths",
"in path: node_to_pair_dict.setdefault(node, dict()) node_to_pair_dict[node].setdefault(prev_pair, 0) node_to_pair_dict[node][prev_pair] += 1 nodes_to_norm.add(node) ## Normalize for",
"Zero array of dimensions len(G.edges()) by len(filtered_paths) edge_to_idx = {edge:idx for idx, edge",
"by summing over all pairs for each edge route_betweenness = {edge:sum(edge_to_pair_dict[edge].values()) for edge",
"iterating over pairs of nodes in filtered_paths or given as input parameter. Uses",
"filtered_paths[prev_pair]: for i in range(0, len(path)-k): kpath = tuple(path[i:i+k+1]) path_to_pair_dict.setdefault(kpath, dict()) path_to_pair_dict[kpath].setdefault(prev_pair, 0)",
"idx, edge in enumerate(G.edges())} pair_to_idx = {pair:idx for idx, pair in enumerate(filtered_paths.keys())} numerator",
"for each node route_betweenness = {node:sum(node_to_pair_dict[node].values()) for node in node_to_pair_dict} return route_betweenness def",
"(path[0], path[-1]) filtered_paths.setdefault(pair, list()) filtered_paths[pair].append(path) if pair != prev_pair and not first: nodes_to_norm",
"Uses dense numpy arrays for computations. ''' ## Zero array of dimensions len(G.edges())",
"node in enumerate(G.nodes())} pair_to_idx = {pair:idx for idx, pair in enumerate(filtered_paths.keys())} numerator =",
"first = True path_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths = dict()",
"pair_to_idx[pair]] += 1 denominator = np.array(denominator) normalized_counts = numerator / denominator total_betweenness =",
"route_betweenness def route_edge_betweenness_from_paths(G, filtered_paths): ''' Computes route betweenness for edges starting from set",
"nodes starting from set of paths filtered_paths. Uses G only to get the",
"filtered_paths[pair]: for node in path: numerator[node_to_idx[node], pair_to_idx[pair]] += 1 denominator = np.array(denominator) normalized_counts",
"edges_to_norm.add(edge) ## Normalize for edge in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1",
"= [] for pair in filtered_paths: denominator.append(len(filtered_paths[pair])) for path in filtered_paths[pair]: for node",
"= normalized_counts.sum(axis=1) route_betweenness = {node:total_betweenness[idx] for node, idx in node_to_idx.items()} return route_betweenness def",
"for edge in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over",
"0 first = True node_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths =",
"over all pairs for each node route_betweenness = {node:sum(node_to_pair_dict[node].values()) for node in node_to_pair_dict}",
"computations. ''' ## Zero array of dimensions len(G.edges()) by len(filtered_paths) edge_to_idx = {edge:idx",
"nodes by reading file filename. Uses dictionaries for computations. ''' pair_counter = 0",
"path_to_pair_dict[kpath][prev_pair] += 1 paths_to_norm.add(kpath) ## Normalize for path in paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair])",
"for path in filtered_paths[pair]: for node in path: numerator[node_to_idx[node], pair_to_idx[pair]] += 1 denominator",
"nodes; could be done by iterating over pairs of nodes in filtered_paths or",
"path_to_pair_dict[kpath].setdefault(prev_pair, 0) path_to_pair_dict[kpath][prev_pair] += 1 paths_to_norm.add(kpath) ## Normalize for path in paths_to_norm: path_to_pair_dict[path][prev_pair]",
"in path: numerator[node_to_idx[node], pair_to_idx[pair]] += 1 denominator = np.array(denominator) normalized_counts = numerator /",
"paths by reading file filename. Uses dictionaries for computations. ''' pair_counter = 0",
"from set of paths filtered_paths. Uses G only to get the number of",
"0 prev_pair = pair if first: first = False ## Handle the last",
"last pair for path in filtered_paths[prev_pair]: paths_to_norm = set() for i in range(0,",
"0) edge_to_pair_dict[edge][prev_pair] += 1 edges_to_norm.add(edge) ## Normalize for edge in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /=",
"## Compute betweenness by summing over all pairs for each edge route_betweenness =",
"''' Computes route betweenness for nodes starting from set of paths filtered_paths. Uses",
"node_to_pair_dict.setdefault(node, dict()) node_to_pair_dict[node].setdefault(prev_pair, 0) node_to_pair_dict[node][prev_pair] += 1 nodes_to_norm.add(node) ## Normalize for node in",
"= 0 first = True edge_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths",
"Uses dictionaries for computations. ''' pair_counter = 0 total_pairs = 0 first =",
"## Normalize for edge in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by",
"= set() for path in filtered_paths[prev_pair]: for node in path: node_to_pair_dict.setdefault(node, dict()) node_to_pair_dict[node].setdefault(prev_pair,",
"normalized_counts.sum(axis=1) route_betweenness = {edge:total_betweenness[idx] for edge, idx in edge_to_idx.items()} return route_betweenness def route_edge_betweenness_from_file(filename):",
"for path in paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs += 1",
"pair_counter = 0 total_pairs = 0 first = True node_to_pair_dict = dict() prev_pair",
"of dimensions len(G.edges()) by len(filtered_paths) edge_to_idx = {edge:idx for idx, edge in enumerate(G.edges())}",
"in edge_to_pair_dict} return route_betweenness def route_path_betweenness_from_file(filename, k): ''' Computes route betweenness for paths",
"normalized_counts = numerator / denominator total_betweenness = normalized_counts.sum(axis=1) route_betweenness = {edge:total_betweenness[idx] for edge,",
"for path in filtered_paths[prev_pair]: paths_to_norm = set() for i in range(0, len(path)-k): kpath",
"for node in nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs += 1",
"= set() for i in range(0, len(path)-k): kpath = tuple(path[i:i+k+1]) path_to_pair_dict.setdefault(kpath, dict()) path_to_pair_dict[kpath].setdefault(prev_pair,",
"/= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all pairs for each node",
"fin: path, *_ = line.strip().split('|') path = path.strip().split(',') pair = (path[0], path[-1]) filtered_paths.setdefault(pair,",
"route betweenness for paths by reading file filename. Uses dictionaries for computations. '''",
"computations. ''' pair_counter = 0 total_pairs = 0 first = True path_to_pair_dict =",
"over all pairs for each edge route_betweenness = {edge:sum(edge_to_pair_dict[edge].values()) for edge in edge_to_pair_dict}",
"0 total_pairs = 0 first = True path_to_pair_dict = dict() prev_pair = (-1,",
"pairs for each edge route_betweenness = {edge:sum(edge_to_pair_dict[edge].values()) for edge in edge_to_pair_dict} return route_betweenness",
"paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs += 1 if pair_counter ==",
"Uses dense numpy arrays for computations. ''' ## Zero array of dimensions len(G.nodes())",
"paths_to_norm.add(kpath) ## Normalize for path in paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1",
"pair in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.edges()), len(filtered_paths))) denominator = [] for pair in",
"denominator.append(len(filtered_paths[pair])) for path in filtered_paths[pair]: for node in path: numerator[node_to_idx[node], pair_to_idx[pair]] += 1",
"path in filtered_paths[pair]: for node in path: numerator[node_to_idx[node], pair_to_idx[pair]] += 1 denominator =",
"np.array(denominator) normalized_counts = numerator / denominator total_betweenness = normalized_counts.sum(axis=1) route_betweenness = {node:total_betweenness[idx] for",
"len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all pairs for each path route_betweenness",
"nodes in filtered_paths or given as input parameter. Uses dense numpy arrays for",
"for path in filtered_paths[prev_pair]: for node in path: node_to_pair_dict.setdefault(node, dict()) node_to_pair_dict[node].setdefault(prev_pair, 0) node_to_pair_dict[node][prev_pair]",
"## Normalize for path in paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by",
"= normalized_counts.sum(axis=1) route_betweenness = {edge:total_betweenness[idx] for edge, idx in edge_to_idx.items()} return route_betweenness def",
"print(f\"{total_pairs} processed.\", flush=True) pair_counter = 0 prev_pair = pair if first: first =",
"## Handle the last pair for path in filtered_paths[prev_pair]: paths_to_norm = set() for",
"pair_counter = 0 total_pairs = 0 first = True path_to_pair_dict = dict() prev_pair",
"pair_counter += 1 total_pairs += 1 if pair_counter == 150_000: print(f\"{total_pairs} processed.\", flush=True)",
"arrays for computations. ''' ## Zero array of dimensions len(G.edges()) by len(filtered_paths) edge_to_idx",
"filtered_paths[pair].append(path) if pair != prev_pair and not first: edges_to_norm = set() for path",
"line.strip().split('|') path = path.strip().split(',') pair = (path[0], path[-1]) filtered_paths.setdefault(pair, list()) filtered_paths[pair].append(path) if pair",
"and not first: paths_to_norm = set() for path in filtered_paths[prev_pair]: for i in",
"dict()) node_to_pair_dict[node].setdefault(prev_pair, 0) node_to_pair_dict[node][prev_pair] += 1 nodes_to_norm.add(node) ## Normalize for node in nodes_to_norm:",
"filtered_paths[prev_pair]: edges_to_norm = set() for i in range(1, len(path)): edge = path[i-1], path[i]",
"edge, idx in edge_to_idx.items()} return route_betweenness def route_edge_betweenness_from_file(filename): ''' Computes route betweenness for",
"+= 1 paths_to_norm.add(kpath) ## Normalize for path in paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) ##",
"in filtered_paths[prev_pair]: for i in range(0, len(path)-k): kpath = tuple(path[i:i+k+1]) path_to_pair_dict.setdefault(kpath, dict()) path_to_pair_dict[kpath].setdefault(prev_pair,",
"in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.edges()), len(filtered_paths))) denominator = [] for pair in filtered_paths:",
"path[-1]) filtered_paths.setdefault(pair, list()) filtered_paths[pair].append(path) if pair != prev_pair and not first: nodes_to_norm =",
"= numerator / denominator total_betweenness = normalized_counts.sum(axis=1) route_betweenness = {node:total_betweenness[idx] for node, idx",
"for paths by reading file filename. Uses dictionaries for computations. ''' pair_counter =",
"= np.array(denominator) normalized_counts = numerator / denominator total_betweenness = normalized_counts.sum(axis=1) route_betweenness = {edge:total_betweenness[idx]",
"1 if pair_counter == 150_000: print(f\"{total_pairs} processed.\", flush=True) pair_counter = 0 prev_pair =",
"dense numpy arrays for computations. ''' ## Zero array of dimensions len(G.edges()) by",
"path in filtered_paths[prev_pair]: paths_to_norm = set() for i in range(0, len(path)-k): kpath =",
"by summing over all pairs for each node route_betweenness = {node:sum(node_to_pair_dict[node].values()) for node",
"denominator = [] for pair in filtered_paths: denominator.append(len(filtered_paths[pair])) for path in filtered_paths[pair]: for",
"enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.nodes()), len(filtered_paths))) denominator = [] for pair in filtered_paths: denominator.append(len(filtered_paths[pair]))",
"edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs += 1 if pair_counter == 150_000:",
"and not first: nodes_to_norm = set() for path in filtered_paths[prev_pair]: for node in",
"paths_to_norm.add(kpath) ## Normalize for path in paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness",
"(path[0], path[-1]) filtered_paths.setdefault(pair, list()) filtered_paths[pair].append(path) if pair != prev_pair and not first: edges_to_norm",
"as nx def route_node_betweenness_from_paths(G, filtered_paths): ''' Computes route betweenness for nodes starting from",
"paths_to_norm = set() for path in filtered_paths[prev_pair]: for i in range(0, len(path)-k): kpath",
"input parameter. Uses dense numpy arrays for computations. ''' ## Zero array of",
"{node:total_betweenness[idx] for node, idx in node_to_idx.items()} return route_betweenness def route_node_betweenness_from_file(filename): ''' Computes route",
"in fin: path, *_ = line.strip().split('|') path = path.strip().split(',') pair = (path[0], path[-1])",
"filtered_paths or given as input parameter. Uses dense numpy arrays for computations. '''",
"prev_pair = (-1, -1) filtered_paths = dict() with open(filename, 'r') as fin: for",
"= {node:idx for idx, node in enumerate(G.nodes())} pair_to_idx = {pair:idx for idx, pair",
"for pair in filtered_paths: denominator.append(len(filtered_paths[pair])) for path in filtered_paths[pair]: for node in path:",
"route_betweenness def route_node_betweenness_from_file(filename): ''' Computes route betweenness for nodes by reading file filename.",
"route_betweenness = {node:sum(node_to_pair_dict[node].values()) for node in node_to_pair_dict} return route_betweenness def route_edge_betweenness_from_paths(G, filtered_paths): '''",
"path in filtered_paths[prev_pair]: nodes_to_norm = set() for node in path: node_to_pair_dict.setdefault(node, dict()) node_to_pair_dict[node].setdefault(prev_pair,",
"Normalize for path in paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing",
"= {pair:idx for idx, pair in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.nodes()), len(filtered_paths))) denominator =",
"{edge:sum(edge_to_pair_dict[edge].values()) for edge in edge_to_pair_dict} return route_betweenness def route_path_betweenness_from_file(filename, k): ''' Computes route",
"= False ## Handle the last pair for path in filtered_paths[prev_pair]: nodes_to_norm =",
"edges by reading file filename. Uses dictionaries for computations. ''' pair_counter = 0",
"list()) filtered_paths[pair].append(path) if pair != prev_pair and not first: edges_to_norm = set() for",
"each node route_betweenness = {node:sum(node_to_pair_dict[node].values()) for node in node_to_pair_dict} return route_betweenness def route_edge_betweenness_from_paths(G,",
"= [] for pair in filtered_paths: denominator.append(len(filtered_paths[pair])) for path in filtered_paths[pair]: for i",
"if first: first = False ## Handle the last pair for path in",
"filtered_paths): ''' Computes route betweenness for nodes starting from set of paths filtered_paths.",
"nx def route_node_betweenness_from_paths(G, filtered_paths): ''' Computes route betweenness for nodes starting from set",
"Normalize for node in nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs +=",
"(-1, -1) filtered_paths = dict() with open(filename, 'r') as fin: for line in",
"i in range(1, len(path)): numerator[edge_to_idx[(path[i-1], path[i])], pair_to_idx[pair]] += 1 denominator = np.array(denominator) normalized_counts",
"path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs += 1 if pair_counter == 150_000:",
"dictionaries for computations. ''' pair_counter = 0 total_pairs = 0 first = True",
"dimensions len(G.edges()) by len(filtered_paths) edge_to_idx = {edge:idx for idx, edge in enumerate(G.edges())} pair_to_idx",
"pair if first: first = False ## Handle the last pair for path",
"Normalize for node in nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing",
"for i in range(0, len(path)-k): kpath = tuple(path[i:i+k+1]) path_to_pair_dict.setdefault(kpath, dict()) path_to_pair_dict[kpath].setdefault(prev_pair, 0) path_to_pair_dict[kpath][prev_pair]",
"edge_to_idx.items()} return route_betweenness def route_edge_betweenness_from_file(filename): ''' Computes route betweenness for edges by reading",
"or given as input parameter. Uses dense numpy arrays for computations. ''' ##",
"len(G.nodes()) by len(filtered_paths) node_to_idx = {node:idx for idx, node in enumerate(G.nodes())} pair_to_idx =",
"node_to_pair_dict} return route_betweenness def route_edge_betweenness_from_paths(G, filtered_paths): ''' Computes route betweenness for edges starting",
"filtered_paths[prev_pair]: for i in range(1, len(path)): edge = path[i-1], path[i] edge_to_pair_dict.setdefault(edge, dict()) edge_to_pair_dict[edge].setdefault(prev_pair,",
"= 0 first = True node_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths",
"file filename. Uses dictionaries for computations. ''' pair_counter = 0 total_pairs = 0",
"dict()) path_to_pair_dict[kpath].setdefault(prev_pair, 0) path_to_pair_dict[kpath][prev_pair] += 1 paths_to_norm.add(kpath) ## Normalize for path in paths_to_norm:",
"import networkx as nx def route_node_betweenness_from_paths(G, filtered_paths): ''' Computes route betweenness for nodes",
"nodes_to_norm.add(node) ## Normalize for node in nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1",
"filtered_paths[pair].append(path) if pair != prev_pair and not first: nodes_to_norm = set() for path",
"edge route_betweenness = {edge:sum(edge_to_pair_dict[edge].values()) for edge in edge_to_pair_dict} return route_betweenness def route_path_betweenness_from_file(filename, k):",
"150_000: print(f\"{total_pairs} processed.\", flush=True) pair_counter = 0 prev_pair = pair if first: first",
"edge in edge_to_pair_dict} return route_betweenness def route_path_betweenness_from_file(filename, k): ''' Computes route betweenness for",
"path[-1]) filtered_paths.setdefault(pair, list()) filtered_paths[pair].append(path) if pair != prev_pair and not first: paths_to_norm =",
"= {pair:idx for idx, pair in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.edges()), len(filtered_paths))) denominator =",
"''' Computes route betweenness for nodes by reading file filename. Uses dictionaries for",
"arrays for computations. ''' ## Zero array of dimensions len(G.nodes()) by len(filtered_paths) node_to_idx",
"= {edge:idx for idx, edge in enumerate(G.edges())} pair_to_idx = {pair:idx for idx, pair",
"range(1, len(path)): numerator[edge_to_idx[(path[i-1], path[i])], pair_to_idx[pair]] += 1 denominator = np.array(denominator) normalized_counts = numerator",
"''' pair_counter = 0 total_pairs = 0 first = True node_to_pair_dict = dict()",
"total_pairs = 0 first = True node_to_pair_dict = dict() prev_pair = (-1, -1)",
"pairs for each node route_betweenness = {node:sum(node_to_pair_dict[node].values()) for node in node_to_pair_dict} return route_betweenness",
"pair for path in filtered_paths[prev_pair]: paths_to_norm = set() for i in range(0, len(path)-k):",
"set() for path in filtered_paths[prev_pair]: for i in range(0, len(path)-k): kpath = tuple(path[i:i+k+1])",
"edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all pairs for each",
"starting from set of paths filtered_paths. Uses G only to get the number",
"Zero array of dimensions len(G.nodes()) by len(filtered_paths) node_to_idx = {node:idx for idx, node",
"route betweenness for nodes starting from set of paths filtered_paths. Uses G only",
"'r') as fin: for line in fin: path, *_ = line.strip().split('|') path =",
"for idx, node in enumerate(G.nodes())} pair_to_idx = {pair:idx for idx, pair in enumerate(filtered_paths.keys())}",
"pair != prev_pair and not first: edges_to_norm = set() for path in filtered_paths[prev_pair]:",
"done by iterating over pairs of nodes in filtered_paths or given as input",
"in nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all pairs",
"nodes_to_norm = set() for path in filtered_paths[prev_pair]: for node in path: node_to_pair_dict.setdefault(node, dict())",
"first = False ## Handle the last pair for path in filtered_paths[prev_pair]: edges_to_norm",
"by summing over all pairs for each path route_betweenness = {path:sum(path_to_pair_dict[path].values()) for path",
"in range(1, len(path)): numerator[edge_to_idx[(path[i-1], path[i])], pair_to_idx[pair]] += 1 denominator = np.array(denominator) normalized_counts =",
"0 total_pairs = 0 first = True edge_to_pair_dict = dict() prev_pair = (-1,",
"prev_pair and not first: paths_to_norm = set() for path in filtered_paths[prev_pair]: for i",
"True node_to_pair_dict = dict() prev_pair = (-1, -1) filtered_paths = dict() with open(filename,",
"for edges by reading file filename. Uses dictionaries for computations. ''' pair_counter =",
"of dimensions len(G.nodes()) by len(filtered_paths) node_to_idx = {node:idx for idx, node in enumerate(G.nodes())}",
"= set() for path in filtered_paths[prev_pair]: for i in range(1, len(path)): edge =",
"in filtered_paths[prev_pair]: for node in path: node_to_pair_dict.setdefault(node, dict()) node_to_pair_dict[node].setdefault(prev_pair, 0) node_to_pair_dict[node][prev_pair] += 1",
"Normalize for path in paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs +=",
"in filtered_paths[prev_pair]: nodes_to_norm = set() for node in path: node_to_pair_dict.setdefault(node, dict()) node_to_pair_dict[node].setdefault(prev_pair, 0)",
"''' ## Zero array of dimensions len(G.edges()) by len(filtered_paths) edge_to_idx = {edge:idx for",
"def route_edge_betweenness_from_file(filename): ''' Computes route betweenness for edges by reading file filename. Uses",
"first: nodes_to_norm = set() for path in filtered_paths[prev_pair]: for node in path: node_to_pair_dict.setdefault(node,",
"path, *_ = line.strip().split('|') path = path.strip().split(',') pair = (path[0], path[-1]) filtered_paths.setdefault(pair, list())",
"/ denominator total_betweenness = normalized_counts.sum(axis=1) route_betweenness = {edge:total_betweenness[idx] for edge, idx in edge_to_idx.items()}",
"Compute betweenness by summing over all pairs for each path route_betweenness = {path:sum(path_to_pair_dict[path].values())",
"in node_to_pair_dict} return route_betweenness def route_edge_betweenness_from_paths(G, filtered_paths): ''' Computes route betweenness for edges",
"Normalize for edge in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs +=",
"= np.zeros((len(G.nodes()), len(filtered_paths))) denominator = [] for pair in filtered_paths: denominator.append(len(filtered_paths[pair])) for path",
"len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all pairs for each edge route_betweenness",
"of nodes in filtered_paths or given as input parameter. Uses dense numpy arrays",
"over all pairs for each path route_betweenness = {path:sum(path_to_pair_dict[path].values()) for path in path_to_pair_dict}",
"as fin: for line in fin: path, *_ = line.strip().split('|') path = path.strip().split(',')",
"[] for pair in filtered_paths: denominator.append(len(filtered_paths[pair])) for path in filtered_paths[pair]: for node in",
"## Normalize for node in nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs",
"dict() prev_pair = (-1, -1) filtered_paths = dict() with open(filename, 'r') as fin:",
"route_betweenness = {edge:total_betweenness[idx] for edge, idx in edge_to_idx.items()} return route_betweenness def route_edge_betweenness_from_file(filename): '''",
"/ denominator total_betweenness = normalized_counts.sum(axis=1) route_betweenness = {node:total_betweenness[idx] for node, idx in node_to_idx.items()}",
"= 0 prev_pair = pair if first: first = False ## Handle the",
"= {edge:sum(edge_to_pair_dict[edge].values()) for edge in edge_to_pair_dict} return route_betweenness def route_path_betweenness_from_file(filename, k): ''' Computes",
"set() for i in range(1, len(path)): edge = path[i-1], path[i] edge_to_pair_dict.setdefault(edge, dict()) edge_to_pair_dict[edge].setdefault(prev_pair,",
"/= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all pairs for each edge",
"np import networkx as nx def route_node_betweenness_from_paths(G, filtered_paths): ''' Computes route betweenness for",
"pair_counter = 0 total_pairs = 0 first = True edge_to_pair_dict = dict() prev_pair",
"line in fin: path, *_ = line.strip().split('|') path = path.strip().split(',') pair = (path[0],",
"-1) filtered_paths = dict() with open(filename, 'r') as fin: for line in fin:",
"in filtered_paths[prev_pair]: edges_to_norm = set() for i in range(1, len(path)): edge = path[i-1],",
"route_path_betweenness_from_file(filename, k): ''' Computes route betweenness for paths by reading file filename. Uses",
"for node in path: node_to_pair_dict.setdefault(node, dict()) node_to_pair_dict[node].setdefault(prev_pair, 0) node_to_pair_dict[node][prev_pair] += 1 nodes_to_norm.add(node) ##",
"idx, pair in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.edges()), len(filtered_paths))) denominator = [] for pair",
"path[i] edge_to_pair_dict.setdefault(edge, dict()) edge_to_pair_dict[edge].setdefault(prev_pair, 0) edge_to_pair_dict[edge][prev_pair] += 1 edges_to_norm.add(edge) ## Normalize for edge",
"of nodes; could be done by iterating over pairs of nodes in filtered_paths",
"= 0 total_pairs = 0 first = True path_to_pair_dict = dict() prev_pair =",
"path in filtered_paths[prev_pair]: for i in range(1, len(path)): edge = path[i-1], path[i] edge_to_pair_dict.setdefault(edge,",
"pair in filtered_paths: denominator.append(len(filtered_paths[pair])) for path in filtered_paths[pair]: for node in path: numerator[node_to_idx[node],",
"= dict() with open(filename, 'r') as fin: for line in fin: path, *_",
"numerator = np.zeros((len(G.edges()), len(filtered_paths))) denominator = [] for pair in filtered_paths: denominator.append(len(filtered_paths[pair])) for",
"for node, idx in node_to_idx.items()} return route_betweenness def route_node_betweenness_from_file(filename): ''' Computes route betweenness",
"for i in range(1, len(path)): numerator[edge_to_idx[(path[i-1], path[i])], pair_to_idx[pair]] += 1 denominator = np.array(denominator)",
"betweenness by summing over all pairs for each path route_betweenness = {path:sum(path_to_pair_dict[path].values()) for",
"0) node_to_pair_dict[node][prev_pair] += 1 nodes_to_norm.add(node) ## Normalize for node in nodes_to_norm: node_to_pair_dict[node][prev_pair] /=",
"+= 1 paths_to_norm.add(kpath) ## Normalize for path in paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter",
"if pair_counter == 150_000: print(f\"{total_pairs} processed.\", flush=True) pair_counter = 0 prev_pair = pair",
"len(filtered_paths) edge_to_idx = {edge:idx for idx, edge in enumerate(G.edges())} pair_to_idx = {pair:idx for",
"processed.\", flush=True) pair_counter = 0 prev_pair = pair if first: first = False",
"for path in paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over",
"for line in fin: path, *_ = line.strip().split('|') path = path.strip().split(',') pair =",
"in paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter += 1 total_pairs += 1 if pair_counter",
"path[i-1], path[i] edge_to_pair_dict.setdefault(edge, dict()) edge_to_pair_dict[edge].setdefault(prev_pair, 0) edge_to_pair_dict[edge][prev_pair] += 1 edges_to_norm.add(edge) ## Normalize for",
"= (path[0], path[-1]) filtered_paths.setdefault(pair, list()) filtered_paths[pair].append(path) if pair != prev_pair and not first:",
"for idx, pair in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.edges()), len(filtered_paths))) denominator = [] for",
"last pair for path in filtered_paths[prev_pair]: nodes_to_norm = set() for node in path:",
"for path in filtered_paths[prev_pair]: nodes_to_norm = set() for node in path: node_to_pair_dict.setdefault(node, dict())",
"def route_edge_betweenness_from_paths(G, filtered_paths): ''' Computes route betweenness for edges starting from set of",
"normalized_counts.sum(axis=1) route_betweenness = {node:total_betweenness[idx] for node, idx in node_to_idx.items()} return route_betweenness def route_node_betweenness_from_file(filename):",
"= 0 total_pairs = 0 first = True edge_to_pair_dict = dict() prev_pair =",
"[] for pair in filtered_paths: denominator.append(len(filtered_paths[pair])) for path in filtered_paths[pair]: for i in",
"= numerator / denominator total_betweenness = normalized_counts.sum(axis=1) route_betweenness = {edge:total_betweenness[idx] for edge, idx",
"filtered_paths[prev_pair]: nodes_to_norm = set() for node in path: node_to_pair_dict.setdefault(node, dict()) node_to_pair_dict[node].setdefault(prev_pair, 0) node_to_pair_dict[node][prev_pair]",
"for edge in edge_to_pair_dict} return route_betweenness def route_path_betweenness_from_file(filename, k): ''' Computes route betweenness",
"+= 1 nodes_to_norm.add(node) ## Normalize for node in nodes_to_norm: node_to_pair_dict[node][prev_pair] /= len(filtered_paths[prev_pair]) ##",
"in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all pairs",
"!= prev_pair and not first: nodes_to_norm = set() for path in filtered_paths[prev_pair]: for",
"/= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all pairs for each path",
"## Zero array of dimensions len(G.nodes()) by len(filtered_paths) node_to_idx = {node:idx for idx,",
"node_to_idx.items()} return route_betweenness def route_node_betweenness_from_file(filename): ''' Computes route betweenness for nodes by reading",
"list()) filtered_paths[pair].append(path) if pair != prev_pair and not first: nodes_to_norm = set() for",
"{pair:idx for idx, pair in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.nodes()), len(filtered_paths))) denominator = []",
"open(filename, 'r') as fin: for line in fin: path, *_ = line.strip().split('|') path",
"betweenness by summing over all pairs for each node route_betweenness = {node:sum(node_to_pair_dict[node].values()) for",
"filtered_paths[pair].append(path) if pair != prev_pair and not first: paths_to_norm = set() for path",
"1 edges_to_norm.add(edge) ## Normalize for edge in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) pair_counter +=",
"edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all pairs for",
"np.zeros((len(G.edges()), len(filtered_paths))) denominator = [] for pair in filtered_paths: denominator.append(len(filtered_paths[pair])) for path in",
"pair != prev_pair and not first: nodes_to_norm = set() for path in filtered_paths[prev_pair]:",
"+= 1 if pair_counter == 150_000: print(f\"{total_pairs} processed.\", flush=True) pair_counter = 0 prev_pair",
"len(path)-k): kpath = tuple(path[i:i+k+1]) path_to_pair_dict.setdefault(kpath, dict()) path_to_pair_dict[kpath].setdefault(prev_pair, 0) path_to_pair_dict[kpath][prev_pair] += 1 paths_to_norm.add(kpath) ##",
"idx, node in enumerate(G.nodes())} pair_to_idx = {pair:idx for idx, pair in enumerate(filtered_paths.keys())} numerator",
"False ## Handle the last pair for path in filtered_paths[prev_pair]: nodes_to_norm = set()",
"path_to_pair_dict.setdefault(kpath, dict()) path_to_pair_dict[kpath].setdefault(prev_pair, 0) path_to_pair_dict[kpath][prev_pair] += 1 paths_to_norm.add(kpath) ## Normalize for path in",
"could be done by iterating over pairs of nodes in filtered_paths or given",
"import numpy as np import networkx as nx def route_node_betweenness_from_paths(G, filtered_paths): ''' Computes",
"paths filtered_paths. Uses G only to get the number of nodes; could be",
"path = path.strip().split(',') pair = (path[0], path[-1]) filtered_paths.setdefault(pair, list()) filtered_paths[pair].append(path) if pair !=",
"enumerate(G.edges())} pair_to_idx = {pair:idx for idx, pair in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.edges()), len(filtered_paths)))",
"0 total_pairs = 0 first = True node_to_pair_dict = dict() prev_pair = (-1,",
"enumerate(G.nodes())} pair_to_idx = {pair:idx for idx, pair in enumerate(filtered_paths.keys())} numerator = np.zeros((len(G.nodes()), len(filtered_paths)))",
"with open(filename, 'r') as fin: for line in fin: path, *_ = line.strip().split('|')",
"edges_to_norm.add(edge) ## Normalize for edge in edges_to_norm: edge_to_pair_dict[edge][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness",
"+= 1 total_pairs += 1 if pair_counter == 150_000: print(f\"{total_pairs} processed.\", flush=True) pair_counter",
"{edge:total_betweenness[idx] for edge, idx in edge_to_idx.items()} return route_betweenness def route_edge_betweenness_from_file(filename): ''' Computes route",
"each edge route_betweenness = {edge:sum(edge_to_pair_dict[edge].values()) for edge in edge_to_pair_dict} return route_betweenness def route_path_betweenness_from_file(filename,",
"to get the number of nodes; could be done by iterating over pairs",
"if pair != prev_pair and not first: edges_to_norm = set() for path in",
"route_betweenness def route_edge_betweenness_from_file(filename): ''' Computes route betweenness for edges by reading file filename.",
"numerator / denominator total_betweenness = normalized_counts.sum(axis=1) route_betweenness = {edge:total_betweenness[idx] for edge, idx in",
"= np.zeros((len(G.edges()), len(filtered_paths))) denominator = [] for pair in filtered_paths: denominator.append(len(filtered_paths[pair])) for path",
"route_edge_betweenness_from_paths(G, filtered_paths): ''' Computes route betweenness for edges starting from set of paths",
"numerator[edge_to_idx[(path[i-1], path[i])], pair_to_idx[pair]] += 1 denominator = np.array(denominator) normalized_counts = numerator / denominator",
"Computes route betweenness for edges starting from set of paths filtered_paths. Uses G",
"array of dimensions len(G.nodes()) by len(filtered_paths) node_to_idx = {node:idx for idx, node in",
"= dict() prev_pair = (-1, -1) filtered_paths = dict() with open(filename, 'r') as",
"pairs of nodes in filtered_paths or given as input parameter. Uses dense numpy",
"paths_to_norm: path_to_pair_dict[path][prev_pair] /= len(filtered_paths[prev_pair]) ## Compute betweenness by summing over all pairs for",
"node route_betweenness = {node:sum(node_to_pair_dict[node].values()) for node in node_to_pair_dict} return route_betweenness def route_edge_betweenness_from_paths(G, filtered_paths):",
"len(filtered_paths) node_to_idx = {node:idx for idx, node in enumerate(G.nodes())} pair_to_idx = {pair:idx for",
"last pair for path in filtered_paths[prev_pair]: edges_to_norm = set() for i in range(1,",
"= path[i-1], path[i] edge_to_pair_dict.setdefault(edge, dict()) edge_to_pair_dict[edge].setdefault(prev_pair, 0) edge_to_pair_dict[edge][prev_pair] += 1 edges_to_norm.add(edge) ## Normalize",
"total_pairs = 0 first = True edge_to_pair_dict = dict() prev_pair = (-1, -1)",
"not first: paths_to_norm = set() for path in filtered_paths[prev_pair]: for i in range(0,",
"len(path)): edge = path[i-1], path[i] edge_to_pair_dict.setdefault(edge, dict()) edge_to_pair_dict[edge].setdefault(prev_pair, 0) edge_to_pair_dict[edge][prev_pair] += 1 edges_to_norm.add(edge)"
] |
[
"print (p[0], \"has fewer than 10 moons.\") except FileNotFoundError: print (\"There is no",
"i in range (0, 8): # Read a line as string s s",
"Open the file try: infile = open (\"planets.txt\", \"r\") # Read (skip over)",
"Break s into components based on commas giving list P p = s.split",
"\"has fewer than 10 moons.\") except FileNotFoundError: print (\"There is no file named",
"ten (10) moons # Open the file try: infile = open (\"planets.txt\", \"r\")",
"moons # Open the file try: infile = open (\"planets.txt\", \"r\") # Read",
"the file try: infile = open (\"planets.txt\", \"r\") # Read (skip over) the",
"p = s.split (\",\") # If p[10] < 10 print the planet name,",
"(\"planets.txt\", \"r\") # Read (skip over) the header line s = infile.readline() #",
"= s.split (\",\") # If p[10] < 10 print the planet name, which",
"name, which is p[0] if int(p[10])<10: print (p[0], \"has fewer than 10 moons.\")",
"giving list P p = s.split (\",\") # If p[10] < 10 print",
"which is p[0] if int(p[10])<10: print (p[0], \"has fewer than 10 moons.\") except",
"s = infile.readline() # Break s into components based on commas giving list",
"than ten (10) moons # Open the file try: infile = open (\"planets.txt\",",
"If p[10] < 10 print the planet name, which is p[0] if int(p[10])<10:",
"= infile.readline() # For each planet for i in range (0, 8): #",
"moons.\") except FileNotFoundError: print (\"There is no file named 'planets.txt'. Please try again\")",
"print the planet name, which is p[0] if int(p[10])<10: print (p[0], \"has fewer",
"a line as string s s = infile.readline() # Break s into components",
"fewer than ten (10) moons # Open the file try: infile = open",
"This program prints the names of planets having fewer than ten (10) moons",
"(0, 8): # Read a line as string s s = infile.readline() #",
"Read (skip over) the header line s = infile.readline() # For each planet",
"infile.readline() # Break s into components based on commas giving list P p",
"for i in range (0, 8): # Read a line as string s",
"planets having fewer than ten (10) moons # Open the file try: infile",
"names of planets having fewer than ten (10) moons # Open the file",
"components based on commas giving list P p = s.split (\",\") # If",
"< 10 print the planet name, which is p[0] if int(p[10])<10: print (p[0],",
"p[0] if int(p[10])<10: print (p[0], \"has fewer than 10 moons.\") except FileNotFoundError: print",
"# Read a line as string s s = infile.readline() # Break s",
"p[10] < 10 print the planet name, which is p[0] if int(p[10])<10: print",
"Input and Output/planets.py # This program prints the names of planets having fewer",
"int(p[10])<10: print (p[0], \"has fewer than 10 moons.\") except FileNotFoundError: print (\"There is",
"header line s = infile.readline() # For each planet for i in range",
"the planet name, which is p[0] if int(p[10])<10: print (p[0], \"has fewer than",
"and Output/planets.py # This program prints the names of planets having fewer than",
"(p[0], \"has fewer than 10 moons.\") except FileNotFoundError: print (\"There is no file",
"# If p[10] < 10 print the planet name, which is p[0] if",
"infile.readline() # For each planet for i in range (0, 8): # Read",
"over) the header line s = infile.readline() # For each planet for i",
"- Files Input and Output/planets.py # This program prints the names of planets",
"# Read (skip over) the header line s = infile.readline() # For each",
"s into components based on commas giving list P p = s.split (\",\")",
"Output/planets.py # This program prints the names of planets having fewer than ten",
"Read a line as string s s = infile.readline() # Break s into",
"having fewer than ten (10) moons # Open the file try: infile =",
"(\",\") # If p[10] < 10 print the planet name, which is p[0]",
"(10) moons # Open the file try: infile = open (\"planets.txt\", \"r\") #",
"open (\"planets.txt\", \"r\") # Read (skip over) the header line s = infile.readline()",
"line s = infile.readline() # For each planet for i in range (0,",
"# Open the file try: infile = open (\"planets.txt\", \"r\") # Read (skip",
"commas giving list P p = s.split (\",\") # If p[10] < 10",
"file try: infile = open (\"planets.txt\", \"r\") # Read (skip over) the header",
"based on commas giving list P p = s.split (\",\") # If p[10]",
"program prints the names of planets having fewer than ten (10) moons #",
"try: infile = open (\"planets.txt\", \"r\") # Read (skip over) the header line",
"# For each planet for i in range (0, 8): # Read a",
"Files Input and Output/planets.py # This program prints the names of planets having",
"P p = s.split (\",\") # If p[10] < 10 print the planet",
"\"r\") # Read (skip over) the header line s = infile.readline() # For",
"the names of planets having fewer than ten (10) moons # Open the",
"s = infile.readline() # For each planet for i in range (0, 8):",
"on commas giving list P p = s.split (\",\") # If p[10] <",
"as string s s = infile.readline() # Break s into components based on",
"s s = infile.readline() # Break s into components based on commas giving",
"prints the names of planets having fewer than ten (10) moons # Open",
"the header line s = infile.readline() # For each planet for i in",
"planet for i in range (0, 8): # Read a line as string",
"is p[0] if int(p[10])<10: print (p[0], \"has fewer than 10 moons.\") except FileNotFoundError:",
"each planet for i in range (0, 8): # Read a line as",
"range (0, 8): # Read a line as string s s = infile.readline()",
"8): # Read a line as string s s = infile.readline() # Break",
"For each planet for i in range (0, 8): # Read a line",
"= infile.readline() # Break s into components based on commas giving list P",
"if int(p[10])<10: print (p[0], \"has fewer than 10 moons.\") except FileNotFoundError: print (\"There",
"line as string s s = infile.readline() # Break s into components based",
"in range (0, 8): # Read a line as string s s =",
"planet name, which is p[0] if int(p[10])<10: print (p[0], \"has fewer than 10",
"fewer than 10 moons.\") except FileNotFoundError: print (\"There is no file named 'planets.txt'.",
"into components based on commas giving list P p = s.split (\",\") #",
"# This program prints the names of planets having fewer than ten (10)",
"(skip over) the header line s = infile.readline() # For each planet for",
"<filename>language/python/pocket-primer/CH5 - Files Input and Output/planets.py # This program prints the names of",
"10 print the planet name, which is p[0] if int(p[10])<10: print (p[0], \"has",
"= open (\"planets.txt\", \"r\") # Read (skip over) the header line s =",
"of planets having fewer than ten (10) moons # Open the file try:",
"# Break s into components based on commas giving list P p =",
"list P p = s.split (\",\") # If p[10] < 10 print the",
"infile = open (\"planets.txt\", \"r\") # Read (skip over) the header line s",
"10 moons.\") except FileNotFoundError: print (\"There is no file named 'planets.txt'. Please try",
"than 10 moons.\") except FileNotFoundError: print (\"There is no file named 'planets.txt'. Please",
"s.split (\",\") # If p[10] < 10 print the planet name, which is",
"string s s = infile.readline() # Break s into components based on commas"
] |
[
"username, password, dirname): if not dirname: dirname = username command = \"useradd -p",
"return ('Cannot delete user',1) def updatePriv(self,username): command = \"usermod -aG sudo \"+username try:",
"try: val = self.conn.sudo(command,password=self.rootPass,hide=True).stdout.strip() return ('User Created: '+username,0) except Exception as e: return",
"= \"usermod -aG sudo \"+username try: val = self.conn.sudo(command,password=self.rootPass).stdout.strip() return ('User Privilege Granted',0)",
"-aG sudo \"+username try: val = self.conn.sudo(command,password=self.rootPass).stdout.strip() return ('User Privilege Granted',0) except Exception",
"= \"awk -F: '{ print $1}' /etc/passwd\" return self.conn.run(command,hide=True).stdout.strip() def deluser(self,username): command =",
"return ('User Deleted: '+username,0) except Exception as e: return ('Cannot delete user',1) def",
"sudo \"+username try: val = self.conn.sudo(command,password=self.rootPass).stdout.strip() return ('User Privilege Granted',0) except Exception as",
"\"+username try: val = self.conn.sudo(command,password=self.rootPass).stdout.strip() return ('User Privilege Granted',0) except Exception as e:",
"\"+username try: val = self.conn.sudo(command,password=self.<PASSWORD>,hide=True).stdout.strip() return ('User Deleted: '+username,0) except Exception as e:",
"as e: return ('Cannot Grant user Privileges',1) op = OperationsUtil() # print(op.createUser(\"test\", \"test\")[0])",
"delete user',1) def updatePriv(self,username): command = \"usermod -aG sudo \"+username try: val =",
"('Cannot delete user',1) def updatePriv(self,username): command = \"usermod -aG sudo \"+username try: val",
"val = self.conn.sudo(command,password=self.rootPass,hide=True).stdout.strip() return ('User Created: '+username,0) except Exception as e: return ('Cannot",
"('User Privilege Granted',0) except Exception as e: return ('Cannot Grant user Privileges',1) op",
"<gh_stars>0 from fabric import Connection class OperationsUtil(): def __init__(self): self.rootUser=\"ubuntu20\" self.rootPass=\"<PASSWORD>!\" self.conn=Connection(host='ubuntu20@10.109.34.222',connect_kwargs={\"password\": self.rootPass})",
"user Privileges',1) op = OperationsUtil() # print(op.createUser(\"test\", \"test\")[0]) # print(op.viewUser()) # print(op.updatePriv(\"test\")[0]) print(op.deluser(\"test1\")[0])",
"Created: '+username,0) except Exception as e: return ('Cannot create user',1) def viewUser(self): command",
"self.conn.sudo(command,password=self.rootPass).stdout.strip() return ('User Privilege Granted',0) except Exception as e: return ('Cannot Grant user",
"from fabric import Connection class OperationsUtil(): def __init__(self): self.rootUser=\"ubuntu20\" self.rootPass=\"<PASSWORD>!\" self.conn=Connection(host='ubuntu20@10.109.34.222',connect_kwargs={\"password\": self.rootPass}) def",
"username command = \"useradd -p \"+password+\" -m -d /home/\"+dirname+\"/ -g users -s /bin/bash",
"'+username,0) except Exception as e: return ('Cannot create user',1) def viewUser(self): command =",
"import Connection class OperationsUtil(): def __init__(self): self.rootUser=\"ubuntu20\" self.rootPass=\"<PASSWORD>!\" self.conn=Connection(host='ubuntu20@10.109.34.222',connect_kwargs={\"password\": self.rootPass}) def createUser(self, username,",
"/home/\"+dirname+\"/ -g users -s /bin/bash \"+username try: val = self.conn.sudo(command,password=self.rootPass,hide=True).stdout.strip() return ('User Created:",
"create user',1) def viewUser(self): command = \"awk -F: '{ print $1}' /etc/passwd\" return",
"return self.conn.run(command,hide=True).stdout.strip() def deluser(self,username): command = \"userdel -f \"+username try: val = self.conn.sudo(command,password=self.<PASSWORD>,hide=True).stdout.strip()",
"except Exception as e: return ('Cannot create user',1) def viewUser(self): command = \"awk",
"def deluser(self,username): command = \"userdel -f \"+username try: val = self.conn.sudo(command,password=self.<PASSWORD>,hide=True).stdout.strip() return ('User",
"= self.conn.sudo(command,password=self.rootPass,hide=True).stdout.strip() return ('User Created: '+username,0) except Exception as e: return ('Cannot create",
"-f \"+username try: val = self.conn.sudo(command,password=self.<PASSWORD>,hide=True).stdout.strip() return ('User Deleted: '+username,0) except Exception as",
"dirname: dirname = username command = \"useradd -p \"+password+\" -m -d /home/\"+dirname+\"/ -g",
"command = \"usermod -aG sudo \"+username try: val = self.conn.sudo(command,password=self.rootPass).stdout.strip() return ('User Privilege",
"command = \"awk -F: '{ print $1}' /etc/passwd\" return self.conn.run(command,hide=True).stdout.strip() def deluser(self,username): command",
"return ('Cannot Grant user Privileges',1) op = OperationsUtil() # print(op.createUser(\"test\", \"test\")[0]) # print(op.viewUser())",
"self.rootUser=\"ubuntu20\" self.rootPass=\"<PASSWORD>!\" self.conn=Connection(host='ubuntu20@10.109.34.222',connect_kwargs={\"password\": self.rootPass}) def createUser(self, username, password, dirname): if not dirname: dirname",
"return ('User Created: '+username,0) except Exception as e: return ('Cannot create user',1) def",
"= \"userdel -f \"+username try: val = self.conn.sudo(command,password=self.<PASSWORD>,hide=True).stdout.strip() return ('User Deleted: '+username,0) except",
"user',1) def updatePriv(self,username): command = \"usermod -aG sudo \"+username try: val = self.conn.sudo(command,password=self.rootPass).stdout.strip()",
"command = \"useradd -p \"+password+\" -m -d /home/\"+dirname+\"/ -g users -s /bin/bash \"+username",
"__init__(self): self.rootUser=\"ubuntu20\" self.rootPass=\"<PASSWORD>!\" self.conn=Connection(host='ubuntu20@10.109.34.222',connect_kwargs={\"password\": self.rootPass}) def createUser(self, username, password, dirname): if not dirname:",
"OperationsUtil(): def __init__(self): self.rootUser=\"ubuntu20\" self.rootPass=\"<PASSWORD>!\" self.conn=Connection(host='ubuntu20@10.109.34.222',connect_kwargs={\"password\": self.rootPass}) def createUser(self, username, password, dirname): if",
"self.conn.sudo(command,password=self.<PASSWORD>,hide=True).stdout.strip() return ('User Deleted: '+username,0) except Exception as e: return ('Cannot delete user',1)",
"as e: return ('Cannot create user',1) def viewUser(self): command = \"awk -F: '{",
"self.rootPass}) def createUser(self, username, password, dirname): if not dirname: dirname = username command",
"-g users -s /bin/bash \"+username try: val = self.conn.sudo(command,password=self.rootPass,hide=True).stdout.strip() return ('User Created: '+username,0)",
"= self.conn.sudo(command,password=self.rootPass).stdout.strip() return ('User Privilege Granted',0) except Exception as e: return ('Cannot Grant",
"try: val = self.conn.sudo(command,password=self.<PASSWORD>,hide=True).stdout.strip() return ('User Deleted: '+username,0) except Exception as e: return",
"('User Deleted: '+username,0) except Exception as e: return ('Cannot delete user',1) def updatePriv(self,username):",
"-d /home/\"+dirname+\"/ -g users -s /bin/bash \"+username try: val = self.conn.sudo(command,password=self.rootPass,hide=True).stdout.strip() return ('User",
"if not dirname: dirname = username command = \"useradd -p \"+password+\" -m -d",
"= \"useradd -p \"+password+\" -m -d /home/\"+dirname+\"/ -g users -s /bin/bash \"+username try:",
"self.conn.run(command,hide=True).stdout.strip() def deluser(self,username): command = \"userdel -f \"+username try: val = self.conn.sudo(command,password=self.<PASSWORD>,hide=True).stdout.strip() return",
"-F: '{ print $1}' /etc/passwd\" return self.conn.run(command,hide=True).stdout.strip() def deluser(self,username): command = \"userdel -f",
"try: val = self.conn.sudo(command,password=self.rootPass).stdout.strip() return ('User Privilege Granted',0) except Exception as e: return",
"not dirname: dirname = username command = \"useradd -p \"+password+\" -m -d /home/\"+dirname+\"/",
"password, dirname): if not dirname: dirname = username command = \"useradd -p \"+password+\"",
"('User Created: '+username,0) except Exception as e: return ('Cannot create user',1) def viewUser(self):",
"command = \"userdel -f \"+username try: val = self.conn.sudo(command,password=self.<PASSWORD>,hide=True).stdout.strip() return ('User Deleted: '+username,0)",
"\"+password+\" -m -d /home/\"+dirname+\"/ -g users -s /bin/bash \"+username try: val = self.conn.sudo(command,password=self.rootPass,hide=True).stdout.strip()",
"= username command = \"useradd -p \"+password+\" -m -d /home/\"+dirname+\"/ -g users -s",
"return ('Cannot create user',1) def viewUser(self): command = \"awk -F: '{ print $1}'",
"fabric import Connection class OperationsUtil(): def __init__(self): self.rootUser=\"ubuntu20\" self.rootPass=\"<PASSWORD>!\" self.conn=Connection(host='ubuntu20@10.109.34.222',connect_kwargs={\"password\": self.rootPass}) def createUser(self,",
"\"useradd -p \"+password+\" -m -d /home/\"+dirname+\"/ -g users -s /bin/bash \"+username try: val",
"Deleted: '+username,0) except Exception as e: return ('Cannot delete user',1) def updatePriv(self,username): command",
"Granted',0) except Exception as e: return ('Cannot Grant user Privileges',1) op = OperationsUtil()",
"/etc/passwd\" return self.conn.run(command,hide=True).stdout.strip() def deluser(self,username): command = \"userdel -f \"+username try: val =",
"def updatePriv(self,username): command = \"usermod -aG sudo \"+username try: val = self.conn.sudo(command,password=self.rootPass).stdout.strip() return",
"Connection class OperationsUtil(): def __init__(self): self.rootUser=\"ubuntu20\" self.rootPass=\"<PASSWORD>!\" self.conn=Connection(host='ubuntu20@10.109.34.222',connect_kwargs={\"password\": self.rootPass}) def createUser(self, username, password,",
"e: return ('Cannot Grant user Privileges',1) op = OperationsUtil() # print(op.createUser(\"test\", \"test\")[0]) #",
"self.rootPass=\"<PASSWORD>!\" self.conn=Connection(host='ubuntu20@10.109.34.222',connect_kwargs={\"password\": self.rootPass}) def createUser(self, username, password, dirname): if not dirname: dirname =",
"except Exception as e: return ('Cannot delete user',1) def updatePriv(self,username): command = \"usermod",
"-p \"+password+\" -m -d /home/\"+dirname+\"/ -g users -s /bin/bash \"+username try: val =",
"self.conn.sudo(command,password=self.rootPass,hide=True).stdout.strip() return ('User Created: '+username,0) except Exception as e: return ('Cannot create user',1)",
"print $1}' /etc/passwd\" return self.conn.run(command,hide=True).stdout.strip() def deluser(self,username): command = \"userdel -f \"+username try:",
"e: return ('Cannot create user',1) def viewUser(self): command = \"awk -F: '{ print",
"val = self.conn.sudo(command,password=self.<PASSWORD>,hide=True).stdout.strip() return ('User Deleted: '+username,0) except Exception as e: return ('Cannot",
"('Cannot Grant user Privileges',1) op = OperationsUtil() # print(op.createUser(\"test\", \"test\")[0]) # print(op.viewUser()) #",
"viewUser(self): command = \"awk -F: '{ print $1}' /etc/passwd\" return self.conn.run(command,hide=True).stdout.strip() def deluser(self,username):",
"as e: return ('Cannot delete user',1) def updatePriv(self,username): command = \"usermod -aG sudo",
"dirname): if not dirname: dirname = username command = \"useradd -p \"+password+\" -m",
"users -s /bin/bash \"+username try: val = self.conn.sudo(command,password=self.rootPass,hide=True).stdout.strip() return ('User Created: '+username,0) except",
"Exception as e: return ('Cannot delete user',1) def updatePriv(self,username): command = \"usermod -aG",
"Exception as e: return ('Cannot create user',1) def viewUser(self): command = \"awk -F:",
"user',1) def viewUser(self): command = \"awk -F: '{ print $1}' /etc/passwd\" return self.conn.run(command,hide=True).stdout.strip()",
"deluser(self,username): command = \"userdel -f \"+username try: val = self.conn.sudo(command,password=self.<PASSWORD>,hide=True).stdout.strip() return ('User Deleted:",
"\"+username try: val = self.conn.sudo(command,password=self.rootPass,hide=True).stdout.strip() return ('User Created: '+username,0) except Exception as e:",
"return ('User Privilege Granted',0) except Exception as e: return ('Cannot Grant user Privileges',1)",
"updatePriv(self,username): command = \"usermod -aG sudo \"+username try: val = self.conn.sudo(command,password=self.rootPass).stdout.strip() return ('User",
"\"usermod -aG sudo \"+username try: val = self.conn.sudo(command,password=self.rootPass).stdout.strip() return ('User Privilege Granted',0) except",
"'+username,0) except Exception as e: return ('Cannot delete user',1) def updatePriv(self,username): command =",
"class OperationsUtil(): def __init__(self): self.rootUser=\"ubuntu20\" self.rootPass=\"<PASSWORD>!\" self.conn=Connection(host='ubuntu20@10.109.34.222',connect_kwargs={\"password\": self.rootPass}) def createUser(self, username, password, dirname):",
"Grant user Privileges',1) op = OperationsUtil() # print(op.createUser(\"test\", \"test\")[0]) # print(op.viewUser()) # print(op.updatePriv(\"test\")[0])",
"Exception as e: return ('Cannot Grant user Privileges',1) op = OperationsUtil() # print(op.createUser(\"test\",",
"'{ print $1}' /etc/passwd\" return self.conn.run(command,hide=True).stdout.strip() def deluser(self,username): command = \"userdel -f \"+username",
"-m -d /home/\"+dirname+\"/ -g users -s /bin/bash \"+username try: val = self.conn.sudo(command,password=self.rootPass,hide=True).stdout.strip() return",
"e: return ('Cannot delete user',1) def updatePriv(self,username): command = \"usermod -aG sudo \"+username",
"self.conn=Connection(host='ubuntu20@10.109.34.222',connect_kwargs={\"password\": self.rootPass}) def createUser(self, username, password, dirname): if not dirname: dirname = username",
"dirname = username command = \"useradd -p \"+password+\" -m -d /home/\"+dirname+\"/ -g users",
"Privilege Granted',0) except Exception as e: return ('Cannot Grant user Privileges',1) op =",
"$1}' /etc/passwd\" return self.conn.run(command,hide=True).stdout.strip() def deluser(self,username): command = \"userdel -f \"+username try: val",
"createUser(self, username, password, dirname): if not dirname: dirname = username command = \"useradd",
"= self.conn.sudo(command,password=self.<PASSWORD>,hide=True).stdout.strip() return ('User Deleted: '+username,0) except Exception as e: return ('Cannot delete",
"def createUser(self, username, password, dirname): if not dirname: dirname = username command =",
"-s /bin/bash \"+username try: val = self.conn.sudo(command,password=self.rootPass,hide=True).stdout.strip() return ('User Created: '+username,0) except Exception",
"def __init__(self): self.rootUser=\"ubuntu20\" self.rootPass=\"<PASSWORD>!\" self.conn=Connection(host='ubuntu20@10.109.34.222',connect_kwargs={\"password\": self.rootPass}) def createUser(self, username, password, dirname): if not",
"val = self.conn.sudo(command,password=self.rootPass).stdout.strip() return ('User Privilege Granted',0) except Exception as e: return ('Cannot",
"def viewUser(self): command = \"awk -F: '{ print $1}' /etc/passwd\" return self.conn.run(command,hide=True).stdout.strip() def",
"\"userdel -f \"+username try: val = self.conn.sudo(command,password=self.<PASSWORD>,hide=True).stdout.strip() return ('User Deleted: '+username,0) except Exception",
"except Exception as e: return ('Cannot Grant user Privileges',1) op = OperationsUtil() #",
"('Cannot create user',1) def viewUser(self): command = \"awk -F: '{ print $1}' /etc/passwd\"",
"\"awk -F: '{ print $1}' /etc/passwd\" return self.conn.run(command,hide=True).stdout.strip() def deluser(self,username): command = \"userdel",
"/bin/bash \"+username try: val = self.conn.sudo(command,password=self.rootPass,hide=True).stdout.strip() return ('User Created: '+username,0) except Exception as"
] |
[
"of type {} as Currency (invalid type): {}\".format(type(value), value)) # operator overloading to",
"encoder): \"\"\" Encode this currency according to the Sia Binary Encoding format. \"\"\"",
"def sum(cls, *values): s = cls() for value in values: s.__iadd__(value) return s",
"cls() c.value = jsdec.Decimal(obj) if lowest_unit: c.value.__imul__(jsdec.Decimal('0.000000001')) return c @classmethod def from_json(_, obj):",
"value(self, value): # normalize the value if isinstance(value, BinaryData): value = value.value elif",
"encoder.add_slice(b) class Blockstake(BaseDataTypeClass): \"\"\" TFChain Blockstake Object. \"\"\" def __init__(self, value=None): self._value =",
"if not isinstance(other, Currency): return self.__lt__(Currency(other)) return self.value.__lt__(other.value) def __le__(self, other): if not",
"def value(self): return self._value @value.setter def value(self, value): value._value = Currency(value=value) # allow",
"return jsstr.repeat('0', Hash.SIZE*2) return s class Currency(BaseDataTypeClass): \"\"\" TFChain Currency Object. \"\"\" def",
"return self.__str__() def json(self): return self.__str__() def bytes(self): return self.value.bytes() def sia_binary_encode(self, encoder):",
"not it is fixed sized. \"\"\" if self._fixed_size == None: encoder.add_slice(self._value) else: encoder.add_array(self._value)",
"other = Currency(value=other) elif isinstance(other, float): other = Currency(value=jsdec.Decimal(str(other))) elif not isinstance(other, Currency):",
"Currency): return self.__ne__(Currency(other)) return self.value.__ne__(other.value) def __gt__(self, other): if not isinstance(other, Currency): return",
"and not isinstance(obj, str): raise TypeError( \"currency is expected to be a string",
"other): if not isinstance(other, Currency): return self.__sub__(Currency(other)) return Currency(self.value.__sub__(other.value)) def __rsub__(self, other): return",
"@property def value(self): return self._value @value.setter def value(self, value): # normalize the value",
"to the Rivine Binary Encoding format. Either encoded as a slice or an",
"be an encoded string when part of a JSON object\") if obj ==",
"def __str__(self): s = super().__str__() if jsstr.isempty(s): return jsstr.repeat('0', Hash.SIZE*2) return s class",
"__int__(self): return jsstr.to_int(self.str(lowest_unit=True)) def bytes(self): return self.value.bytes(prec=9) def __str__(self): return self.str() def str(self,",
"\"), '.') if jsstr.isempty(s): s = \"0\" if with_unit: s += \" TFT\"",
"def __mul__(self, other): if not isinstance(other, Currency): return self.__mul__(Currency(other)) return Currency(self.value.__mul__(other.value).to_nearest(9)) def __rmul__(self,",
"size, check this now lvalue = len(value) if self._fixed_size != None and lvalue",
"tferrors import tfchain.polyfill.encoding.base64 as jsbase64 import tfchain.polyfill.encoding.hex as jshex import tfchain.polyfill.encoding.str as jsstr",
"to be turned into an int def __int__(self): return jsstr.to_int(self.str(lowest_unit=True)) def bytes(self): return",
"return self.str() def str(self, with_unit=False, lowest_unit=False, precision=9): \"\"\" Turn this Currency value into",
"obj == '': obj = None return cls(value=obj) def __str__(self): s = super().__str__()",
"self._from_str = lambda s: jshex.bytes_from_hex( s[2:] if (s.startswith(\"0x\") or s.startswith(\"0X\")) else s) self._to_str",
"values for intermediate computations # raise tferrors.CurrencyNegativeValue(d.__str__()) self._value = d return raise TypeError(",
"self._value = Currency(value) @classmethod def from_json(cls, obj): if obj != None and not",
"\"\"), \"0\") elif jsstr.contains(s, \".\"): s = jsstr.rstrip(jsstr.rstrip(s, \"0 \"), '.') if jsstr.isempty(s):",
"__str__(self): return self.str() def str(self, with_unit=False, lowest_unit=False, precision=9): \"\"\" Turn this Currency value",
"object\") if obj == '': obj = None return cls(value=obj, fixed_size=fixed_size, strencoding=strencoding) @property",
"isinstance(other, Currency): return self.__eq__(Currency(other)) return self.value.__eq__(other.value) def __ne__(self, other): if not isinstance(other, Currency):",
"return self.value.__ne__(other.value) def __gt__(self, other): if not isinstance(other, Currency): return self.__gt__(Currency(other)) return self.value.__gt__(other.value)",
"__init__(self, value=None): self._value = Currency(value) @classmethod def from_json(cls, obj): if obj != None",
"as jsbase64 import tfchain.polyfill.encoding.hex as jshex import tfchain.polyfill.encoding.str as jsstr import tfchain.polyfill.encoding.decimal as",
"elif not isinstance(other, BinaryData): raise TypeError( \"Binary data of type {} is not",
"def __len__(self): return len(self.value) def __str__(self): return self._to_str(self._value) def str(self): return self.__str__() def",
"{}\".format(type(fixed_size))) if fixed_size < 0: raise TypeError( \"fixed size should be at least",
"is not supported\".format(type(other))) if self._fixed_size != other._fixed_size: raise TypeError( \"Cannot compare binary data",
"None return cls(value=obj) @property def value(self): return self._value @value.setter def value(self, value): value._value",
"obj == '': obj = None c = cls() c.value = jsdec.Decimal(obj) if",
"self.__iadd__(Currency(other)) self._value.__iadd__(other.value) return self # operator overloading to allow currencies to be multiplied",
"minus(self, other): return self.__sub__(other) def times(self, other): return self.__mul__(other) def divided_by(self, other): return",
"return self.__str__() def bytes(self): return self.value.bytes() def sia_binary_encode(self, encoder): \"\"\" Encode this block",
"None and not isinstance(strencoding, str): raise TypeError( \"strencoding should be None or a",
"# all good, assign the bytearray value self._value = value def __len__(self): return",
"is expected to be an encoded string when part of a JSON object,",
"fixed_size < 0: raise TypeError( \"fixed size should be at least 0, {}",
"sia_binary_encode(self, encoder): \"\"\" Encode this block stake (==Currency) according to the Sia Binary",
"def __hash__(self): return hash(self.__str__()) def sia_binary_encode(self, encoder): \"\"\" Encode this binary data according",
"return self.value != other.value def _op_other_as_binary_data(self, other): if isinstance(other, (str, bytes, bytearray)): other",
"other # allow our currency to be turned into an int def __int__(self):",
"rivine_binary_encode(self, encoder): \"\"\" Encode this block stake (==Currency) according to the Rivine Binary",
"other): return self.__mul__(other) def __imul__(self, other): if not isinstance(other, Currency): return self.__imul__(Currency(other)) self._value.__imul__(other.value)",
"self.__le__(Currency(other)) return self.value.__le__(other.value) def __eq__(self, other): if not isinstance(other, Currency): return self.__eq__(Currency(other)) return",
"0 # based on the binary length of the value self._fixed_size = len(self.value)",
"self.__truediv__(other) def equal_to(self, other): return self.__eq__(other) def not_equal_to(self, other): return self.__ne__(other) def less_than(self,",
"good, assign the bytearray value self._value = value def __len__(self): return len(self.value) def",
"allowed\".format(fixed_size)) if fixed_size != 0: self._fixed_size = fixed_size else: self._fixed_size = None #",
"isinstance(other, Currency): return self.__gt__(Currency(other)) return self.value.__gt__(other.value) def __ge__(self, other): if not isinstance(other, Currency):",
"isinstance(value, str): value = self._from_str(value) elif isinstance(value, bytearray): value = bytes(value) elif not",
"not isinstance(other, Currency): return self.__lt__(Currency(other)) return self.value.__lt__(other.value) def __le__(self, other): if not isinstance(other,",
"raise TypeError( \"{} is not a valid string encoding\".format(strencoding)) self._strencoding = strencoding #",
"import tfchain.polyfill.array as jsarray from tfchain.types.BaseDataType import BaseDataTypeClass class BinaryData(BaseDataTypeClass): \"\"\" BinaryData is",
"return self.value == other.value def __ne__(self, other): other = self._op_other_as_binary_data(other) return self.value !=",
"other): return self.__gt__(other) def less_than_or_equal_to(self, other): return self.__le__(other) def greater_than_or_equal_to(self, other): return self.__ge__(other)",
"precision=9): \"\"\" Turn this Currency value into a str TFT unit-based value, optionally",
"value self._fixed_size = len(self.value) @classmethod def from_json(cls, obj, fixed_size=None, strencoding=None): if obj !=",
"other): other = self._op_other_as_binary_data(other) return self.value != other.value def _op_other_as_binary_data(self, other): if isinstance(other,",
"isinstance(other, Currency): return self.__sub__(Currency(other)) return Currency(self.value.__sub__(other.value)) def __rsub__(self, other): return self.__sub__(other) def __isub__(self,",
"def json(self): return self.__str__() def __eq__(self, other): other = self._op_other_as_binary_data(other) return self.value ==",
"'': obj = None return cls(value=obj) @property def value(self): return self._value @value.setter def",
"isinstance(other, (str, bytes, bytearray)): other = BinaryData( value=other, fixed_size=self._fixed_size, strencoding=self._strencoding) elif not isinstance(other,",
"other): return self.__sub__(other) def times(self, other): return self.__mul__(other) def divided_by(self, other): return self.__truediv__(other)",
"isinstance(other, BinaryData): raise TypeError( \"Binary data of type {} is not supported\".format(type(other))) if",
"bytearray value self._value = value def __len__(self): return len(self.value) def __str__(self): return self._to_str(self._value)",
"str)): other = Currency(value=other) elif isinstance(other, float): other = Currency(value=jsdec.Decimal(str(other))) elif not isinstance(other,",
"operator overloading to allow currencies to be divided def __truediv__(self, other): if not",
"\"\"\" if self._fixed_size == None: encoder.add_slice(self._value) else: encoder.add_array(self._value) def rivine_binary_encode(self, encoder): \"\"\" Encode",
"__isub__(self, other): if not isinstance(other, Currency): return self.__isub__(Currency(other)) self._value.__isub__(other.value) return self # operator",
"def json(self): return self.str(lowest_unit=True) def sia_binary_encode(self, encoder): \"\"\" Encode this currency according to",
"encoder.add_array(b) def rivine_binary_encode(self, encoder): \"\"\" Encode this currency according to the Rivine Binary",
"!= None and lvalue != 0 and lvalue != self._fixed_size: raise ValueError( \"binary",
"with the currency notation. @param with_unit: include the TFT currency suffix unit with",
"value(self): return self._value def plus(self, other): return self.__add__(other) def minus(self, other): return self.__sub__(other)",
"other def __hash__(self): return hash(self.__str__()) def sia_binary_encode(self, encoder): \"\"\" Encode this binary data",
"= None return cls(value=obj, fixed_size=fixed_size, strencoding=strencoding) @property def value(self): return self._value @value.setter def",
"type): {}\".format(type(value), value)) # operator overloading to allow currencies to be summed def",
"self.bytes() encoder.add_int(len(b)) encoder.add_array(b) def rivine_binary_encode(self, encoder): \"\"\" Encode this currency according to the",
"return self.__le__(Currency(other)) return self.value.__le__(other.value) def __eq__(self, other): if not isinstance(other, Currency): return self.__eq__(Currency(other))",
"if isinstance(value, Currency): self._value = value.value return if isinstance(value, (int, str, jsdec.Decimal)): inner_value",
"if strencoding != None and not isinstance(strencoding, str): raise TypeError( \"strencoding should be",
"d.as_tuple() # sign is first return value if exp < -9: raise tferrors.CurrencyPrecisionOverflow(d.__str__())",
"__repr__(self): return self.__str__() def json(self): return self.__str__() def __eq__(self, other): other = self._op_other_as_binary_data(other)",
"self.__lt__(other) def greater_than(self, other): return self.__gt__(other) def less_than_or_equal_to(self, other): return self.__le__(other) def greater_than_or_equal_to(self,",
"type used for any binary data used in tfchain. \"\"\" def __init__(self, value=None,",
"Currency(value=jsdec.Decimal(str(other))) elif not isinstance(other, Currency): raise TypeError( \"currency of type {} is not",
"return self.__lt__(other) def greater_than(self, other): return self.__gt__(other) def less_than_or_equal_to(self, other): return self.__le__(other) def",
"from_json(cls, obj, fixed_size=None, strencoding=None): if obj != None and not isinstance(obj, str): raise",
"other): return self.__add__(other) def minus(self, other): return self.__sub__(other) def times(self, other): return self.__mul__(other)",
"JSON object, not type {}\".format(type(obj))) if obj == '': obj = None return",
"other): return self.__mul__(other) def divided_by(self, other): return self.__truediv__(other) def equal_to(self, other): return self.__eq__(other)",
"lambda value: '0x' + jshex.bytes_to_hex(value) else: raise TypeError( \"{} is not a valid",
"self.__eq__(other) def not_equal_to(self, other): return self.__ne__(other) def less_than(self, other): return self.__lt__(other) def greater_than(self,",
"BinaryData, str, bytes or bytearray, not {}\".format(type(value))) # if fixed size, check this",
"format. \"\"\" b = self.bytes() encoder.add_int(len(b)) encoder.add_array(b) def rivine_binary_encode(self, encoder): \"\"\" Encode this",
"cls() for value in values: s.__iadd__(value) return s @classmethod def from_str(cls, obj, lowest_unit=False):",
"if not isinstance(other, Currency): return self.__gt__(Currency(other)) return self.value.__gt__(other.value) def __ge__(self, other): if not",
"self._value.__imul__(other.value) return self # operator overloading to allow currencies to be divided def",
"def value(self): return self._value def plus(self, other): return self.__add__(other) def minus(self, other): return",
"return self.__eq__(Currency(other)) return self.value.__eq__(other.value) def __ne__(self, other): if not isinstance(other, Currency): return self.__ne__(Currency(other))",
"return hash(self.__str__()) def sia_binary_encode(self, encoder): \"\"\" Encode this binary data according to the",
"overloading to allow currencies to be multiplied def __mul__(self, other): if not isinstance(other,",
"fixed sized. \"\"\" if self._fixed_size == None: encoder.add_slice(self._value) else: encoder.add_array(self._value) def rivine_binary_encode(self, encoder):",
"self.value == other.value def __ne__(self, other): other = self._op_other_as_binary_data(other) return self.value != other.value",
"be a string , not type {}\".format(type(obj))) if obj == '': obj =",
"def __eq__(self, other): other = self._op_other_as_binary_data(other) return self.value == other.value def __ne__(self, other):",
"jsbase64.bytes_from_b64(s) self._to_str = lambda value: jsbase64.bytes_to_b64(value) elif jsstr.String(strencoding).lower().strip().__eq__('hexprefix'): self._from_str = lambda s: jshex.bytes_from_hex(",
"return if isinstance(value, Currency): self._value = value.value return if isinstance(value, (int, str, jsdec.Decimal)):",
"if not isinstance(other, Currency): return self.__mul__(Currency(other)) return Currency(self.value.__mul__(other.value).to_nearest(9)) def __rmul__(self, other): return self.__mul__(other)",
"else: self._fixed_size = None # for now use no fixed size # define",
"the bytearray value self._value = value def __len__(self): return len(self.value) def __str__(self): return",
"strencoding=self._strencoding) elif not isinstance(other, BinaryData): raise TypeError( \"Binary data of type {} is",
"def str(self): return self.__str__() def __repr__(self): return self.__str__() def json(self): return self.__str__() def",
"be subtracted def __sub__(self, other): if not isinstance(other, Currency): return self.__sub__(Currency(other)) return Currency(self.value.__sub__(other.value))",
"self._to_str = lambda value: '0x' + jshex.bytes_to_hex(value) else: raise TypeError( \"{} is not",
"\"Binary data of type {} is not supported\".format(type(other))) if self._fixed_size != other._fixed_size: raise",
"bytes or bytearray, not {}\".format(type(value))) # if fixed size, check this now lvalue",
"jshex.bytes_to_hex(value) else: raise TypeError( \"{} is not a valid string encoding\".format(strencoding)) self._strencoding =",
"Currency Object. \"\"\" def __init__(self, value=None): self._value = None self.value = value @classmethod",
"isinstance(other, Currency): return self.__le__(Currency(other)) return self.value.__le__(other.value) def __eq__(self, other): if not isinstance(other, Currency):",
"Encoding format. Either encoded as a slice or an array, depending on whether",
"= value if isinstance(inner_value, str): inner_value = jsstr.String(inner_value).upper().strip().value if len(inner_value) >= 4 and",
"operator overloading to allow currencies to be subtracted def __sub__(self, other): if not",
"not_equal_to(self, other): return self.__ne__(other) def less_than(self, other): return self.__lt__(other) def greater_than(self, other): return",
"None: self._value = jsdec.Decimal() return if isinstance(value, Currency): self._value = value.value return if",
"first return value if exp < -9: raise tferrors.CurrencyPrecisionOverflow(d.__str__()) # if sign !=",
"other.value def __ne__(self, other): other = self._op_other_as_binary_data(other) return self.value != other.value def _op_other_as_binary_data(self,",
"from_json(_, obj): return Currency.from_str(obj, lowest_unit=True) @property def value(self): return self._value def plus(self, other):",
"None # for now use no fixed size # define the value (finally)",
"jsstr.String(inner_value).upper().strip().value if len(inner_value) >= 4 and inner_value[-3:] == 'TFT': inner_value = jsstr.rstrip(inner_value[:-3]) d",
"self._value @value.setter def value(self, value): value._value = Currency(value=value) # allow our block stake",
"# define string encoding if strencoding != None and not isinstance(strencoding, str): raise",
"return self.__iadd__(Currency(other)) self._value.__iadd__(other.value) return self # operator overloading to allow currencies to be",
"values: s.__iadd__(value) return s @classmethod def from_str(cls, obj, lowest_unit=False): if obj != None",
"sign is first return value if exp < -9: raise tferrors.CurrencyPrecisionOverflow(d.__str__()) # if",
"def value(self, value): value._value = Currency(value=value) # allow our block stake to be",
"value=other, fixed_size=self._fixed_size, strencoding=self._strencoding) elif not isinstance(other, BinaryData): raise TypeError( \"Binary data of type",
"tferrors.CurrencyNegativeValue(d.__str__()) self._value = d return raise TypeError( \"cannot set value of type {}",
"self._fixed_size = None # for now use no fixed size # define the",
"self.bytes() encoder.add_slice(b) class Blockstake(BaseDataTypeClass): \"\"\" TFChain Blockstake Object. \"\"\" def __init__(self, value=None): self._value",
"JSON object\") if obj == '': obj = None return cls(value=obj, fixed_size=fixed_size, strencoding=strencoding)",
"str, bytes or bytearray, not {}\".format(type(value))) # if fixed size, check this now",
"TypeError( \"currency is expected to be a string , not type {}\".format(type(obj))) if",
"@property def value(self): return self._value @value.setter def value(self, value): value._value = Currency(value=value) #",
"other): if not isinstance(other, Currency): return self.__eq__(Currency(other)) return self.value.__eq__(other.value) def __ne__(self, other): if",
"self.__str__() def __repr__(self): return self.__str__() def json(self): return self.__str__() def __eq__(self, other): other",
"# define the value (finally) self._value = None self.value = value if fixed_size",
"tfchain. \"\"\" def __init__(self, value=None, fixed_size=None, strencoding=None): # define string encoding if strencoding",
"isinstance(other, Currency): raise TypeError( \"currency of type {} is not supported\".format(type(other))) return other",
"the fixed size now, if the fixed_size was 0 # based on the",
"= jsdec.Decimal(obj) if lowest_unit: c.value.__imul__(jsdec.Decimal('0.000000001')) return c @classmethod def from_json(_, obj): return Currency.from_str(obj,",
"self._value = d return raise TypeError( \"cannot set value of type {} as",
"divided_by(self, other): return self.__truediv__(other) def equal_to(self, other): return self.__eq__(other) def not_equal_to(self, other): return",
"to the Sia Binary Encoding format. Either encoded as a slice or an",
"Currency): return self.__gt__(Currency(other)) return self.value.__gt__(other.value) def __ge__(self, other): if not isinstance(other, Currency): return",
"def __int__(self): return jsstr.to_int(self.value.str(lowest_unit=False)) def str(self): return jsstr.from_int(self.__int__()) def __str__(self): return self.str() def",
"s def __repr__(self): return self.str(with_unit=True) def json(self): return self.str(lowest_unit=True) def sia_binary_encode(self, encoder): \"\"\"",
"TypeError( \"block stake is expected to be a string when part of a",
"or s.startswith(\"0X\")) else s) self._to_str = lambda value: '0x' + jshex.bytes_to_hex(value) else: raise",
"__ne__(self, other): other = self._op_other_as_binary_data(other) return self.value != other.value def _op_other_as_binary_data(self, other): if",
"data with different strencoding: self({}) != other({})\".format( self._strencoding, other._strencoding)) return other def __hash__(self):",
"type {} is not supported\".format(type(other))) return other # allow our currency to be",
"= Currency(value) @classmethod def from_json(cls, obj): if obj != None and not isinstance(obj,",
"return cls(value=obj) def __str__(self): s = super().__str__() if jsstr.isempty(s): return jsstr.repeat('0', Hash.SIZE*2) return",
"json(self): return self.str(lowest_unit=True) def sia_binary_encode(self, encoder): \"\"\" Encode this currency according to the",
"of fixed size {}, length {} is not allowed\".format( self._fixed_size, len(value))) # all",
"string , not type {}\".format(type(obj))) if obj == '': obj = None c",
"= jsstr.lstrip(jsstr.replace(s, \".\", \"\"), \"0\") elif jsstr.contains(s, \".\"): s = jsstr.rstrip(jsstr.rstrip(s, \"0 \"),",
"\"\"\" TFChain Hash Object, a special type of BinaryData \"\"\" def __init__(self, value=None):",
"turned into an int def __int__(self): return jsstr.to_int(self.value.str(lowest_unit=False)) def str(self): return jsstr.from_int(self.__int__()) def",
"our block stake to be turned into an int def __int__(self): return jsstr.to_int(self.value.str(lowest_unit=False))",
"@classmethod def from_str(cls, obj, lowest_unit=False): if obj != None and not isinstance(obj, str):",
"the Sia Binary Encoding format. \"\"\" b = self.bytes() encoder.add_int(len(b)) encoder.add_array(b) def rivine_binary_encode(self,",
"def __str__(self): return self.str() def str(self, with_unit=False, lowest_unit=False, precision=9): \"\"\" Turn this Currency",
"string encoding\".format(strencoding)) self._strencoding = strencoding # define fixed size if fixed_size != None:",
"None or jsstr.String(strencoding).lower().strip().__eq__('hex'): self._from_str = lambda s: jshex.bytes_from_hex(s) self._to_str = lambda value: jshex.bytes_to_hex(value)",
"def __ne__(self, other): other = self._op_other_as_binary_data(other) return self.value != other.value def _op_other_as_binary_data(self, other):",
"obj): return Currency.from_str(obj, lowest_unit=True) @property def value(self): return self._value def plus(self, other): return",
"raise TypeError( \"cannot set value of type {} as Currency (invalid type): {}\".format(type(value),",
"and not isinstance(obj, str): raise TypeError( \"binary data is expected to be an",
"self._to_str = lambda value: jsbase64.bytes_to_b64(value) elif jsstr.String(strencoding).lower().strip().__eq__('hexprefix'): self._from_str = lambda s: jshex.bytes_from_hex( s[2:]",
"def rivine_binary_encode(self, encoder): \"\"\" Encode this currency according to the Rivine Binary Encoding",
"__init__(self, value=None): super().__init__(value, fixed_size=Hash.SIZE, strencoding='hex') @classmethod def from_json(cls, obj): if obj != None",
"self._value = None self.value = value if fixed_size == 0: # define the",
"encoding\".format(strencoding)) self._strencoding = strencoding # define fixed size if fixed_size != None: if",
"!= self._fixed_size: raise ValueError( \"binary data was expected to be of fixed size",
"else: raise TypeError( \"{} is not a valid string encoding\".format(strencoding)) self._strencoding = strencoding",
"raise TypeError( \"fixed size should be None or int, not be of type",
"Currency): return self.__truediv__(Currency(other)) return Currency(self.value.__truediv__(other.value).to_nearest(9)) # operator overloading to allow currencies to be",
"!= other._strencoding: raise TypeError( \"Cannot compare binary data with different strencoding: self({}) !=",
"self.value != other.value def _op_other_as_binary_data(self, other): if isinstance(other, (str, bytes, bytearray)): other =",
"\"\"\" Encode this binary data according to the Rivine Binary Encoding format. Either",
"d return raise TypeError( \"cannot set value of type {} as Currency (invalid",
"value): # normalize the value if isinstance(value, BinaryData): value = value.value elif value",
"if not isinstance(other, Currency): return self.__truediv__(Currency(other)) return Currency(self.value.__truediv__(other.value).to_nearest(9)) # operator overloading to allow",
"string when part of a JSON object, not type {}\".format(type(obj))) if obj ==",
"fixed_size=Hash.SIZE, strencoding='hex') @classmethod def from_json(cls, obj): if obj != None and not isinstance(obj,",
"raise ValueError( \"binary data was expected to be of fixed size {}, length",
"= self._op_other_as_binary_data(other) return self.value == other.value def __ne__(self, other): other = self._op_other_as_binary_data(other) return",
"strencoding=None): # define string encoding if strencoding != None and not isinstance(strencoding, str):",
"raise tferrors.CurrencyNegativeValue(d.__str__()) self._value = d return raise TypeError( \"cannot set value of type",
"return self.str(with_unit=True) def json(self): return self.str(lowest_unit=True) def sia_binary_encode(self, encoder): \"\"\" Encode this currency",
"lowest_unit=False, precision=9): \"\"\" Turn this Currency value into a str TFT unit-based value,",
"less_than_or_equal_to(self, other): return self.__le__(other) def greater_than_or_equal_to(self, other): return self.__ge__(other) def negate(self): return Currency(self.value.negate())",
"type {}\".format(type(fixed_size))) if fixed_size < 0: raise TypeError( \"fixed size should be at",
"<reponame>GlenDC/threefold-wallet-electron import tfchain.errors as tferrors import tfchain.polyfill.encoding.base64 as jsbase64 import tfchain.polyfill.encoding.hex as jshex",
"size: self({}) != other({})\".format( self._fixed_size, other._fixed_size)) if self._strencoding != other._strencoding: raise TypeError( \"Cannot",
"this binary data according to the Rivine Binary Encoding format. Either encoded as",
"value if isinstance(value, BinaryData): value = value.value elif value == None: if self._fixed_size",
"self._fixed_size, len(value))) # all good, assign the bytearray value self._value = value def",
"self.__add__(other) def __iadd__(self, other): if not isinstance(other, Currency): return self.__iadd__(Currency(other)) self._value.__iadd__(other.value) return self",
"import tfchain.polyfill.encoding.str as jsstr import tfchain.polyfill.encoding.decimal as jsdec import tfchain.polyfill.array as jsarray from",
"\"\"\" b = self.bytes() encoder.add_int(len(b)) encoder.add_array(b) def rivine_binary_encode(self, encoder): \"\"\" Encode this currency",
"if not isinstance(other, Currency): return self.__isub__(Currency(other)) self._value.__isub__(other.value) return self # operator overloading to",
"from_str(cls, obj, lowest_unit=False): if obj != None and not isinstance(obj, str): raise TypeError(",
"exp < -9: raise tferrors.CurrencyPrecisionOverflow(d.__str__()) # if sign != 0: # allow negative",
"value: jshex.bytes_to_hex(value) elif jsstr.String(strencoding).lower().strip().__eq__('base64'): self._from_str = lambda s: jsbase64.bytes_from_b64(s) self._to_str = lambda value:",
"c = cls() c.value = jsdec.Decimal(obj) if lowest_unit: c.value.__imul__(jsdec.Decimal('0.000000001')) return c @classmethod def",
"Currency(self.value.__mul__(other.value).to_nearest(9)) def __rmul__(self, other): return self.__mul__(other) def __imul__(self, other): if not isinstance(other, Currency):",
"return self._value @value.setter def value(self, value): # normalize the value if isinstance(value, BinaryData):",
"-9: raise tferrors.CurrencyPrecisionOverflow(d.__str__()) # if sign != 0: # allow negative values for",
"self.__lt__(Currency(other)) return self.value.__lt__(other.value) def __le__(self, other): if not isinstance(other, Currency): return self.__le__(Currency(other)) return",
"other): return self.__eq__(other) def not_equal_to(self, other): return self.__ne__(other) def less_than(self, other): return self.__lt__(other)",
"other): return self.__le__(other) def greater_than_or_equal_to(self, other): return self.__ge__(other) def negate(self): return Currency(self.value.negate()) @value.setter",
"__mul__(self, other): if not isinstance(other, Currency): return self.__mul__(Currency(other)) return Currency(self.value.__mul__(other.value).to_nearest(9)) def __rmul__(self, other):",
"jsstr.to_int(self.str(lowest_unit=True)) def bytes(self): return self.value.bytes(prec=9) def __str__(self): return self.str() def str(self, with_unit=False, lowest_unit=False,",
"def from_str(cls, obj, lowest_unit=False): if obj != None and not isinstance(obj, str): raise",
"not be of type {}\".format(strencoding)) if strencoding == None or jsstr.String(strencoding).lower().strip().__eq__('hex'): self._from_str =",
"= None return cls(value=obj) def __str__(self): s = super().__str__() if jsstr.isempty(s): return jsstr.repeat('0',",
"__gt__(self, other): if not isinstance(other, Currency): return self.__gt__(Currency(other)) return self.value.__gt__(other.value) def __ge__(self, other):",
"now, if the fixed_size was 0 # based on the binary length of",
"str, jsdec.Decimal)): inner_value = value if isinstance(inner_value, str): inner_value = jsstr.String(inner_value).upper().strip().value if len(inner_value)",
"was 0 # based on the binary length of the value self._fixed_size =",
"encoder.add_int(len(b)) encoder.add_array(b) def rivine_binary_encode(self, encoder): \"\"\" Encode this block stake (==Currency) according to",
"bytes(value) elif not isinstance(value, bytes) and not jsarray.is_uint8_array(value): raise TypeError( \"binary data can",
"# allow negative values for intermediate computations # raise tferrors.CurrencyNegativeValue(d.__str__()) self._value = d",
"less_than(self, other): return self.__lt__(other) def greater_than(self, other): return self.__gt__(other) def less_than_or_equal_to(self, other): return",
"self.__truediv__(Currency(other)) return Currency(self.value.__truediv__(other.value).to_nearest(9)) # operator overloading to allow currencies to be subtracted def",
"negate(self): return Currency(self.value.negate()) @value.setter def value(self, value): if value == None: self._value =",
"isinstance(other, Currency): return self.__imul__(Currency(other)) self._value.__imul__(other.value) return self # operator overloading to allow currencies",
"lambda s: jshex.bytes_from_hex( s[2:] if (s.startswith(\"0x\") or s.startswith(\"0X\")) else s) self._to_str = lambda",
"other = self._op_other_as_binary_data(other) return self.value == other.value def __ne__(self, other): other = self._op_other_as_binary_data(other)",
"sia_binary_encode(self, encoder): \"\"\" Encode this currency according to the Sia Binary Encoding format.",
"allow negative values for intermediate computations # raise tferrors.CurrencyNegativeValue(d.__str__()) self._value = d return",
"allow our block stake to be turned into an int def __int__(self): return",
"not jsarray.is_uint8_array(value): raise TypeError( \"binary data can only be set to a BinaryData,",
"overloading to allow currencies to be subtracted def __sub__(self, other): if not isinstance(other,",
"not type {}\".format(type(obj))) if obj == '': obj = None return cls(value=obj) @property",
"@classmethod def from_json(_, obj): return Currency.from_str(obj, lowest_unit=True) @property def value(self): return self._value def",
"value = bytes(jsarray.new_array(0)) elif isinstance(value, str): value = self._from_str(value) elif isinstance(value, bytearray): value",
"return self.__ge__(Currency(other)) return self.value.__ge__(other.value) @staticmethod def _op_other_as_currency(other): if isinstance(other, (int, str)): other =",
"bytes(jsarray.new_array(self._fixed_size)) else: value = bytes(jsarray.new_array(0)) elif isinstance(value, str): value = self._from_str(value) elif isinstance(value,",
"other._strencoding: raise TypeError( \"Cannot compare binary data with different strencoding: self({}) != other({})\".format(",
"self._value = None self.value = value @classmethod def sum(cls, *values): s = cls()",
"be compared def __lt__(self, other): if not isinstance(other, Currency): return self.__lt__(Currency(other)) return self.value.__lt__(other.value)",
"define string encoding if strencoding != None and not isinstance(strencoding, str): raise TypeError(",
"times(self, other): return self.__mul__(other) def divided_by(self, other): return self.__truediv__(other) def equal_to(self, other): return",
"= fixed_size else: self._fixed_size = None # for now use no fixed size",
"\"\"\" def __init__(self, value=None, fixed_size=None, strencoding=None): # define string encoding if strencoding !=",
"should be None or int, not be of type {}\".format(type(fixed_size))) if fixed_size <",
"Hash Object, a special type of BinaryData \"\"\" def __init__(self, value=None): super().__init__(value, fixed_size=Hash.SIZE,",
"define the value (finally) self._value = None self.value = value if fixed_size ==",
"len(inner_value) >= 4 and inner_value[-3:] == 'TFT': inner_value = jsstr.rstrip(inner_value[:-3]) d = jsdec.Decimal(inner_value)",
"bytes(self): return self.value.bytes(prec=9) def __str__(self): return self.str() def str(self, with_unit=False, lowest_unit=False, precision=9): \"\"\"",
"= lambda value: jsbase64.bytes_to_b64(value) elif jsstr.String(strencoding).lower().strip().__eq__('hexprefix'): self._from_str = lambda s: jshex.bytes_from_hex( s[2:] if",
"not isinstance(obj, str): raise TypeError( \"block stake is expected to be a string",
"self._value = value.value return if isinstance(value, (int, str, jsdec.Decimal)): inner_value = value if",
"Currency value into a str TFT unit-based value, optionally with the currency notation.",
"if obj == '': obj = None c = cls() c.value = jsdec.Decimal(obj)",
"(==Currency) according to the Sia Binary Encoding format. \"\"\" b = self.bytes() encoder.add_int(len(b))",
"overloading to allow currencies to be summed def __add__(self, other): if not isinstance(other,",
"return self.__ge__(other) def negate(self): return Currency(self.value.negate()) @value.setter def value(self, value): if value ==",
"fixed_size=fixed_size, strencoding=strencoding) @property def value(self): return self._value @value.setter def value(self, value): # normalize",
"block stake (==Currency) according to the Sia Binary Encoding format. \"\"\" b =",
"= Currency(value=jsdec.Decimal(str(other))) elif not isinstance(other, Currency): raise TypeError( \"currency of type {} is",
"self._strencoding = strencoding # define fixed size if fixed_size != None: if not",
"raise TypeError( \"currency of type {} is not supported\".format(type(other))) return other # allow",
"__init__(self, value=None): self._value = None self.value = value @classmethod def sum(cls, *values): s",
"self.value.__ge__(other.value) @staticmethod def _op_other_as_currency(other): if isinstance(other, (int, str)): other = Currency(value=other) elif isinstance(other,",
"if jsstr.isempty(s): return jsstr.repeat('0', Hash.SIZE*2) return s class Currency(BaseDataTypeClass): \"\"\" TFChain Currency Object.",
"self({}) != other({})\".format( self._strencoding, other._strencoding)) return other def __hash__(self): return hash(self.__str__()) def sia_binary_encode(self,",
"expected to be an encoded string when part of a JSON object, not",
"Currency): return self.__sub__(Currency(other)) return Currency(self.value.__sub__(other.value)) def __rsub__(self, other): return self.__sub__(other) def __isub__(self, other):",
"fixed_size was 0 # based on the binary length of the value self._fixed_size",
"part of a JSON object, not type {}\".format(type(obj))) if obj == '': obj",
"Currency(self.value.negate()) @value.setter def value(self, value): if value == None: self._value = jsdec.Decimal() return",
"'0x' + jshex.bytes_to_hex(value) else: raise TypeError( \"{} is not a valid string encoding\".format(strencoding))",
"all good, assign the bytearray value self._value = value def __len__(self): return len(self.value)",
"computations # raise tferrors.CurrencyNegativeValue(d.__str__()) self._value = d return raise TypeError( \"cannot set value",
"and inner_value[-3:] == 'TFT': inner_value = jsstr.rstrip(inner_value[:-3]) d = jsdec.Decimal(inner_value) _, _, exp",
"tferrors.CurrencyPrecisionOverflow(d.__str__()) # if sign != 0: # allow negative values for intermediate computations",
"def __repr__(self): return self.__str__() def json(self): return self.__str__() def __eq__(self, other): other =",
"allow currencies to be compared def __lt__(self, other): if not isinstance(other, Currency): return",
"return self.__mul__(Currency(other)) return Currency(self.value.__mul__(other.value).to_nearest(9)) def __rmul__(self, other): return self.__mul__(other) def __imul__(self, other): if",
"other): if not isinstance(other, Currency): return self.__truediv__(Currency(other)) return Currency(self.value.__truediv__(other.value).to_nearest(9)) # operator overloading to",
"if (s.startswith(\"0x\") or s.startswith(\"0X\")) else s) self._to_str = lambda value: '0x' + jshex.bytes_to_hex(value)",
"not isinstance(other, Currency): return self.__mul__(Currency(other)) return Currency(self.value.__mul__(other.value).to_nearest(9)) def __rmul__(self, other): return self.__mul__(other) def",
"Currency): return self.__isub__(Currency(other)) self._value.__isub__(other.value) return self # operator overloading to allow currencies to",
"jsstr.lstrip(jsstr.replace(s, \".\", \"\"), \"0\") elif jsstr.contains(s, \".\"): s = jsstr.rstrip(jsstr.rstrip(s, \"0 \"), '.')",
"overloading to allow currencies to be divided def __truediv__(self, other): if not isinstance(other,",
"len(value))) # all good, assign the bytearray value self._value = value def __len__(self):",
"as a slice or an array, depending on whether or not it is",
"this block stake (==Currency) according to the Rivine Binary Encoding format. \"\"\" b",
"@param with_unit: include the TFT currency suffix unit with the str \"\"\" s",
"currencies to be summed def __add__(self, other): if not isinstance(other, Currency): return self.__add__(Currency(other))",
"if not isinstance(other, Currency): return self.__eq__(Currency(other)) return self.value.__eq__(other.value) def __ne__(self, other): if not",
"bytearray, not {}\".format(type(value))) # if fixed size, check this now lvalue = len(value)",
"rivine_binary_encode(self, encoder): \"\"\" Encode this binary data according to the Rivine Binary Encoding",
"be set to a BinaryData, str, bytes or bytearray, not {}\".format(type(value))) # if",
"unit-based value, optionally with the currency notation. @param with_unit: include the TFT currency",
"binary data with different strencoding: self({}) != other({})\".format( self._strencoding, other._strencoding)) return other def",
"no fixed size # define the value (finally) self._value = None self.value =",
"other): return self.__ne__(other) def less_than(self, other): return self.__lt__(other) def greater_than(self, other): return self.__gt__(other)",
"\"currency of type {} is not supported\".format(type(other))) return other # allow our currency",
"stake is expected to be a string when part of a JSON object,",
"(str, bytes, bytearray)): other = BinaryData( value=other, fixed_size=self._fixed_size, strencoding=self._strencoding) elif not isinstance(other, BinaryData):",
"== None: encoder.add_slice(self._value) else: encoder.add_array(self._value) class Hash(BinaryData): SIZE = 32 \"\"\" TFChain Hash",
"def from_json(cls, obj, fixed_size=None, strencoding=None): if obj != None and not isinstance(obj, str):",
"def __add__(self, other): if not isinstance(other, Currency): return self.__add__(Currency(other)) return Currency(self.value.__add__(other.value)) def __radd__(self,",
"binary data according to the Rivine Binary Encoding format. Either encoded as a",
"expected to be a string , not type {}\".format(type(obj))) if obj == '':",
"return self.value.__eq__(other.value) def __ne__(self, other): if not isinstance(other, Currency): return self.__ne__(Currency(other)) return self.value.__ne__(other.value)",
"jsarray.is_uint8_array(value): raise TypeError( \"binary data can only be set to a BinaryData, str,",
"TFT unit-based value, optionally with the currency notation. @param with_unit: include the TFT",
"and not isinstance(obj, str): raise TypeError( \"block stake is expected to be a",
"JSON object, not {}\".format(type(obj))) if obj == '': obj = None return cls(value=obj)",
"value=None): self._value = Currency(value) @classmethod def from_json(cls, obj): if obj != None and",
"str): value = self._from_str(value) elif isinstance(value, bytearray): value = bytes(value) elif not isinstance(value,",
"tfchain.polyfill.encoding.str as jsstr import tfchain.polyfill.encoding.decimal as jsdec import tfchain.polyfill.array as jsarray from tfchain.types.BaseDataType",
"be an encoded string when part of a JSON object, not {}\".format(type(obj))) if",
"\"\"\" b = self.bytes() encoder.add_slice(b) class Blockstake(BaseDataTypeClass): \"\"\" TFChain Blockstake Object. \"\"\" def",
"str): raise TypeError( \"block stake is expected to be a string when part",
"our currency to be turned into an int def __int__(self): return jsstr.to_int(self.str(lowest_unit=True)) def",
"b = self.bytes() encoder.add_slice(b) class Blockstake(BaseDataTypeClass): \"\"\" TFChain Blockstake Object. \"\"\" def __init__(self,",
"if the fixed_size was 0 # based on the binary length of the",
"def __le__(self, other): if not isinstance(other, Currency): return self.__le__(Currency(other)) return self.value.__le__(other.value) def __eq__(self,",
"\"binary data is expected to be an encoded string when part of a",
"the Sia Binary Encoding format. Either encoded as a slice or an array,",
"float): other = Currency(value=jsdec.Decimal(str(other))) elif not isinstance(other, Currency): raise TypeError( \"currency of type",
"fixed size now, if the fixed_size was 0 # based on the binary",
"= None # for now use no fixed size # define the value",
"not type {}\".format(type(obj))) if obj == '': obj = None c = cls()",
"\"cannot set value of type {} as Currency (invalid type): {}\".format(type(value), value)) #",
"TFChain Blockstake Object. \"\"\" def __init__(self, value=None): self._value = Currency(value) @classmethod def from_json(cls,",
"TypeError( \"Cannot compare binary data with different fixed size: self({}) != other({})\".format( self._fixed_size,",
"isinstance(other, Currency): return self.__add__(Currency(other)) return Currency(self.value.__add__(other.value)) def __radd__(self, other): return self.__add__(other) def __iadd__(self,",
"not isinstance(strencoding, str): raise TypeError( \"strencoding should be None or a str, not",
"jshex.bytes_from_hex(s) self._to_str = lambda value: jshex.bytes_to_hex(value) elif jsstr.String(strencoding).lower().strip().__eq__('base64'): self._from_str = lambda s: jsbase64.bytes_from_b64(s)",
"None: encoder.add_slice(self._value) else: encoder.add_array(self._value) class Hash(BinaryData): SIZE = 32 \"\"\" TFChain Hash Object,",
"to the Sia Binary Encoding format. \"\"\" b = self.bytes() encoder.add_int(len(b)) encoder.add_array(b) def",
"s: jshex.bytes_from_hex( s[2:] if (s.startswith(\"0x\") or s.startswith(\"0X\")) else s) self._to_str = lambda value:",
"according to the Sia Binary Encoding format. \"\"\" b = self.bytes() encoder.add_int(len(b)) encoder.add_array(b)",
"return cls(value=obj, fixed_size=fixed_size, strencoding=strencoding) @property def value(self): return self._value @value.setter def value(self, value):",
"isinstance(other, Currency): return self.__iadd__(Currency(other)) self._value.__iadd__(other.value) return self # operator overloading to allow currencies",
"was expected to be of fixed size {}, length {} is not allowed\".format(",
"object, not type {}\".format(type(obj))) if obj == '': obj = None return cls(value=obj)",
"encoder): \"\"\" Encode this block stake (==Currency) according to the Rivine Binary Encoding",
"with_unit=False, lowest_unit=False, precision=9): \"\"\" Turn this Currency value into a str TFT unit-based",
"else: encoder.add_array(self._value) class Hash(BinaryData): SIZE = 32 \"\"\" TFChain Hash Object, a special",
"int): raise TypeError( \"fixed size should be None or int, not be of",
"when part of a JSON object\") if obj == '': obj = None",
"\"binary data was expected to be of fixed size {}, length {} is",
"be summed def __add__(self, other): if not isinstance(other, Currency): return self.__add__(Currency(other)) return Currency(self.value.__add__(other.value))",
"subtracted def __sub__(self, other): if not isinstance(other, Currency): return self.__sub__(Currency(other)) return Currency(self.value.__sub__(other.value)) def",
"sia_binary_encode(self, encoder): \"\"\" Encode this binary data according to the Sia Binary Encoding",
"tfchain.polyfill.encoding.base64 as jsbase64 import tfchain.polyfill.encoding.hex as jshex import tfchain.polyfill.encoding.str as jsstr import tfchain.polyfill.encoding.decimal",
"Currency): return self.__add__(Currency(other)) return Currency(self.value.__add__(other.value)) def __radd__(self, other): return self.__add__(other) def __iadd__(self, other):",
"value): value._value = Currency(value=value) # allow our block stake to be turned into",
"as Currency (invalid type): {}\".format(type(value), value)) # operator overloading to allow currencies to",
"only be set to a BinaryData, str, bytes or bytearray, not {}\".format(type(value))) #",
"self.__str__() def json(self): return self.__str__() def __eq__(self, other): other = self._op_other_as_binary_data(other) return self.value",
"format. \"\"\" b = self.bytes() encoder.add_slice(b) class Blockstake(BaseDataTypeClass): \"\"\" TFChain Blockstake Object. \"\"\"",
"self # operator overloading to allow currencies to be compared def __lt__(self, other):",
"isinstance(other, Currency): return self.__truediv__(Currency(other)) return Currency(self.value.__truediv__(other.value).to_nearest(9)) # operator overloading to allow currencies to",
"= self._op_other_as_binary_data(other) return self.value != other.value def _op_other_as_binary_data(self, other): if isinstance(other, (str, bytes,",
"to be multiplied def __mul__(self, other): if not isinstance(other, Currency): return self.__mul__(Currency(other)) return",
"a JSON object, not type {}\".format(type(obj))) if obj == '': obj = None",
"obj != None and not isinstance(obj, str): raise TypeError( \"currency is expected to",
"if not isinstance(other, Currency): return self.__iadd__(Currency(other)) self._value.__iadd__(other.value) return self # operator overloading to",
"= value def __len__(self): return len(self.value) def __str__(self): return self._to_str(self._value) def str(self): return",
"c.value.__imul__(jsdec.Decimal('0.000000001')) return c @classmethod def from_json(_, obj): return Currency.from_str(obj, lowest_unit=True) @property def value(self):",
"'': obj = None return cls(value=obj, fixed_size=fixed_size, strencoding=strencoding) @property def value(self): return self._value",
"other): return self.__lt__(other) def greater_than(self, other): return self.__gt__(other) def less_than_or_equal_to(self, other): return self.__le__(other)",
"Encode this block stake (==Currency) according to the Rivine Binary Encoding format. \"\"\"",
"super().__str__() if jsstr.isempty(s): return jsstr.repeat('0', Hash.SIZE*2) return s class Currency(BaseDataTypeClass): \"\"\" TFChain Currency",
"an array, depending on whether or not it is fixed sized. \"\"\" if",
"== None: self._value = jsdec.Decimal() return if isinstance(value, Currency): self._value = value.value return",
"string when part of a JSON object\") if obj == '': obj =",
"this currency according to the Rivine Binary Encoding format. \"\"\" b = self.bytes()",
"return self.__add__(Currency(other)) return Currency(self.value.__add__(other.value)) def __radd__(self, other): return self.__add__(other) def __iadd__(self, other): if",
"def __init__(self, value=None): self._value = Currency(value) @classmethod def from_json(cls, obj): if obj !=",
"value def __len__(self): return len(self.value) def __str__(self): return self._to_str(self._value) def str(self): return self.__str__()",
"__str__(self): return self.str() def __repr__(self): return self.__str__() def json(self): return self.__str__() def bytes(self):",
"isinstance(obj, str): raise TypeError( \"binary data is expected to be an encoded string",
"else s) self._to_str = lambda value: '0x' + jshex.bytes_to_hex(value) else: raise TypeError( \"{}",
"= d return raise TypeError( \"cannot set value of type {} as Currency",
"currencies to be divided def __truediv__(self, other): if not isinstance(other, Currency): return self.__truediv__(Currency(other))",
"!= other.value def _op_other_as_binary_data(self, other): if isinstance(other, (str, bytes, bytearray)): other = BinaryData(",
"\"{} is not a valid string encoding\".format(strencoding)) self._strencoding = strencoding # define fixed",
"self.value.__ne__(other.value) def __gt__(self, other): if not isinstance(other, Currency): return self.__gt__(Currency(other)) return self.value.__gt__(other.value) def",
"def __str__(self): return self._to_str(self._value) def str(self): return self.__str__() def __repr__(self): return self.__str__() def",
"to be an encoded string when part of a JSON object\") if obj",
"self._fixed_size != None and lvalue != 0 and lvalue != self._fixed_size: raise ValueError(",
"be at least 0, {} is not allowed\".format(fixed_size)) if fixed_size != 0: self._fixed_size",
"raise TypeError( \"fixed size should be at least 0, {} is not allowed\".format(fixed_size))",
"!= None and not isinstance(obj, str): raise TypeError( \"currency is expected to be",
"self._value = jsdec.Decimal() return if isinstance(value, Currency): self._value = value.value return if isinstance(value,",
"is first return value if exp < -9: raise tferrors.CurrencyPrecisionOverflow(d.__str__()) # if sign",
"Binary Encoding format. \"\"\" b = self.bytes() encoder.add_int(len(b)) encoder.add_array(b) def rivine_binary_encode(self, encoder): \"\"\"",
"s = jsstr.rstrip(jsstr.rstrip(s, \"0 \"), '.') if jsstr.isempty(s): s = \"0\" if with_unit:",
"unit with the str \"\"\" s = self.value.str(precision) if lowest_unit: s = jsstr.lstrip(jsstr.replace(s,",
"def __ge__(self, other): if not isinstance(other, Currency): return self.__ge__(Currency(other)) return self.value.__ge__(other.value) @staticmethod def",
"return self # operator overloading to allow currencies to be divided def __truediv__(self,",
"return Currency(self.value.__mul__(other.value).to_nearest(9)) def __rmul__(self, other): return self.__mul__(other) def __imul__(self, other): if not isinstance(other,",
"strencoding=strencoding) @property def value(self): return self._value @value.setter def value(self, value): # normalize the",
"# based on the binary length of the value self._fixed_size = len(self.value) @classmethod",
"expected to be an encoded string when part of a JSON object\") if",
"value if fixed_size == 0: # define the fixed size now, if the",
"# operator overloading to allow currencies to be compared def __lt__(self, other): if",
"def __rsub__(self, other): return self.__sub__(other) def __isub__(self, other): if not isinstance(other, Currency): return",
"class Hash(BinaryData): SIZE = 32 \"\"\" TFChain Hash Object, a special type of",
"be None or a str, not be of type {}\".format(strencoding)) if strencoding ==",
"return self.__isub__(Currency(other)) self._value.__isub__(other.value) return self # operator overloading to allow currencies to be",
"stake to be turned into an int def __int__(self): return jsstr.to_int(self.value.str(lowest_unit=False)) def str(self):",
"self({}) != other({})\".format( self._fixed_size, other._fixed_size)) if self._strencoding != other._strencoding: raise TypeError( \"Cannot compare",
">= 4 and inner_value[-3:] == 'TFT': inner_value = jsstr.rstrip(inner_value[:-3]) d = jsdec.Decimal(inner_value) _,",
"bytearray)): other = BinaryData( value=other, fixed_size=self._fixed_size, strencoding=self._strencoding) elif not isinstance(other, BinaryData): raise TypeError(",
"jsstr.String(strencoding).lower().strip().__eq__('hex'): self._from_str = lambda s: jshex.bytes_from_hex(s) self._to_str = lambda value: jshex.bytes_to_hex(value) elif jsstr.String(strencoding).lower().strip().__eq__('base64'):",
"is not allowed\".format( self._fixed_size, len(value))) # all good, assign the bytearray value self._value",
"should be at least 0, {} is not allowed\".format(fixed_size)) if fixed_size != 0:",
"self # operator overloading to allow currencies to be multiplied def __mul__(self, other):",
"into a str TFT unit-based value, optionally with the currency notation. @param with_unit:",
"string when part of a JSON object, not {}\".format(type(obj))) if obj == '':",
"Currency(self.value.__truediv__(other.value).to_nearest(9)) # operator overloading to allow currencies to be subtracted def __sub__(self, other):",
"_op_other_as_binary_data(self, other): if isinstance(other, (str, bytes, bytearray)): other = BinaryData( value=other, fixed_size=self._fixed_size, strencoding=self._strencoding)",
"TypeError( \"fixed size should be None or int, not be of type {}\".format(type(fixed_size)))",
"# operator overloading to allow currencies to be multiplied def __mul__(self, other): if",
"\".\"): s = jsstr.rstrip(jsstr.rstrip(s, \"0 \"), '.') if jsstr.isempty(s): s = \"0\" if",
"int def __int__(self): return jsstr.to_int(self.value.str(lowest_unit=False)) def str(self): return jsstr.from_int(self.__int__()) def __str__(self): return self.str()",
"lvalue != 0 and lvalue != self._fixed_size: raise ValueError( \"binary data was expected",
"self._value = value def __len__(self): return len(self.value) def __str__(self): return self._to_str(self._value) def str(self):",
"None or a str, not be of type {}\".format(strencoding)) if strencoding == None",
"operator overloading to allow currencies to be multiplied def __mul__(self, other): if not",
"binary data according to the Sia Binary Encoding format. Either encoded as a",
"__int__(self): return jsstr.to_int(self.value.str(lowest_unit=False)) def str(self): return jsstr.from_int(self.__int__()) def __str__(self): return self.str() def __repr__(self):",
"if isinstance(value, BinaryData): value = value.value elif value == None: if self._fixed_size !=",
"size {}, length {} is not allowed\".format( self._fixed_size, len(value))) # all good, assign",
"# for now use no fixed size # define the value (finally) self._value",
"raise TypeError( \"hash is expected to be an encoded string when part of",
"None: if self._fixed_size != None: value = bytes(jsarray.new_array(self._fixed_size)) else: value = bytes(jsarray.new_array(0)) elif",
"or not it is fixed sized. \"\"\" if self._fixed_size == None: encoder.add_slice(self._value) else:",
"size if fixed_size != None: if not isinstance(fixed_size, int): raise TypeError( \"fixed size",
"return other def __hash__(self): return hash(self.__str__()) def sia_binary_encode(self, encoder): \"\"\" Encode this binary",
"elif jsstr.String(strencoding).lower().strip().__eq__('base64'): self._from_str = lambda s: jsbase64.bytes_from_b64(s) self._to_str = lambda value: jsbase64.bytes_to_b64(value) elif",
", not type {}\".format(type(obj))) if obj == '': obj = None c =",
"self._from_str(value) elif isinstance(value, bytearray): value = bytes(value) elif not isinstance(value, bytes) and not",
"type {}\".format(strencoding)) if strencoding == None or jsstr.String(strencoding).lower().strip().__eq__('hex'): self._from_str = lambda s: jshex.bytes_from_hex(s)",
"other): if not isinstance(other, Currency): return self.__iadd__(Currency(other)) self._value.__iadd__(other.value) return self # operator overloading",
"self.value.bytes() def sia_binary_encode(self, encoder): \"\"\" Encode this block stake (==Currency) according to the",
"not supported\".format(type(other))) return other # allow our currency to be turned into an",
"self.bytes() encoder.add_int(len(b)) encoder.add_array(b) def rivine_binary_encode(self, encoder): \"\"\" Encode this block stake (==Currency) according",
"raise TypeError( \"binary data can only be set to a BinaryData, str, bytes",
"into an int def __int__(self): return jsstr.to_int(self.str(lowest_unit=True)) def bytes(self): return self.value.bytes(prec=9) def __str__(self):",
"from_json(cls, obj): if obj != None and not isinstance(obj, str): raise TypeError( \"block",
"value, optionally with the currency notation. @param with_unit: include the TFT currency suffix",
"# operator overloading to allow currencies to be subtracted def __sub__(self, other): if",
"raise TypeError( \"strencoding should be None or a str, not be of type",
"0: # define the fixed size now, if the fixed_size was 0 #",
"*values): s = cls() for value in values: s.__iadd__(value) return s @classmethod def",
"different fixed size: self({}) != other({})\".format( self._fixed_size, other._fixed_size)) if self._strencoding != other._strencoding: raise",
"def __lt__(self, other): if not isinstance(other, Currency): return self.__lt__(Currency(other)) return self.value.__lt__(other.value) def __le__(self,",
"self.__gt__(Currency(other)) return self.value.__gt__(other.value) def __ge__(self, other): if not isinstance(other, Currency): return self.__ge__(Currency(other)) return",
"str): inner_value = jsstr.String(inner_value).upper().strip().value if len(inner_value) >= 4 and inner_value[-3:] == 'TFT': inner_value",
"elif isinstance(value, bytearray): value = bytes(value) elif not isinstance(value, bytes) and not jsarray.is_uint8_array(value):",
"other): return self.__ge__(other) def negate(self): return Currency(self.value.negate()) @value.setter def value(self, value): if value",
"# define fixed size if fixed_size != None: if not isinstance(fixed_size, int): raise",
"if with_unit: s += \" TFT\" return s def __repr__(self): return self.str(with_unit=True) def",
"of a JSON object\") if obj == '': obj = None return cls(value=obj,",
"the Rivine Binary Encoding format. \"\"\" b = self.bytes() encoder.add_slice(b) class Blockstake(BaseDataTypeClass): \"\"\"",
"str(self): return self.__str__() def __repr__(self): return self.__str__() def json(self): return self.__str__() def __eq__(self,",
"\"Cannot compare binary data with different fixed size: self({}) != other({})\".format( self._fixed_size, other._fixed_size))",
"other): if not isinstance(other, Currency): return self.__isub__(Currency(other)) self._value.__isub__(other.value) return self # operator overloading",
"Currency(self.value.__add__(other.value)) def __radd__(self, other): return self.__add__(other) def __iadd__(self, other): if not isinstance(other, Currency):",
"lvalue = len(value) if self._fixed_size != None and lvalue != 0 and lvalue",
"value(self): return self._value @value.setter def value(self, value): # normalize the value if isinstance(value,",
"# if sign != 0: # allow negative values for intermediate computations #",
"class Currency(BaseDataTypeClass): \"\"\" TFChain Currency Object. \"\"\" def __init__(self, value=None): self._value = None",
"value == None: self._value = jsdec.Decimal() return if isinstance(value, Currency): self._value = value.value",
"lambda value: jshex.bytes_to_hex(value) elif jsstr.String(strencoding).lower().strip().__eq__('base64'): self._from_str = lambda s: jsbase64.bytes_from_b64(s) self._to_str = lambda",
"jsdec import tfchain.polyfill.array as jsarray from tfchain.types.BaseDataType import BaseDataTypeClass class BinaryData(BaseDataTypeClass): \"\"\" BinaryData",
"Sia Binary Encoding format. Either encoded as a slice or an array, depending",
"Rivine Binary Encoding format. Either encoded as a slice or an array, depending",
"fixed size # define the value (finally) self._value = None self.value = value",
"jsstr.repeat('0', Hash.SIZE*2) return s class Currency(BaseDataTypeClass): \"\"\" TFChain Currency Object. \"\"\" def __init__(self,",
"to be of fixed size {}, length {} is not allowed\".format( self._fixed_size, len(value)))",
"jsstr.String(strencoding).lower().strip().__eq__('hexprefix'): self._from_str = lambda s: jshex.bytes_from_hex( s[2:] if (s.startswith(\"0x\") or s.startswith(\"0X\")) else s)",
"return other # allow our currency to be turned into an int def",
"return self._to_str(self._value) def str(self): return self.__str__() def __repr__(self): return self.__str__() def json(self): return",
"raise TypeError( \"block stake is expected to be a string when part of",
"!= 0: self._fixed_size = fixed_size else: self._fixed_size = None # for now use",
"supported\".format(type(other))) if self._fixed_size != other._fixed_size: raise TypeError( \"Cannot compare binary data with different",
"TFChain Currency Object. \"\"\" def __init__(self, value=None): self._value = None self.value = value",
"def less_than(self, other): return self.__lt__(other) def greater_than(self, other): return self.__gt__(other) def less_than_or_equal_to(self, other):",
"if isinstance(other, (int, str)): other = Currency(value=other) elif isinstance(other, float): other = Currency(value=jsdec.Decimal(str(other)))",
"'': obj = None return cls(value=obj) def __str__(self): s = super().__str__() if jsstr.isempty(s):",
"be multiplied def __mul__(self, other): if not isinstance(other, Currency): return self.__mul__(Currency(other)) return Currency(self.value.__mul__(other.value).to_nearest(9))",
"str TFT unit-based value, optionally with the currency notation. @param with_unit: include the",
"with the str \"\"\" s = self.value.str(precision) if lowest_unit: s = jsstr.lstrip(jsstr.replace(s, \".\",",
"self._from_str = lambda s: jsbase64.bytes_from_b64(s) self._to_str = lambda value: jsbase64.bytes_to_b64(value) elif jsstr.String(strencoding).lower().strip().__eq__('hexprefix'): self._from_str",
"TypeError( \"fixed size should be at least 0, {} is not allowed\".format(fixed_size)) if",
"self._op_other_as_binary_data(other) return self.value != other.value def _op_other_as_binary_data(self, other): if isinstance(other, (str, bytes, bytearray)):",
"Encode this binary data according to the Sia Binary Encoding format. Either encoded",
"inner_value = value if isinstance(inner_value, str): inner_value = jsstr.String(inner_value).upper().strip().value if len(inner_value) >= 4",
"isinstance(fixed_size, int): raise TypeError( \"fixed size should be None or int, not be",
"fixed size {}, length {} is not allowed\".format( self._fixed_size, len(value))) # all good,",
"other._fixed_size: raise TypeError( \"Cannot compare binary data with different fixed size: self({}) !=",
"not allowed\".format( self._fixed_size, len(value))) # all good, assign the bytearray value self._value =",
"if exp < -9: raise tferrors.CurrencyPrecisionOverflow(d.__str__()) # if sign != 0: # allow",
"isinstance(inner_value, str): inner_value = jsstr.String(inner_value).upper().strip().value if len(inner_value) >= 4 and inner_value[-3:] == 'TFT':",
"jsstr.String(strencoding).lower().strip().__eq__('base64'): self._from_str = lambda s: jsbase64.bytes_from_b64(s) self._to_str = lambda value: jsbase64.bytes_to_b64(value) elif jsstr.String(strencoding).lower().strip().__eq__('hexprefix'):",
"other): if not isinstance(other, Currency): return self.__add__(Currency(other)) return Currency(self.value.__add__(other.value)) def __radd__(self, other): return",
"self.__str__() def __eq__(self, other): other = self._op_other_as_binary_data(other) return self.value == other.value def __ne__(self,",
"0: raise TypeError( \"fixed size should be at least 0, {} is not",
"rivine_binary_encode(self, encoder): \"\"\" Encode this currency according to the Rivine Binary Encoding format.",
"if len(inner_value) >= 4 and inner_value[-3:] == 'TFT': inner_value = jsstr.rstrip(inner_value[:-3]) d =",
"to allow currencies to be compared def __lt__(self, other): if not isinstance(other, Currency):",
"Rivine Binary Encoding format. \"\"\" b = self.bytes() encoder.add_slice(b) class Blockstake(BaseDataTypeClass): \"\"\" TFChain",
"if jsstr.isempty(s): s = \"0\" if with_unit: s += \" TFT\" return s",
"return self.str(lowest_unit=True) def sia_binary_encode(self, encoder): \"\"\" Encode this currency according to the Sia",
"suffix unit with the str \"\"\" s = self.value.str(precision) if lowest_unit: s =",
"if fixed_size == 0: # define the fixed size now, if the fixed_size",
"if fixed_size < 0: raise TypeError( \"fixed size should be at least 0,",
"negative values for intermediate computations # raise tferrors.CurrencyNegativeValue(d.__str__()) self._value = d return raise",
"self._fixed_size = len(self.value) @classmethod def from_json(cls, obj, fixed_size=None, strencoding=None): if obj != None",
"sum(cls, *values): s = cls() for value in values: s.__iadd__(value) return s @classmethod",
"return self.value.__gt__(other.value) def __ge__(self, other): if not isinstance(other, Currency): return self.__ge__(Currency(other)) return self.value.__ge__(other.value)",
"if isinstance(other, (str, bytes, bytearray)): other = BinaryData( value=other, fixed_size=self._fixed_size, strencoding=self._strencoding) elif not",
"value): if value == None: self._value = jsdec.Decimal() return if isinstance(value, Currency): self._value",
"to allow currencies to be multiplied def __mul__(self, other): if not isinstance(other, Currency):",
"length {} is not allowed\".format( self._fixed_size, len(value))) # all good, assign the bytearray",
"# normalize the value if isinstance(value, BinaryData): value = value.value elif value ==",
"value = bytes(jsarray.new_array(self._fixed_size)) else: value = bytes(jsarray.new_array(0)) elif isinstance(value, str): value = self._from_str(value)",
"object, not {}\".format(type(obj))) if obj == '': obj = None return cls(value=obj) def",
"a str, not be of type {}\".format(strencoding)) if strencoding == None or jsstr.String(strencoding).lower().strip().__eq__('hex'):",
"str(self, with_unit=False, lowest_unit=False, precision=9): \"\"\" Turn this Currency value into a str TFT",
"self._fixed_size == None: encoder.add_slice(self._value) else: encoder.add_array(self._value) class Hash(BinaryData): SIZE = 32 \"\"\" TFChain",
"BinaryData(BaseDataTypeClass): \"\"\" BinaryData is the data type used for any binary data used",
"isinstance(value, bytearray): value = bytes(value) elif not isinstance(value, bytes) and not jsarray.is_uint8_array(value): raise",
"for intermediate computations # raise tferrors.CurrencyNegativeValue(d.__str__()) self._value = d return raise TypeError( \"cannot",
"self._fixed_size != None: value = bytes(jsarray.new_array(self._fixed_size)) else: value = bytes(jsarray.new_array(0)) elif isinstance(value, str):",
"data was expected to be of fixed size {}, length {} is not",
"obj, fixed_size=None, strencoding=None): if obj != None and not isinstance(obj, str): raise TypeError(",
"= 32 \"\"\" TFChain Hash Object, a special type of BinaryData \"\"\" def",
"def __truediv__(self, other): if not isinstance(other, Currency): return self.__truediv__(Currency(other)) return Currency(self.value.__truediv__(other.value).to_nearest(9)) # operator",
"block stake (==Currency) according to the Rivine Binary Encoding format. \"\"\" b =",
"b = self.bytes() encoder.add_int(len(b)) encoder.add_array(b) def rivine_binary_encode(self, encoder): \"\"\" Encode this currency according",
"according to the Rivine Binary Encoding format. \"\"\" b = self.bytes() encoder.add_slice(b) class",
"value of type {} as Currency (invalid type): {}\".format(type(value), value)) # operator overloading",
"obj != None and not isinstance(obj, str): raise TypeError( \"binary data is expected",
"raise TypeError( \"currency is expected to be a string , not type {}\".format(type(obj)))",
"@property def value(self): return self._value def plus(self, other): return self.__add__(other) def minus(self, other):",
"self._value.__iadd__(other.value) return self # operator overloading to allow currencies to be multiplied def",
"return Currency(self.value.__truediv__(other.value).to_nearest(9)) # operator overloading to allow currencies to be subtracted def __sub__(self,",
"be None or int, not be of type {}\".format(type(fixed_size))) if fixed_size < 0:",
"\"\"\" Encode this block stake (==Currency) according to the Rivine Binary Encoding format.",
"self._to_str(self._value) def str(self): return self.__str__() def __repr__(self): return self.__str__() def json(self): return self.__str__()",
"def __iadd__(self, other): if not isinstance(other, Currency): return self.__iadd__(Currency(other)) self._value.__iadd__(other.value) return self #",
"None: value = bytes(jsarray.new_array(self._fixed_size)) else: value = bytes(jsarray.new_array(0)) elif isinstance(value, str): value =",
"expected to be a string when part of a JSON object, not type",
"return self._value @value.setter def value(self, value): value._value = Currency(value=value) # allow our block",
"bytes(jsarray.new_array(0)) elif isinstance(value, str): value = self._from_str(value) elif isinstance(value, bytearray): value = bytes(value)",
"str \"\"\" s = self.value.str(precision) if lowest_unit: s = jsstr.lstrip(jsstr.replace(s, \".\", \"\"), \"0\")",
"value = value.value elif value == None: if self._fixed_size != None: value =",
"be turned into an int def __int__(self): return jsstr.to_int(self.str(lowest_unit=True)) def bytes(self): return self.value.bytes(prec=9)",
"not isinstance(other, Currency): return self.__truediv__(Currency(other)) return Currency(self.value.__truediv__(other.value).to_nearest(9)) # operator overloading to allow currencies",
"self.__isub__(Currency(other)) self._value.__isub__(other.value) return self # operator overloading to allow currencies to be compared",
"to be divided def __truediv__(self, other): if not isinstance(other, Currency): return self.__truediv__(Currency(other)) return",
"at least 0, {} is not allowed\".format(fixed_size)) if fixed_size != 0: self._fixed_size =",
"other): return self.__add__(other) def __iadd__(self, other): if not isinstance(other, Currency): return self.__iadd__(Currency(other)) self._value.__iadd__(other.value)",
"return Currency(self.value.__sub__(other.value)) def __rsub__(self, other): return self.__sub__(other) def __isub__(self, other): if not isinstance(other,",
"self.__mul__(Currency(other)) return Currency(self.value.__mul__(other.value).to_nearest(9)) def __rmul__(self, other): return self.__mul__(other) def __imul__(self, other): if not",
"\"fixed size should be None or int, not be of type {}\".format(type(fixed_size))) if",
"encoder.add_array(b) def rivine_binary_encode(self, encoder): \"\"\" Encode this block stake (==Currency) according to the",
"allow currencies to be divided def __truediv__(self, other): if not isinstance(other, Currency): return",
"!= None and not isinstance(obj, str): raise TypeError( \"block stake is expected to",
"with_unit: s += \" TFT\" return s def __repr__(self): return self.str(with_unit=True) def json(self):",
"def __int__(self): return jsstr.to_int(self.str(lowest_unit=True)) def bytes(self): return self.value.bytes(prec=9) def __str__(self): return self.str() def",
"__truediv__(self, other): if not isinstance(other, Currency): return self.__truediv__(Currency(other)) return Currency(self.value.__truediv__(other.value).to_nearest(9)) # operator overloading",
"other._strencoding)) return other def __hash__(self): return hash(self.__str__()) def sia_binary_encode(self, encoder): \"\"\" Encode this",
"self.__ge__(other) def negate(self): return Currency(self.value.negate()) @value.setter def value(self, value): if value == None:",
"when part of a JSON object, not {}\".format(type(obj))) if obj == '': obj",
"if self._fixed_size == None: encoder.add_slice(self._value) else: encoder.add_array(self._value) class Hash(BinaryData): SIZE = 32 \"\"\"",
"elif jsstr.String(strencoding).lower().strip().__eq__('hexprefix'): self._from_str = lambda s: jshex.bytes_from_hex( s[2:] if (s.startswith(\"0x\") or s.startswith(\"0X\")) else",
"if strencoding == None or jsstr.String(strencoding).lower().strip().__eq__('hex'): self._from_str = lambda s: jshex.bytes_from_hex(s) self._to_str =",
"if not isinstance(other, Currency): return self.__imul__(Currency(other)) self._value.__imul__(other.value) return self # operator overloading to",
"def __ne__(self, other): if not isinstance(other, Currency): return self.__ne__(Currency(other)) return self.value.__ne__(other.value) def __gt__(self,",
"Currency): self._value = value.value return if isinstance(value, (int, str, jsdec.Decimal)): inner_value = value",
"return self.value.__le__(other.value) def __eq__(self, other): if not isinstance(other, Currency): return self.__eq__(Currency(other)) return self.value.__eq__(other.value)",
"import tfchain.polyfill.encoding.decimal as jsdec import tfchain.polyfill.array as jsarray from tfchain.types.BaseDataType import BaseDataTypeClass class",
"other._fixed_size)) if self._strencoding != other._strencoding: raise TypeError( \"Cannot compare binary data with different",
"be of type {}\".format(strencoding)) if strencoding == None or jsstr.String(strencoding).lower().strip().__eq__('hex'): self._from_str = lambda",
"self.value.__le__(other.value) def __eq__(self, other): if not isinstance(other, Currency): return self.__eq__(Currency(other)) return self.value.__eq__(other.value) def",
"self._fixed_size: raise ValueError( \"binary data was expected to be of fixed size {},",
"should be None or a str, not be of type {}\".format(strencoding)) if strencoding",
"\"\"\" s = self.value.str(precision) if lowest_unit: s = jsstr.lstrip(jsstr.replace(s, \".\", \"\"), \"0\") elif",
"cls(value=obj, fixed_size=fixed_size, strencoding=strencoding) @property def value(self): return self._value @value.setter def value(self, value): #",
"= bytes(value) elif not isinstance(value, bytes) and not jsarray.is_uint8_array(value): raise TypeError( \"binary data",
"with different fixed size: self({}) != other({})\".format( self._fixed_size, other._fixed_size)) if self._strencoding != other._strencoding:",
"\"\"\" def __init__(self, value=None): self._value = Currency(value) @classmethod def from_json(cls, obj): if obj",
"return self.__str__() def __eq__(self, other): other = self._op_other_as_binary_data(other) return self.value == other.value def",
"allow currencies to be multiplied def __mul__(self, other): if not isinstance(other, Currency): return",
"format. Either encoded as a slice or an array, depending on whether or",
"not isinstance(other, Currency): return self.__add__(Currency(other)) return Currency(self.value.__add__(other.value)) def __radd__(self, other): return self.__add__(other) def",
"fixed_size=None, strencoding=None): if obj != None and not isinstance(obj, str): raise TypeError( \"binary",
"this currency according to the Sia Binary Encoding format. \"\"\" b = self.bytes()",
"if not isinstance(other, Currency): return self.__add__(Currency(other)) return Currency(self.value.__add__(other.value)) def __radd__(self, other): return self.__add__(other)",
"BinaryData): value = value.value elif value == None: if self._fixed_size != None: value",
"Binary Encoding format. \"\"\" b = self.bytes() encoder.add_slice(b) class Blockstake(BaseDataTypeClass): \"\"\" TFChain Blockstake",
"self._value.__isub__(other.value) return self # operator overloading to allow currencies to be compared def",
"'': obj = None c = cls() c.value = jsdec.Decimal(obj) if lowest_unit: c.value.__imul__(jsdec.Decimal('0.000000001'))",
"return self.__sub__(other) def __isub__(self, other): if not isinstance(other, Currency): return self.__isub__(Currency(other)) self._value.__isub__(other.value) return",
"raise TypeError( \"binary data is expected to be an encoded string when part",
"def greater_than_or_equal_to(self, other): return self.__ge__(other) def negate(self): return Currency(self.value.negate()) @value.setter def value(self, value):",
"== other.value def __ne__(self, other): other = self._op_other_as_binary_data(other) return self.value != other.value def",
"value @classmethod def sum(cls, *values): s = cls() for value in values: s.__iadd__(value)",
"isinstance(other, Currency): return self.__ne__(Currency(other)) return self.value.__ne__(other.value) def __gt__(self, other): if not isinstance(other, Currency):",
"# allow our block stake to be turned into an int def __int__(self):",
"fixed_size=None, strencoding=None): # define string encoding if strencoding != None and not isinstance(strencoding,",
"__ne__(self, other): if not isinstance(other, Currency): return self.__ne__(Currency(other)) return self.value.__ne__(other.value) def __gt__(self, other):",
"compare binary data with different strencoding: self({}) != other({})\".format( self._strencoding, other._strencoding)) return other",
"self._fixed_size, other._fixed_size)) if self._strencoding != other._strencoding: raise TypeError( \"Cannot compare binary data with",
"not isinstance(value, bytes) and not jsarray.is_uint8_array(value): raise TypeError( \"binary data can only be",
"jsstr import tfchain.polyfill.encoding.decimal as jsdec import tfchain.polyfill.array as jsarray from tfchain.types.BaseDataType import BaseDataTypeClass",
"Object, a special type of BinaryData \"\"\" def __init__(self, value=None): super().__init__(value, fixed_size=Hash.SIZE, strencoding='hex')",
"lowest_unit=False): if obj != None and not isinstance(obj, str): raise TypeError( \"currency is",
"isinstance(other, (int, str)): other = Currency(value=other) elif isinstance(other, float): other = Currency(value=jsdec.Decimal(str(other))) elif",
"len(self.value) def __str__(self): return self._to_str(self._value) def str(self): return self.__str__() def __repr__(self): return self.__str__()",
"# raise tferrors.CurrencyNegativeValue(d.__str__()) self._value = d return raise TypeError( \"cannot set value of",
"and lvalue != self._fixed_size: raise ValueError( \"binary data was expected to be of",
"TypeError( \"binary data is expected to be an encoded string when part of",
"to be an encoded string when part of a JSON object, not {}\".format(type(obj)))",
"Currency(BaseDataTypeClass): \"\"\" TFChain Currency Object. \"\"\" def __init__(self, value=None): self._value = None self.value",
"this now lvalue = len(value) if self._fixed_size != None and lvalue != 0",
"4 and inner_value[-3:] == 'TFT': inner_value = jsstr.rstrip(inner_value[:-3]) d = jsdec.Decimal(inner_value) _, _,",
"def __gt__(self, other): if not isinstance(other, Currency): return self.__gt__(Currency(other)) return self.value.__gt__(other.value) def __ge__(self,",
"if not isinstance(other, Currency): return self.__ge__(Currency(other)) return self.value.__ge__(other.value) @staticmethod def _op_other_as_currency(other): if isinstance(other,",
"for any binary data used in tfchain. \"\"\" def __init__(self, value=None, fixed_size=None, strencoding=None):",
"type {} is not supported\".format(type(other))) if self._fixed_size != other._fixed_size: raise TypeError( \"Cannot compare",
"Hash.SIZE*2) return s class Currency(BaseDataTypeClass): \"\"\" TFChain Currency Object. \"\"\" def __init__(self, value=None):",
"multiplied def __mul__(self, other): if not isinstance(other, Currency): return self.__mul__(Currency(other)) return Currency(self.value.__mul__(other.value).to_nearest(9)) def",
"__rsub__(self, other): return self.__sub__(other) def __isub__(self, other): if not isinstance(other, Currency): return self.__isub__(Currency(other))",
"currency to be turned into an int def __int__(self): return jsstr.to_int(self.str(lowest_unit=True)) def bytes(self):",
"None: if not isinstance(fixed_size, int): raise TypeError( \"fixed size should be None or",
"greater_than_or_equal_to(self, other): return self.__ge__(other) def negate(self): return Currency(self.value.negate()) @value.setter def value(self, value): if",
"not isinstance(other, BinaryData): raise TypeError( \"Binary data of type {} is not supported\".format(type(other)))",
"not isinstance(other, Currency): return self.__imul__(Currency(other)) self._value.__imul__(other.value) return self # operator overloading to allow",
"operator overloading to allow currencies to be summed def __add__(self, other): if not",
"lowest_unit: c.value.__imul__(jsdec.Decimal('0.000000001')) return c @classmethod def from_json(_, obj): return Currency.from_str(obj, lowest_unit=True) @property def",
"the str \"\"\" s = self.value.str(precision) if lowest_unit: s = jsstr.lstrip(jsstr.replace(s, \".\", \"\"),",
"return self # operator overloading to allow currencies to be compared def __lt__(self,",
"BinaryData): raise TypeError( \"Binary data of type {} is not supported\".format(type(other))) if self._fixed_size",
"cls(value=obj) def __str__(self): s = super().__str__() if jsstr.isempty(s): return jsstr.repeat('0', Hash.SIZE*2) return s",
"tfchain.polyfill.encoding.hex as jshex import tfchain.polyfill.encoding.str as jsstr import tfchain.polyfill.encoding.decimal as jsdec import tfchain.polyfill.array",
"return self.__sub__(other) def times(self, other): return self.__mul__(other) def divided_by(self, other): return self.__truediv__(other) def",
"tfchain.types.BaseDataType import BaseDataTypeClass class BinaryData(BaseDataTypeClass): \"\"\" BinaryData is the data type used for",
"__radd__(self, other): return self.__add__(other) def __iadd__(self, other): if not isinstance(other, Currency): return self.__iadd__(Currency(other))",
"if lowest_unit: s = jsstr.lstrip(jsstr.replace(s, \".\", \"\"), \"0\") elif jsstr.contains(s, \".\"): s =",
"is not allowed\".format(fixed_size)) if fixed_size != 0: self._fixed_size = fixed_size else: self._fixed_size =",
"int def __int__(self): return jsstr.to_int(self.str(lowest_unit=True)) def bytes(self): return self.value.bytes(prec=9) def __str__(self): return self.str()",
"this binary data according to the Sia Binary Encoding format. Either encoded as",
"a special type of BinaryData \"\"\" def __init__(self, value=None): super().__init__(value, fixed_size=Hash.SIZE, strencoding='hex') @classmethod",
"fixed_size == 0: # define the fixed size now, if the fixed_size was",
"notation. @param with_unit: include the TFT currency suffix unit with the str \"\"\"",
"value: '0x' + jshex.bytes_to_hex(value) else: raise TypeError( \"{} is not a valid string",
"tfchain.polyfill.encoding.decimal as jsdec import tfchain.polyfill.array as jsarray from tfchain.types.BaseDataType import BaseDataTypeClass class BinaryData(BaseDataTypeClass):",
"self.value.bytes(prec=9) def __str__(self): return self.str() def str(self, with_unit=False, lowest_unit=False, precision=9): \"\"\" Turn this",
"def not_equal_to(self, other): return self.__ne__(other) def less_than(self, other): return self.__lt__(other) def greater_than(self, other):",
"is not supported\".format(type(other))) return other # allow our currency to be turned into",
"\"\"\" Encode this currency according to the Sia Binary Encoding format. \"\"\" b",
"None and not isinstance(obj, str): raise TypeError( \"hash is expected to be an",
"a BinaryData, str, bytes or bytearray, not {}\".format(type(value))) # if fixed size, check",
"strencoding=None): if obj != None and not isinstance(obj, str): raise TypeError( \"binary data",
"None and not isinstance(obj, str): raise TypeError( \"currency is expected to be a",
"if obj != None and not isinstance(obj, str): raise TypeError( \"binary data is",
"fixed size: self({}) != other({})\".format( self._fixed_size, other._fixed_size)) if self._strencoding != other._strencoding: raise TypeError(",
"jsstr.isempty(s): return jsstr.repeat('0', Hash.SIZE*2) return s class Currency(BaseDataTypeClass): \"\"\" TFChain Currency Object. \"\"\"",
"isinstance(obj, str): raise TypeError( \"hash is expected to be an encoded string when",
"str, not be of type {}\".format(strencoding)) if strencoding == None or jsstr.String(strencoding).lower().strip().__eq__('hex'): self._from_str",
"\"\"\" TFChain Blockstake Object. \"\"\" def __init__(self, value=None): self._value = Currency(value) @classmethod def",
"the currency notation. @param with_unit: include the TFT currency suffix unit with the",
"None: encoder.add_slice(self._value) else: encoder.add_array(self._value) def rivine_binary_encode(self, encoder): \"\"\" Encode this binary data according",
"sized. \"\"\" if self._fixed_size == None: encoder.add_slice(self._value) else: encoder.add_array(self._value) class Hash(BinaryData): SIZE =",
"for now use no fixed size # define the value (finally) self._value =",
"= lambda s: jshex.bytes_from_hex(s) self._to_str = lambda value: jshex.bytes_to_hex(value) elif jsstr.String(strencoding).lower().strip().__eq__('base64'): self._from_str =",
"@classmethod def from_json(cls, obj, fixed_size=None, strencoding=None): if obj != None and not isinstance(obj,",
"return self.__add__(other) def __iadd__(self, other): if not isinstance(other, Currency): return self.__iadd__(Currency(other)) self._value.__iadd__(other.value) return",
"!= 0: # allow negative values for intermediate computations # raise tferrors.CurrencyNegativeValue(d.__str__()) self._value",
"if self._fixed_size != None: value = bytes(jsarray.new_array(self._fixed_size)) else: value = bytes(jsarray.new_array(0)) elif isinstance(value,",
"not isinstance(other, Currency): return self.__eq__(Currency(other)) return self.value.__eq__(other.value) def __ne__(self, other): if not isinstance(other,",
"set value of type {} as Currency (invalid type): {}\".format(type(value), value)) # operator",
"len(value) if self._fixed_size != None and lvalue != 0 and lvalue != self._fixed_size:",
"# operator overloading to allow currencies to be divided def __truediv__(self, other): if",
"!= None: if not isinstance(fixed_size, int): raise TypeError( \"fixed size should be None",
"self._strencoding, other._strencoding)) return other def __hash__(self): return hash(self.__str__()) def sia_binary_encode(self, encoder): \"\"\" Encode",
"return jsstr.from_int(self.__int__()) def __str__(self): return self.str() def __repr__(self): return self.__str__() def json(self): return",
"not isinstance(other, Currency): return self.__iadd__(Currency(other)) self._value.__iadd__(other.value) return self # operator overloading to allow",
"return self.value.bytes(prec=9) def __str__(self): return self.str() def str(self, with_unit=False, lowest_unit=False, precision=9): \"\"\" Turn",
"be turned into an int def __int__(self): return jsstr.to_int(self.value.str(lowest_unit=False)) def str(self): return jsstr.from_int(self.__int__())",
"0 and lvalue != self._fixed_size: raise ValueError( \"binary data was expected to be",
"self.str() def __repr__(self): return self.__str__() def json(self): return self.__str__() def bytes(self): return self.value.bytes()",
"__sub__(self, other): if not isinstance(other, Currency): return self.__sub__(Currency(other)) return Currency(self.value.__sub__(other.value)) def __rsub__(self, other):",
"fixed size, check this now lvalue = len(value) if self._fixed_size != None and",
"jshex.bytes_from_hex( s[2:] if (s.startswith(\"0x\") or s.startswith(\"0X\")) else s) self._to_str = lambda value: '0x'",
"if obj == '': obj = None return cls(value=obj, fixed_size=fixed_size, strencoding=strencoding) @property def",
"other): if not isinstance(other, Currency): return self.__imul__(Currency(other)) self._value.__imul__(other.value) return self # operator overloading",
"is expected to be an encoded string when part of a JSON object\")",
"self.__mul__(other) def __imul__(self, other): if not isinstance(other, Currency): return self.__imul__(Currency(other)) self._value.__imul__(other.value) return self",
"self.__ne__(Currency(other)) return self.value.__ne__(other.value) def __gt__(self, other): if not isinstance(other, Currency): return self.__gt__(Currency(other)) return",
"Object. \"\"\" def __init__(self, value=None): self._value = Currency(value) @classmethod def from_json(cls, obj): if",
"fixed_size != None: if not isinstance(fixed_size, int): raise TypeError( \"fixed size should be",
"use no fixed size # define the value (finally) self._value = None self.value",
"__imul__(self, other): if not isinstance(other, Currency): return self.__imul__(Currency(other)) self._value.__imul__(other.value) return self # operator",
"def sia_binary_encode(self, encoder): \"\"\" Encode this block stake (==Currency) according to the Sia",
"encoder): \"\"\" Encode this binary data according to the Rivine Binary Encoding format.",
"ValueError( \"binary data was expected to be of fixed size {}, length {}",
"_op_other_as_currency(other): if isinstance(other, (int, str)): other = Currency(value=other) elif isinstance(other, float): other =",
"\"\"\" if self._fixed_size == None: encoder.add_slice(self._value) else: encoder.add_array(self._value) class Hash(BinaryData): SIZE = 32",
"\"fixed size should be at least 0, {} is not allowed\".format(fixed_size)) if fixed_size",
"self._value def plus(self, other): return self.__add__(other) def minus(self, other): return self.__sub__(other) def times(self,",
"\" TFT\" return s def __repr__(self): return self.str(with_unit=True) def json(self): return self.str(lowest_unit=True) def",
"other = self._op_other_as_binary_data(other) return self.value != other.value def _op_other_as_binary_data(self, other): if isinstance(other, (str,",
"Turn this Currency value into a str TFT unit-based value, optionally with the",
"None return cls(value=obj) def __str__(self): s = super().__str__() if jsstr.isempty(s): return jsstr.repeat('0', Hash.SIZE*2)",
"obj != None and not isinstance(obj, str): raise TypeError( \"block stake is expected",
"an int def __int__(self): return jsstr.to_int(self.value.str(lowest_unit=False)) def str(self): return jsstr.from_int(self.__int__()) def __str__(self): return",
"bytes, bytearray)): other = BinaryData( value=other, fixed_size=self._fixed_size, strencoding=self._strencoding) elif not isinstance(other, BinaryData): raise",
"\"block stake is expected to be a string when part of a JSON",
"jsbase64.bytes_to_b64(value) elif jsstr.String(strencoding).lower().strip().__eq__('hexprefix'): self._from_str = lambda s: jshex.bytes_from_hex( s[2:] if (s.startswith(\"0x\") or s.startswith(\"0X\"))",
"# define the fixed size now, if the fixed_size was 0 # based",
"= lambda s: jsbase64.bytes_from_b64(s) self._to_str = lambda value: jsbase64.bytes_to_b64(value) elif jsstr.String(strencoding).lower().strip().__eq__('hexprefix'): self._from_str =",
"value if exp < -9: raise tferrors.CurrencyPrecisionOverflow(d.__str__()) # if sign != 0: #",
"_, exp = d.as_tuple() # sign is first return value if exp <",
"{}\".format(type(obj))) if obj == '': obj = None c = cls() c.value =",
"in tfchain. \"\"\" def __init__(self, value=None, fixed_size=None, strencoding=None): # define string encoding if",
"obj): if obj != None and not isinstance(obj, str): raise TypeError( \"hash is",
"encoder.add_array(self._value) class Hash(BinaryData): SIZE = 32 \"\"\" TFChain Hash Object, a special type",
"other): return self.__truediv__(other) def equal_to(self, other): return self.__eq__(other) def not_equal_to(self, other): return self.__ne__(other)",
"def json(self): return self.__str__() def bytes(self): return self.value.bytes() def sia_binary_encode(self, encoder): \"\"\" Encode",
"return self.__truediv__(other) def equal_to(self, other): return self.__eq__(other) def not_equal_to(self, other): return self.__ne__(other) def",
"the binary length of the value self._fixed_size = len(self.value) @classmethod def from_json(cls, obj,",
"strencoding='hex') @classmethod def from_json(cls, obj): if obj != None and not isinstance(obj, str):",
"\"\"\" b = self.bytes() encoder.add_int(len(b)) encoder.add_array(b) def rivine_binary_encode(self, encoder): \"\"\" Encode this block",
"s = jsstr.lstrip(jsstr.replace(s, \".\", \"\"), \"0\") elif jsstr.contains(s, \".\"): s = jsstr.rstrip(jsstr.rstrip(s, \"0",
"Encode this currency according to the Sia Binary Encoding format. \"\"\" b =",
"data with different fixed size: self({}) != other({})\".format( self._fixed_size, other._fixed_size)) if self._strencoding !=",
"return self.__mul__(other) def divided_by(self, other): return self.__truediv__(other) def equal_to(self, other): return self.__eq__(other) def",
"{} is not allowed\".format(fixed_size)) if fixed_size != 0: self._fixed_size = fixed_size else: self._fixed_size",
"if fixed_size != None: if not isinstance(fixed_size, int): raise TypeError( \"fixed size should",
"= d.as_tuple() # sign is first return value if exp < -9: raise",
"equal_to(self, other): return self.__eq__(other) def not_equal_to(self, other): return self.__ne__(other) def less_than(self, other): return",
"= lambda s: jshex.bytes_from_hex( s[2:] if (s.startswith(\"0x\") or s.startswith(\"0X\")) else s) self._to_str =",
"# sign is first return value if exp < -9: raise tferrors.CurrencyPrecisionOverflow(d.__str__()) #",
"@value.setter def value(self, value): value._value = Currency(value=value) # allow our block stake to",
"encoder): \"\"\" Encode this binary data according to the Sia Binary Encoding format.",
"def less_than_or_equal_to(self, other): return self.__le__(other) def greater_than_or_equal_to(self, other): return self.__ge__(other) def negate(self): return",
"# if fixed size, check this now lvalue = len(value) if self._fixed_size !=",
"return self.__le__(other) def greater_than_or_equal_to(self, other): return self.__ge__(other) def negate(self): return Currency(self.value.negate()) @value.setter def",
"{}, length {} is not allowed\".format( self._fixed_size, len(value))) # all good, assign the",
"not be of type {}\".format(type(fixed_size))) if fixed_size < 0: raise TypeError( \"fixed size",
"value(self): return self._value @value.setter def value(self, value): value._value = Currency(value=value) # allow our",
"= self._from_str(value) elif isinstance(value, bytearray): value = bytes(value) elif not isinstance(value, bytes) and",
"jsstr.rstrip(jsstr.rstrip(s, \"0 \"), '.') if jsstr.isempty(s): s = \"0\" if with_unit: s +=",
"0, {} is not allowed\".format(fixed_size)) if fixed_size != 0: self._fixed_size = fixed_size else:",
"other = Currency(value=jsdec.Decimal(str(other))) elif not isinstance(other, Currency): raise TypeError( \"currency of type {}",
"= super().__str__() if jsstr.isempty(s): return jsstr.repeat('0', Hash.SIZE*2) return s class Currency(BaseDataTypeClass): \"\"\" TFChain",
"return self.__ne__(Currency(other)) return self.value.__ne__(other.value) def __gt__(self, other): if not isinstance(other, Currency): return self.__gt__(Currency(other))",
"Blockstake Object. \"\"\" def __init__(self, value=None): self._value = Currency(value) @classmethod def from_json(cls, obj):",
"\"\"\" Turn this Currency value into a str TFT unit-based value, optionally with",
"compare binary data with different fixed size: self({}) != other({})\".format( self._fixed_size, other._fixed_size)) if",
"jshex import tfchain.polyfill.encoding.str as jsstr import tfchain.polyfill.encoding.decimal as jsdec import tfchain.polyfill.array as jsarray",
"from_json(cls, obj): if obj != None and not isinstance(obj, str): raise TypeError( \"hash",
"jsdec.Decimal() return if isinstance(value, Currency): self._value = value.value return if isinstance(value, (int, str,",
"depending on whether or not it is fixed sized. \"\"\" if self._fixed_size ==",
"self.value = value if fixed_size == 0: # define the fixed size now,",
"turned into an int def __int__(self): return jsstr.to_int(self.str(lowest_unit=True)) def bytes(self): return self.value.bytes(prec=9) def",
"if self._strencoding != other._strencoding: raise TypeError( \"Cannot compare binary data with different strencoding:",
"!= other._fixed_size: raise TypeError( \"Cannot compare binary data with different fixed size: self({})",
"plus(self, other): return self.__add__(other) def minus(self, other): return self.__sub__(other) def times(self, other): return",
"= lambda value: jshex.bytes_to_hex(value) elif jsstr.String(strencoding).lower().strip().__eq__('base64'): self._from_str = lambda s: jsbase64.bytes_from_b64(s) self._to_str =",
"optionally with the currency notation. @param with_unit: include the TFT currency suffix unit",
"__init__(self, value=None, fixed_size=None, strencoding=None): # define string encoding if strencoding != None and",
"obj != None and not isinstance(obj, str): raise TypeError( \"hash is expected to",
"class BinaryData(BaseDataTypeClass): \"\"\" BinaryData is the data type used for any binary data",
"used in tfchain. \"\"\" def __init__(self, value=None, fixed_size=None, strencoding=None): # define string encoding",
"bytearray): value = bytes(value) elif not isinstance(value, bytes) and not jsarray.is_uint8_array(value): raise TypeError(",
"value = bytes(value) elif not isinstance(value, bytes) and not jsarray.is_uint8_array(value): raise TypeError( \"binary",
"return self.value.__ge__(other.value) @staticmethod def _op_other_as_currency(other): if isinstance(other, (int, str)): other = Currency(value=other) elif",
"s += \" TFT\" return s def __repr__(self): return self.str(with_unit=True) def json(self): return",
"return self.__truediv__(Currency(other)) return Currency(self.value.__truediv__(other.value).to_nearest(9)) # operator overloading to allow currencies to be subtracted",
"part of a JSON object, not {}\".format(type(obj))) if obj == '': obj =",
"length of the value self._fixed_size = len(self.value) @classmethod def from_json(cls, obj, fixed_size=None, strencoding=None):",
"encoder.add_int(len(b)) encoder.add_array(b) def rivine_binary_encode(self, encoder): \"\"\" Encode this currency according to the Rivine",
"other({})\".format( self._strencoding, other._strencoding)) return other def __hash__(self): return hash(self.__str__()) def sia_binary_encode(self, encoder): \"\"\"",
"self.__mul__(other) def divided_by(self, other): return self.__truediv__(other) def equal_to(self, other): return self.__eq__(other) def not_equal_to(self,",
"BinaryData \"\"\" def __init__(self, value=None): super().__init__(value, fixed_size=Hash.SIZE, strencoding='hex') @classmethod def from_json(cls, obj): if",
"as jsstr import tfchain.polyfill.encoding.decimal as jsdec import tfchain.polyfill.array as jsarray from tfchain.types.BaseDataType import",
"obj): if obj != None and not isinstance(obj, str): raise TypeError( \"block stake",
"== '': obj = None return cls(value=obj, fixed_size=fixed_size, strencoding=strencoding) @property def value(self): return",
"with_unit: include the TFT currency suffix unit with the str \"\"\" s =",
"(int, str)): other = Currency(value=other) elif isinstance(other, float): other = Currency(value=jsdec.Decimal(str(other))) elif not",
"on whether or not it is fixed sized. \"\"\" if self._fixed_size == None:",
"other): if not isinstance(other, Currency): return self.__mul__(Currency(other)) return Currency(self.value.__mul__(other.value).to_nearest(9)) def __rmul__(self, other): return",
"bytes(self): return self.value.bytes() def sia_binary_encode(self, encoder): \"\"\" Encode this block stake (==Currency) according",
"< -9: raise tferrors.CurrencyPrecisionOverflow(d.__str__()) # if sign != 0: # allow negative values",
"\".\", \"\"), \"0\") elif jsstr.contains(s, \".\"): s = jsstr.rstrip(jsstr.rstrip(s, \"0 \"), '.') if",
"def greater_than(self, other): return self.__gt__(other) def less_than_or_equal_to(self, other): return self.__le__(other) def greater_than_or_equal_to(self, other):",
"lowest_unit: s = jsstr.lstrip(jsstr.replace(s, \".\", \"\"), \"0\") elif jsstr.contains(s, \".\"): s = jsstr.rstrip(jsstr.rstrip(s,",
"{} is not supported\".format(type(other))) return other # allow our currency to be turned",
"def rivine_binary_encode(self, encoder): \"\"\" Encode this block stake (==Currency) according to the Rivine",
"None and lvalue != 0 and lvalue != self._fixed_size: raise ValueError( \"binary data",
"jsstr.to_int(self.value.str(lowest_unit=False)) def str(self): return jsstr.from_int(self.__int__()) def __str__(self): return self.str() def __repr__(self): return self.__str__()",
"c.value = jsdec.Decimal(obj) if lowest_unit: c.value.__imul__(jsdec.Decimal('0.000000001')) return c @classmethod def from_json(_, obj): return",
"TypeError( \"cannot set value of type {} as Currency (invalid type): {}\".format(type(value), value))",
"jsbase64 import tfchain.polyfill.encoding.hex as jshex import tfchain.polyfill.encoding.str as jsstr import tfchain.polyfill.encoding.decimal as jsdec",
"isinstance(other, Currency): return self.__ge__(Currency(other)) return self.value.__ge__(other.value) @staticmethod def _op_other_as_currency(other): if isinstance(other, (int, str)):",
"def str(self): return jsstr.from_int(self.__int__()) def __str__(self): return self.str() def __repr__(self): return self.__str__() def",
"the value self._fixed_size = len(self.value) @classmethod def from_json(cls, obj, fixed_size=None, strencoding=None): if obj",
"not isinstance(other, Currency): return self.__le__(Currency(other)) return self.value.__le__(other.value) def __eq__(self, other): if not isinstance(other,",
"@value.setter def value(self, value): # normalize the value if isinstance(value, BinaryData): value =",
"fixed_size=self._fixed_size, strencoding=self._strencoding) elif not isinstance(other, BinaryData): raise TypeError( \"Binary data of type {}",
"= len(self.value) @classmethod def from_json(cls, obj, fixed_size=None, strencoding=None): if obj != None and",
"_, _, exp = d.as_tuple() # sign is first return value if exp",
"\"\"\" Encode this currency according to the Rivine Binary Encoding format. \"\"\" b",
"is the data type used for any binary data used in tfchain. \"\"\"",
"None return cls(value=obj, fixed_size=fixed_size, strencoding=strencoding) @property def value(self): return self._value @value.setter def value(self,",
"= lambda value: '0x' + jshex.bytes_to_hex(value) else: raise TypeError( \"{} is not a",
"not allowed\".format(fixed_size)) if fixed_size != 0: self._fixed_size = fixed_size else: self._fixed_size = None",
"isinstance(value, bytes) and not jsarray.is_uint8_array(value): raise TypeError( \"binary data can only be set",
"!= None and not isinstance(strencoding, str): raise TypeError( \"strencoding should be None or",
"= self.bytes() encoder.add_int(len(b)) encoder.add_array(b) def rivine_binary_encode(self, encoder): \"\"\" Encode this currency according to",
"currencies to be subtracted def __sub__(self, other): if not isinstance(other, Currency): return self.__sub__(Currency(other))",
"obj == '': obj = None return cls(value=obj) @property def value(self): return self._value",
"or an array, depending on whether or not it is fixed sized. \"\"\"",
"return self.__lt__(Currency(other)) return self.value.__lt__(other.value) def __le__(self, other): if not isinstance(other, Currency): return self.__le__(Currency(other))",
"value=None, fixed_size=None, strencoding=None): # define string encoding if strencoding != None and not",
"import tfchain.polyfill.encoding.hex as jshex import tfchain.polyfill.encoding.str as jsstr import tfchain.polyfill.encoding.decimal as jsdec import",
"def __rmul__(self, other): return self.__mul__(other) def __imul__(self, other): if not isinstance(other, Currency): return",
"(invalid type): {}\".format(type(value), value)) # operator overloading to allow currencies to be summed",
"currency notation. @param with_unit: include the TFT currency suffix unit with the str",
"+= \" TFT\" return s def __repr__(self): return self.str(with_unit=True) def json(self): return self.str(lowest_unit=True)",
"to be a string when part of a JSON object, not type {}\".format(type(obj)))",
"if self._fixed_size != None and lvalue != 0 and lvalue != self._fixed_size: raise",
"encoder.add_array(self._value) def rivine_binary_encode(self, encoder): \"\"\" Encode this binary data according to the Rivine",
"= jsdec.Decimal(inner_value) _, _, exp = d.as_tuple() # sign is first return value",
"return self.str() def __repr__(self): return self.__str__() def json(self): return self.__str__() def bytes(self): return",
"__ge__(self, other): if not isinstance(other, Currency): return self.__ge__(Currency(other)) return self.value.__ge__(other.value) @staticmethod def _op_other_as_currency(other):",
"+ jshex.bytes_to_hex(value) else: raise TypeError( \"{} is not a valid string encoding\".format(strencoding)) self._strencoding",
"return Currency.from_str(obj, lowest_unit=True) @property def value(self): return self._value def plus(self, other): return self.__add__(other)",
"with different strencoding: self({}) != other({})\".format( self._strencoding, other._strencoding)) return other def __hash__(self): return",
"\"hash is expected to be an encoded string when part of a JSON",
"if isinstance(inner_value, str): inner_value = jsstr.String(inner_value).upper().strip().value if len(inner_value) >= 4 and inner_value[-3:] ==",
"encoder.add_slice(self._value) else: encoder.add_array(self._value) class Hash(BinaryData): SIZE = 32 \"\"\" TFChain Hash Object, a",
"self.__ge__(Currency(other)) return self.value.__ge__(other.value) @staticmethod def _op_other_as_currency(other): if isinstance(other, (int, str)): other = Currency(value=other)",
"__eq__(self, other): other = self._op_other_as_binary_data(other) return self.value == other.value def __ne__(self, other): other",
"slice or an array, depending on whether or not it is fixed sized.",
"of a JSON object, not {}\".format(type(obj))) if obj == '': obj = None",
"as jsarray from tfchain.types.BaseDataType import BaseDataTypeClass class BinaryData(BaseDataTypeClass): \"\"\" BinaryData is the data",
"valid string encoding\".format(strencoding)) self._strencoding = strencoding # define fixed size if fixed_size !=",
"if isinstance(value, (int, str, jsdec.Decimal)): inner_value = value if isinstance(inner_value, str): inner_value =",
"= value.value return if isinstance(value, (int, str, jsdec.Decimal)): inner_value = value if isinstance(inner_value,",
"a JSON object\") if obj == '': obj = None return cls(value=obj, fixed_size=fixed_size,",
"value=None): self._value = None self.value = value @classmethod def sum(cls, *values): s =",
"\"\"\" TFChain Currency Object. \"\"\" def __init__(self, value=None): self._value = None self.value =",
"TFChain Hash Object, a special type of BinaryData \"\"\" def __init__(self, value=None): super().__init__(value,",
"exp = d.as_tuple() # sign is first return value if exp < -9:",
"other.value def _op_other_as_binary_data(self, other): if isinstance(other, (str, bytes, bytearray)): other = BinaryData( value=other,",
"isinstance(value, BinaryData): value = value.value elif value == None: if self._fixed_size != None:",
"!= None and not isinstance(obj, str): raise TypeError( \"hash is expected to be",
"return s class Currency(BaseDataTypeClass): \"\"\" TFChain Currency Object. \"\"\" def __init__(self, value=None): self._value",
"size # define the value (finally) self._value = None self.value = value if",
"def value(self): return self._value @value.setter def value(self, value): # normalize the value if",
"not isinstance(other, Currency): return self.__isub__(Currency(other)) self._value.__isub__(other.value) return self # operator overloading to allow",
"used for any binary data used in tfchain. \"\"\" def __init__(self, value=None, fixed_size=None,",
"\"\"\" Encode this block stake (==Currency) according to the Sia Binary Encoding format.",
"elif isinstance(other, float): other = Currency(value=jsdec.Decimal(str(other))) elif not isinstance(other, Currency): raise TypeError( \"currency",
"= Currency(value=value) # allow our block stake to be turned into an int",
"inner_value = jsstr.String(inner_value).upper().strip().value if len(inner_value) >= 4 and inner_value[-3:] == 'TFT': inner_value =",
"not isinstance(other, Currency): raise TypeError( \"currency of type {} is not supported\".format(type(other))) return",
"size should be at least 0, {} is not allowed\".format(fixed_size)) if fixed_size !=",
"fixed_size else: self._fixed_size = None # for now use no fixed size #",
"or int, not be of type {}\".format(type(fixed_size))) if fixed_size < 0: raise TypeError(",
"= bytes(jsarray.new_array(0)) elif isinstance(value, str): value = self._from_str(value) elif isinstance(value, bytearray): value =",
"= None self.value = value @classmethod def sum(cls, *values): s = cls() for",
"@classmethod def from_json(cls, obj): if obj != None and not isinstance(obj, str): raise",
"def from_json(cls, obj): if obj != None and not isinstance(obj, str): raise TypeError(",
"lambda value: jsbase64.bytes_to_b64(value) elif jsstr.String(strencoding).lower().strip().__eq__('hexprefix'): self._from_str = lambda s: jshex.bytes_from_hex( s[2:] if (s.startswith(\"0x\")",
"else: encoder.add_array(self._value) def rivine_binary_encode(self, encoder): \"\"\" Encode this binary data according to the",
"s[2:] if (s.startswith(\"0x\") or s.startswith(\"0X\")) else s) self._to_str = lambda value: '0x' +",
"= Currency(value=other) elif isinstance(other, float): other = Currency(value=jsdec.Decimal(str(other))) elif not isinstance(other, Currency): raise",
"def bytes(self): return self.value.bytes(prec=9) def __str__(self): return self.str() def str(self, with_unit=False, lowest_unit=False, precision=9):",
"stake (==Currency) according to the Rivine Binary Encoding format. \"\"\" b = self.bytes()",
"based on the binary length of the value self._fixed_size = len(self.value) @classmethod def",
"obj = None return cls(value=obj, fixed_size=fixed_size, strencoding=strencoding) @property def value(self): return self._value @value.setter",
"None and not isinstance(obj, str): raise TypeError( \"block stake is expected to be",
"Currency): return self.__eq__(Currency(other)) return self.value.__eq__(other.value) def __ne__(self, other): if not isinstance(other, Currency): return",
"@staticmethod def _op_other_as_currency(other): if isinstance(other, (int, str)): other = Currency(value=other) elif isinstance(other, float):",
"def __init__(self, value=None, fixed_size=None, strencoding=None): # define string encoding if strencoding != None",
"= jsstr.String(inner_value).upper().strip().value if len(inner_value) >= 4 and inner_value[-3:] == 'TFT': inner_value = jsstr.rstrip(inner_value[:-3])",
"def __init__(self, value=None): super().__init__(value, fixed_size=Hash.SIZE, strencoding='hex') @classmethod def from_json(cls, obj): if obj !=",
"Binary Encoding format. Either encoded as a slice or an array, depending on",
"if self._fixed_size != other._fixed_size: raise TypeError( \"Cannot compare binary data with different fixed",
"not isinstance(other, Currency): return self.__gt__(Currency(other)) return self.value.__gt__(other.value) def __ge__(self, other): if not isinstance(other,",
"str): raise TypeError( \"currency is expected to be a string , not type",
"self.__imul__(Currency(other)) self._value.__imul__(other.value) return self # operator overloading to allow currencies to be divided",
"return self.__sub__(Currency(other)) return Currency(self.value.__sub__(other.value)) def __rsub__(self, other): return self.__sub__(other) def __isub__(self, other): if",
"inner_value = jsstr.rstrip(inner_value[:-3]) d = jsdec.Decimal(inner_value) _, _, exp = d.as_tuple() # sign",
"and lvalue != 0 and lvalue != self._fixed_size: raise ValueError( \"binary data was",
"type {}\".format(type(obj))) if obj == '': obj = None return cls(value=obj) @property def",
"(int, str, jsdec.Decimal)): inner_value = value if isinstance(inner_value, str): inner_value = jsstr.String(inner_value).upper().strip().value if",
"< 0: raise TypeError( \"fixed size should be at least 0, {} is",
"not isinstance(fixed_size, int): raise TypeError( \"fixed size should be None or int, not",
"allow currencies to be summed def __add__(self, other): if not isinstance(other, Currency): return",
"\"0 \"), '.') if jsstr.isempty(s): s = \"0\" if with_unit: s += \"",
"__str__(self): return self._to_str(self._value) def str(self): return self.__str__() def __repr__(self): return self.__str__() def json(self):",
"if obj != None and not isinstance(obj, str): raise TypeError( \"hash is expected",
"len(self.value) @classmethod def from_json(cls, obj, fixed_size=None, strencoding=None): if obj != None and not",
"s @classmethod def from_str(cls, obj, lowest_unit=False): if obj != None and not isinstance(obj,",
"self._strencoding != other._strencoding: raise TypeError( \"Cannot compare binary data with different strencoding: self({})",
"\"0\" if with_unit: s += \" TFT\" return s def __repr__(self): return self.str(with_unit=True)",
"tfchain.errors as tferrors import tfchain.polyfill.encoding.base64 as jsbase64 import tfchain.polyfill.encoding.hex as jshex import tfchain.polyfill.encoding.str",
"not isinstance(obj, str): raise TypeError( \"hash is expected to be an encoded string",
"or a str, not be of type {}\".format(strencoding)) if strencoding == None or",
"value = self._from_str(value) elif isinstance(value, bytearray): value = bytes(value) elif not isinstance(value, bytes)",
"jsstr.contains(s, \".\"): s = jsstr.rstrip(jsstr.rstrip(s, \"0 \"), '.') if jsstr.isempty(s): s = \"0\"",
"Object. \"\"\" def __init__(self, value=None): self._value = None self.value = value @classmethod def",
"now lvalue = len(value) if self._fixed_size != None and lvalue != 0 and",
"tfchain.polyfill.array as jsarray from tfchain.types.BaseDataType import BaseDataTypeClass class BinaryData(BaseDataTypeClass): \"\"\" BinaryData is the",
"obj == '': obj = None return cls(value=obj, fixed_size=fixed_size, strencoding=strencoding) @property def value(self):",
"= jsstr.rstrip(jsstr.rstrip(s, \"0 \"), '.') if jsstr.isempty(s): s = \"0\" if with_unit: s",
"other): if not isinstance(other, Currency): return self.__lt__(Currency(other)) return self.value.__lt__(other.value) def __le__(self, other): if",
"self.__gt__(other) def less_than_or_equal_to(self, other): return self.__le__(other) def greater_than_or_equal_to(self, other): return self.__ge__(other) def negate(self):",
"of type {}\".format(type(fixed_size))) if fixed_size < 0: raise TypeError( \"fixed size should be",
"or bytearray, not {}\".format(type(value))) # if fixed size, check this now lvalue =",
"__lt__(self, other): if not isinstance(other, Currency): return self.__lt__(Currency(other)) return self.value.__lt__(other.value) def __le__(self, other):",
"SIZE = 32 \"\"\" TFChain Hash Object, a special type of BinaryData \"\"\"",
"__len__(self): return len(self.value) def __str__(self): return self._to_str(self._value) def str(self): return self.__str__() def __repr__(self):",
"Currency(self.value.__sub__(other.value)) def __rsub__(self, other): return self.__sub__(other) def __isub__(self, other): if not isinstance(other, Currency):",
"Sia Binary Encoding format. \"\"\" b = self.bytes() encoder.add_int(len(b)) encoder.add_array(b) def rivine_binary_encode(self, encoder):",
"Encode this block stake (==Currency) according to the Sia Binary Encoding format. \"\"\"",
"lambda s: jshex.bytes_from_hex(s) self._to_str = lambda value: jshex.bytes_to_hex(value) elif jsstr.String(strencoding).lower().strip().__eq__('base64'): self._from_str = lambda",
"special type of BinaryData \"\"\" def __init__(self, value=None): super().__init__(value, fixed_size=Hash.SIZE, strencoding='hex') @classmethod def",
"be divided def __truediv__(self, other): if not isinstance(other, Currency): return self.__truediv__(Currency(other)) return Currency(self.value.__truediv__(other.value).to_nearest(9))",
"and not isinstance(obj, str): raise TypeError( \"hash is expected to be an encoded",
"def __repr__(self): return self.str(with_unit=True) def json(self): return self.str(lowest_unit=True) def sia_binary_encode(self, encoder): \"\"\" Encode",
"TypeError( \"hash is expected to be an encoded string when part of a",
"Currency(value=value) # allow our block stake to be turned into an int def",
"== None: encoder.add_slice(self._value) else: encoder.add_array(self._value) def rivine_binary_encode(self, encoder): \"\"\" Encode this binary data",
"def __repr__(self): return self.__str__() def json(self): return self.__str__() def bytes(self): return self.value.bytes() def",
"__repr__(self): return self.str(with_unit=True) def json(self): return self.str(lowest_unit=True) def sia_binary_encode(self, encoder): \"\"\" Encode this",
"stake (==Currency) according to the Sia Binary Encoding format. \"\"\" b = self.bytes()",
"= cls() for value in values: s.__iadd__(value) return s @classmethod def from_str(cls, obj,",
"= BinaryData( value=other, fixed_size=self._fixed_size, strencoding=self._strencoding) elif not isinstance(other, BinaryData): raise TypeError( \"Binary data",
"if not isinstance(other, Currency): return self.__sub__(Currency(other)) return Currency(self.value.__sub__(other.value)) def __rsub__(self, other): return self.__sub__(other)",
"overloading to allow currencies to be compared def __lt__(self, other): if not isinstance(other,",
"(s.startswith(\"0x\") or s.startswith(\"0X\")) else s) self._to_str = lambda value: '0x' + jshex.bytes_to_hex(value) else:",
"{} is not supported\".format(type(other))) if self._fixed_size != other._fixed_size: raise TypeError( \"Cannot compare binary",
"other): if not isinstance(other, Currency): return self.__gt__(Currency(other)) return self.value.__gt__(other.value) def __ge__(self, other): if",
"not isinstance(other, Currency): return self.__ge__(Currency(other)) return self.value.__ge__(other.value) @staticmethod def _op_other_as_currency(other): if isinstance(other, (int,",
"def minus(self, other): return self.__sub__(other) def times(self, other): return self.__mul__(other) def divided_by(self, other):",
"self.value.__gt__(other.value) def __ge__(self, other): if not isinstance(other, Currency): return self.__ge__(Currency(other)) return self.value.__ge__(other.value) @staticmethod",
"def _op_other_as_currency(other): if isinstance(other, (int, str)): other = Currency(value=other) elif isinstance(other, float): other",
"self.__str__() def json(self): return self.__str__() def bytes(self): return self.value.bytes() def sia_binary_encode(self, encoder): \"\"\"",
"= \"0\" if with_unit: s += \" TFT\" return s def __repr__(self): return",
"data is expected to be an encoded string when part of a JSON",
"encoder): \"\"\" Encode this block stake (==Currency) according to the Sia Binary Encoding",
"def value(self, value): # normalize the value if isinstance(value, BinaryData): value = value.value",
"jshex.bytes_to_hex(value) elif jsstr.String(strencoding).lower().strip().__eq__('base64'): self._from_str = lambda s: jsbase64.bytes_from_b64(s) self._to_str = lambda value: jsbase64.bytes_to_b64(value)",
"define the fixed size now, if the fixed_size was 0 # based on",
"def str(self, with_unit=False, lowest_unit=False, precision=9): \"\"\" Turn this Currency value into a str",
"is expected to be a string when part of a JSON object, not",
"if value == None: self._value = jsdec.Decimal() return if isinstance(value, Currency): self._value =",
"if not isinstance(other, Currency): return self.__ne__(Currency(other)) return self.value.__ne__(other.value) def __gt__(self, other): if not",
"and not jsarray.is_uint8_array(value): raise TypeError( \"binary data can only be set to a",
"{}\".format(type(obj))) if obj == '': obj = None return cls(value=obj) def __str__(self): s",
"Currency): return self.__imul__(Currency(other)) self._value.__imul__(other.value) return self # operator overloading to allow currencies to",
"Encoding format. \"\"\" b = self.bytes() encoder.add_slice(b) class Blockstake(BaseDataTypeClass): \"\"\" TFChain Blockstake Object.",
"encoded string when part of a JSON object, not {}\".format(type(obj))) if obj ==",
"return self.__mul__(other) def __imul__(self, other): if not isinstance(other, Currency): return self.__imul__(Currency(other)) self._value.__imul__(other.value) return",
"self.value = value @classmethod def sum(cls, *values): s = cls() for value in",
"self._fixed_size != other._fixed_size: raise TypeError( \"Cannot compare binary data with different fixed size:",
"Currency): raise TypeError( \"currency of type {} is not supported\".format(type(other))) return other #",
"def divided_by(self, other): return self.__truediv__(other) def equal_to(self, other): return self.__eq__(other) def not_equal_to(self, other):",
"currency according to the Sia Binary Encoding format. \"\"\" b = self.bytes() encoder.add_int(len(b))",
"is expected to be a string , not type {}\".format(type(obj))) if obj ==",
"include the TFT currency suffix unit with the str \"\"\" s = self.value.str(precision)",
"a slice or an array, depending on whether or not it is fixed",
"== '': obj = None return cls(value=obj) def __str__(self): s = super().__str__() if",
"isinstance(obj, str): raise TypeError( \"block stake is expected to be a string when",
"string encoding if strencoding != None and not isinstance(strencoding, str): raise TypeError( \"strencoding",
"TFT currency suffix unit with the str \"\"\" s = self.value.str(precision) if lowest_unit:",
"isinstance(obj, str): raise TypeError( \"currency is expected to be a string , not",
"== None or jsstr.String(strencoding).lower().strip().__eq__('hex'): self._from_str = lambda s: jshex.bytes_from_hex(s) self._to_str = lambda value:",
"elif isinstance(value, str): value = self._from_str(value) elif isinstance(value, bytearray): value = bytes(value) elif",
"not supported\".format(type(other))) if self._fixed_size != other._fixed_size: raise TypeError( \"Cannot compare binary data with",
"self.__sub__(Currency(other)) return Currency(self.value.__sub__(other.value)) def __rsub__(self, other): return self.__sub__(other) def __isub__(self, other): if not",
"allow our currency to be turned into an int def __int__(self): return jsstr.to_int(self.str(lowest_unit=True))",
"obj, lowest_unit=False): if obj != None and not isinstance(obj, str): raise TypeError( \"currency",
"jsdec.Decimal(inner_value) _, _, exp = d.as_tuple() # sign is first return value if",
"{}\".format(type(obj))) if obj == '': obj = None return cls(value=obj) @property def value(self):",
"value: jsbase64.bytes_to_b64(value) elif jsstr.String(strencoding).lower().strip().__eq__('hexprefix'): self._from_str = lambda s: jshex.bytes_from_hex( s[2:] if (s.startswith(\"0x\") or",
"Currency(value) @classmethod def from_json(cls, obj): if obj != None and not isinstance(obj, str):",
"Currency): return self.__le__(Currency(other)) return self.value.__le__(other.value) def __eq__(self, other): if not isinstance(other, Currency): return",
"jsdec.Decimal)): inner_value = value if isinstance(inner_value, str): inner_value = jsstr.String(inner_value).upper().strip().value if len(inner_value) >=",
"s: jshex.bytes_from_hex(s) self._to_str = lambda value: jshex.bytes_to_hex(value) elif jsstr.String(strencoding).lower().strip().__eq__('base64'): self._from_str = lambda s:",
"raise TypeError( \"Binary data of type {} is not supported\".format(type(other))) if self._fixed_size !=",
"not isinstance(obj, str): raise TypeError( \"currency is expected to be a string ,",
"TypeError( \"currency of type {} is not supported\".format(type(other))) return other # allow our",
"return self.__add__(other) def minus(self, other): return self.__sub__(other) def times(self, other): return self.__mul__(other) def",
"or jsstr.String(strencoding).lower().strip().__eq__('hex'): self._from_str = lambda s: jshex.bytes_from_hex(s) self._to_str = lambda value: jshex.bytes_to_hex(value) elif",
"define fixed size if fixed_size != None: if not isinstance(fixed_size, int): raise TypeError(",
"it is fixed sized. \"\"\" if self._fixed_size == None: encoder.add_slice(self._value) else: encoder.add_array(self._value) class",
"expected to be of fixed size {}, length {} is not allowed\".format( self._fixed_size,",
"if self._fixed_size == None: encoder.add_slice(self._value) else: encoder.add_array(self._value) def rivine_binary_encode(self, encoder): \"\"\" Encode this",
"def value(self, value): if value == None: self._value = jsdec.Decimal() return if isinstance(value,",
"self.__add__(other) def minus(self, other): return self.__sub__(other) def times(self, other): return self.__mul__(other) def divided_by(self,",
"elif value == None: if self._fixed_size != None: value = bytes(jsarray.new_array(self._fixed_size)) else: value",
"fixed_size != 0: self._fixed_size = fixed_size else: self._fixed_size = None # for now",
"= cls() c.value = jsdec.Decimal(obj) if lowest_unit: c.value.__imul__(jsdec.Decimal('0.000000001')) return c @classmethod def from_json(_,",
"== 'TFT': inner_value = jsstr.rstrip(inner_value[:-3]) d = jsdec.Decimal(inner_value) _, _, exp = d.as_tuple()",
"binary data used in tfchain. \"\"\" def __init__(self, value=None, fixed_size=None, strencoding=None): # define",
"== 0: # define the fixed size now, if the fixed_size was 0",
"be of type {}\".format(type(fixed_size))) if fixed_size < 0: raise TypeError( \"fixed size should",
"of type {}\".format(strencoding)) if strencoding == None or jsstr.String(strencoding).lower().strip().__eq__('hex'): self._from_str = lambda s:",
"self._fixed_size == None: encoder.add_slice(self._value) else: encoder.add_array(self._value) def rivine_binary_encode(self, encoder): \"\"\" Encode this binary",
"compared def __lt__(self, other): if not isinstance(other, Currency): return self.__lt__(Currency(other)) return self.value.__lt__(other.value) def",
"Encode this binary data according to the Rivine Binary Encoding format. Either encoded",
"into an int def __int__(self): return jsstr.to_int(self.value.str(lowest_unit=False)) def str(self): return jsstr.from_int(self.__int__()) def __str__(self):",
"return self # operator overloading to allow currencies to be multiplied def __mul__(self,",
"s) self._to_str = lambda value: '0x' + jshex.bytes_to_hex(value) else: raise TypeError( \"{} is",
"Encoding format. \"\"\" b = self.bytes() encoder.add_int(len(b)) encoder.add_array(b) def rivine_binary_encode(self, encoder): \"\"\" Encode",
"__hash__(self): return hash(self.__str__()) def sia_binary_encode(self, encoder): \"\"\" Encode this binary data according to",
"from tfchain.types.BaseDataType import BaseDataTypeClass class BinaryData(BaseDataTypeClass): \"\"\" BinaryData is the data type used",
"value._value = Currency(value=value) # allow our block stake to be turned into an",
"!= None: value = bytes(jsarray.new_array(self._fixed_size)) else: value = bytes(jsarray.new_array(0)) elif isinstance(value, str): value",
"s = \"0\" if with_unit: s += \" TFT\" return s def __repr__(self):",
"if fixed_size != 0: self._fixed_size = fixed_size else: self._fixed_size = None # for",
"self._to_str = lambda value: jshex.bytes_to_hex(value) elif jsstr.String(strencoding).lower().strip().__eq__('base64'): self._from_str = lambda s: jsbase64.bytes_from_b64(s) self._to_str",
"= None self.value = value if fixed_size == 0: # define the fixed",
"def __init__(self, value=None): self._value = None self.value = value @classmethod def sum(cls, *values):",
"the data type used for any binary data used in tfchain. \"\"\" def",
"obj = None c = cls() c.value = jsdec.Decimal(obj) if lowest_unit: c.value.__imul__(jsdec.Decimal('0.000000001')) return",
"def __isub__(self, other): if not isinstance(other, Currency): return self.__isub__(Currency(other)) self._value.__isub__(other.value) return self #",
"to allow currencies to be summed def __add__(self, other): if not isinstance(other, Currency):",
"to be compared def __lt__(self, other): if not isinstance(other, Currency): return self.__lt__(Currency(other)) return",
"be a string when part of a JSON object, not type {}\".format(type(obj))) if",
"BinaryData( value=other, fixed_size=self._fixed_size, strencoding=self._strencoding) elif not isinstance(other, BinaryData): raise TypeError( \"Binary data of",
"not {}\".format(type(obj))) if obj == '': obj = None return cls(value=obj) def __str__(self):",
"return len(self.value) def __str__(self): return self._to_str(self._value) def str(self): return self.__str__() def __repr__(self): return",
"return self.__gt__(Currency(other)) return self.value.__gt__(other.value) def __ge__(self, other): if not isinstance(other, Currency): return self.__ge__(Currency(other))",
"== '': obj = None return cls(value=obj) @property def value(self): return self._value @value.setter",
"is not a valid string encoding\".format(strencoding)) self._strencoding = strencoding # define fixed size",
"the fixed_size was 0 # based on the binary length of the value",
"other): return self.__sub__(other) def __isub__(self, other): if not isinstance(other, Currency): return self.__isub__(Currency(other)) self._value.__isub__(other.value)",
"\"binary data can only be set to a BinaryData, str, bytes or bytearray,",
"self.__le__(other) def greater_than_or_equal_to(self, other): return self.__ge__(other) def negate(self): return Currency(self.value.negate()) @value.setter def value(self,",
"summed def __add__(self, other): if not isinstance(other, Currency): return self.__add__(Currency(other)) return Currency(self.value.__add__(other.value)) def",
"def __imul__(self, other): if not isinstance(other, Currency): return self.__imul__(Currency(other)) self._value.__imul__(other.value) return self #",
"= jsstr.rstrip(inner_value[:-3]) d = jsdec.Decimal(inner_value) _, _, exp = d.as_tuple() # sign is",
"32 \"\"\" TFChain Hash Object, a special type of BinaryData \"\"\" def __init__(self,",
"(finally) self._value = None self.value = value if fixed_size == 0: # define",
"type {}\".format(type(obj))) if obj == '': obj = None c = cls() c.value",
"set to a BinaryData, str, bytes or bytearray, not {}\".format(type(value))) # if fixed",
"Currency.from_str(obj, lowest_unit=True) @property def value(self): return self._value def plus(self, other): return self.__add__(other) def",
"bytes) and not jsarray.is_uint8_array(value): raise TypeError( \"binary data can only be set to",
"value=None): super().__init__(value, fixed_size=Hash.SIZE, strencoding='hex') @classmethod def from_json(cls, obj): if obj != None and",
"value into a str TFT unit-based value, optionally with the currency notation. @param",
"operator overloading to allow currencies to be compared def __lt__(self, other): if not",
"sized. \"\"\" if self._fixed_size == None: encoder.add_slice(self._value) else: encoder.add_array(self._value) def rivine_binary_encode(self, encoder): \"\"\"",
"!= None and not isinstance(obj, str): raise TypeError( \"binary data is expected to",
"currencies to be multiplied def __mul__(self, other): if not isinstance(other, Currency): return self.__mul__(Currency(other))",
"value (finally) self._value = None self.value = value if fixed_size == 0: #",
"None c = cls() c.value = jsdec.Decimal(obj) if lowest_unit: c.value.__imul__(jsdec.Decimal('0.000000001')) return c @classmethod",
"def __str__(self): return self.str() def __repr__(self): return self.__str__() def json(self): return self.__str__() def",
"of BinaryData \"\"\" def __init__(self, value=None): super().__init__(value, fixed_size=Hash.SIZE, strencoding='hex') @classmethod def from_json(cls, obj):",
"part of a JSON object\") if obj == '': obj = None return",
"the TFT currency suffix unit with the str \"\"\" s = self.value.str(precision) if",
"__repr__(self): return self.__str__() def json(self): return self.__str__() def bytes(self): return self.value.bytes() def sia_binary_encode(self,",
"allowed\".format( self._fixed_size, len(value))) # all good, assign the bytearray value self._value = value",
"# operator overloading to allow currencies to be summed def __add__(self, other): if",
"str(self): return jsstr.from_int(self.__int__()) def __str__(self): return self.str() def __repr__(self): return self.__str__() def json(self):",
"inner_value[-3:] == 'TFT': inner_value = jsstr.rstrip(inner_value[:-3]) d = jsdec.Decimal(inner_value) _, _, exp =",
"class Blockstake(BaseDataTypeClass): \"\"\" TFChain Blockstake Object. \"\"\" def __init__(self, value=None): self._value = Currency(value)",
"def from_json(_, obj): return Currency.from_str(obj, lowest_unit=True) @property def value(self): return self._value def plus(self,",
"jsstr.isempty(s): s = \"0\" if with_unit: s += \" TFT\" return s def",
"'.') if jsstr.isempty(s): s = \"0\" if with_unit: s += \" TFT\" return",
"cls(value=obj) @property def value(self): return self._value @value.setter def value(self, value): value._value = Currency(value=value)",
"block stake to be turned into an int def __int__(self): return jsstr.to_int(self.value.str(lowest_unit=False)) def",
"not {}\".format(type(value))) # if fixed size, check this now lvalue = len(value) if",
"data of type {} is not supported\".format(type(other))) if self._fixed_size != other._fixed_size: raise TypeError(",
"TypeError( \"strencoding should be None or a str, not be of type {}\".format(strencoding))",
"to be subtracted def __sub__(self, other): if not isinstance(other, Currency): return self.__sub__(Currency(other)) return",
"Currency): return self.__mul__(Currency(other)) return Currency(self.value.__mul__(other.value).to_nearest(9)) def __rmul__(self, other): return self.__mul__(other) def __imul__(self, other):",
"data can only be set to a BinaryData, str, bytes or bytearray, not",
"lambda s: jsbase64.bytes_from_b64(s) self._to_str = lambda value: jsbase64.bytes_to_b64(value) elif jsstr.String(strencoding).lower().strip().__eq__('hexprefix'): self._from_str = lambda",
"if lowest_unit: c.value.__imul__(jsdec.Decimal('0.000000001')) return c @classmethod def from_json(_, obj): return Currency.from_str(obj, lowest_unit=True) @property",
"lowest_unit=True) @property def value(self): return self._value def plus(self, other): return self.__add__(other) def minus(self,",
"it is fixed sized. \"\"\" if self._fixed_size == None: encoder.add_slice(self._value) else: encoder.add_array(self._value) def",
"== None: if self._fixed_size != None: value = bytes(jsarray.new_array(self._fixed_size)) else: value = bytes(jsarray.new_array(0))",
"@value.setter def value(self, value): if value == None: self._value = jsdec.Decimal() return if",
"\"strencoding should be None or a str, not be of type {}\".format(strencoding)) if",
"self.str() def str(self, with_unit=False, lowest_unit=False, precision=9): \"\"\" Turn this Currency value into a",
"currency suffix unit with the str \"\"\" s = self.value.str(precision) if lowest_unit: s",
"other): if not isinstance(other, Currency): return self.__ge__(Currency(other)) return self.value.__ge__(other.value) @staticmethod def _op_other_as_currency(other): if",
"self.__eq__(Currency(other)) return self.value.__eq__(other.value) def __ne__(self, other): if not isinstance(other, Currency): return self.__ne__(Currency(other)) return",
"__eq__(self, other): if not isinstance(other, Currency): return self.__eq__(Currency(other)) return self.value.__eq__(other.value) def __ne__(self, other):",
"a JSON object, not {}\".format(type(obj))) if obj == '': obj = None return",
"return if isinstance(value, (int, str, jsdec.Decimal)): inner_value = value if isinstance(inner_value, str): inner_value",
"this Currency value into a str TFT unit-based value, optionally with the currency",
"isinstance(other, Currency): return self.__isub__(Currency(other)) self._value.__isub__(other.value) return self # operator overloading to allow currencies",
"c @classmethod def from_json(_, obj): return Currency.from_str(obj, lowest_unit=True) @property def value(self): return self._value",
"= None c = cls() c.value = jsdec.Decimal(obj) if lowest_unit: c.value.__imul__(jsdec.Decimal('0.000000001')) return c",
"of the value self._fixed_size = len(self.value) @classmethod def from_json(cls, obj, fixed_size=None, strencoding=None): if",
"not a valid string encoding\".format(strencoding)) self._strencoding = strencoding # define fixed size if",
"isinstance(other, float): other = Currency(value=jsdec.Decimal(str(other))) elif not isinstance(other, Currency): raise TypeError( \"currency of",
"else: value = bytes(jsarray.new_array(0)) elif isinstance(value, str): value = self._from_str(value) elif isinstance(value, bytearray):",
"!= other({})\".format( self._strencoding, other._strencoding)) return other def __hash__(self): return hash(self.__str__()) def sia_binary_encode(self, encoder):",
"Either encoded as a slice or an array, depending on whether or not",
"an int def __int__(self): return jsstr.to_int(self.str(lowest_unit=True)) def bytes(self): return self.value.bytes(prec=9) def __str__(self): return",
"__iadd__(self, other): if not isinstance(other, Currency): return self.__iadd__(Currency(other)) self._value.__iadd__(other.value) return self # operator",
"elif not isinstance(other, Currency): raise TypeError( \"currency of type {} is not supported\".format(type(other)))",
"not isinstance(other, Currency): return self.__ne__(Currency(other)) return self.value.__ne__(other.value) def __gt__(self, other): if not isinstance(other,",
"greater_than(self, other): return self.__gt__(other) def less_than_or_equal_to(self, other): return self.__le__(other) def greater_than_or_equal_to(self, other): return",
"type of BinaryData \"\"\" def __init__(self, value=None): super().__init__(value, fixed_size=Hash.SIZE, strencoding='hex') @classmethod def from_json(cls,",
"TypeError( \"Binary data of type {} is not supported\".format(type(other))) if self._fixed_size != other._fixed_size:",
"None self.value = value if fixed_size == 0: # define the fixed size",
"__le__(self, other): if not isinstance(other, Currency): return self.__le__(Currency(other)) return self.value.__le__(other.value) def __eq__(self, other):",
"BaseDataTypeClass class BinaryData(BaseDataTypeClass): \"\"\" BinaryData is the data type used for any binary",
"a valid string encoding\".format(strencoding)) self._strencoding = strencoding # define fixed size if fixed_size",
"value self._value = value def __len__(self): return len(self.value) def __str__(self): return self._to_str(self._value) def",
"return self.__str__() def __repr__(self): return self.__str__() def json(self): return self.__str__() def __eq__(self, other):",
"if not isinstance(fixed_size, int): raise TypeError( \"fixed size should be None or int,",
"Currency): return self.__ge__(Currency(other)) return self.value.__ge__(other.value) @staticmethod def _op_other_as_currency(other): if isinstance(other, (int, str)): other",
"obj = None return cls(value=obj) def __str__(self): s = super().__str__() if jsstr.isempty(s): return",
"encoded string when part of a JSON object\") if obj == '': obj",
"self._fixed_size = fixed_size else: self._fixed_size = None # for now use no fixed",
"of type {} is not supported\".format(type(other))) return other # allow our currency to",
"this block stake (==Currency) according to the Sia Binary Encoding format. \"\"\" b",
"isinstance(other, Currency): return self.__mul__(Currency(other)) return Currency(self.value.__mul__(other.value).to_nearest(9)) def __rmul__(self, other): return self.__mul__(other) def __imul__(self,",
"if obj == '': obj = None return cls(value=obj) @property def value(self): return",
"None or int, not be of type {}\".format(type(fixed_size))) if fixed_size < 0: raise",
"according to the Rivine Binary Encoding format. Either encoded as a slice or",
"s = super().__str__() if jsstr.isempty(s): return jsstr.repeat('0', Hash.SIZE*2) return s class Currency(BaseDataTypeClass): \"\"\"",
"isinstance(other, Currency): return self.__lt__(Currency(other)) return self.value.__lt__(other.value) def __le__(self, other): if not isinstance(other, Currency):",
"self # operator overloading to allow currencies to be divided def __truediv__(self, other):",
"to the Rivine Binary Encoding format. \"\"\" b = self.bytes() encoder.add_slice(b) class Blockstake(BaseDataTypeClass):",
"None self.value = value @classmethod def sum(cls, *values): s = cls() for value",
"self.value.__eq__(other.value) def __ne__(self, other): if not isinstance(other, Currency): return self.__ne__(Currency(other)) return self.value.__ne__(other.value) def",
"Hash(BinaryData): SIZE = 32 \"\"\" TFChain Hash Object, a special type of BinaryData",
"return cls(value=obj) @property def value(self): return self._value @value.setter def value(self, value): value._value =",
"json(self): return self.__str__() def __eq__(self, other): other = self._op_other_as_binary_data(other) return self.value == other.value",
"self.value.__lt__(other.value) def __le__(self, other): if not isinstance(other, Currency): return self.__le__(Currency(other)) return self.value.__le__(other.value) def",
"binary length of the value self._fixed_size = len(self.value) @classmethod def from_json(cls, obj, fixed_size=None,",
"return jsstr.to_int(self.str(lowest_unit=True)) def bytes(self): return self.value.bytes(prec=9) def __str__(self): return self.str() def str(self, with_unit=False,",
"TypeError( \"binary data can only be set to a BinaryData, str, bytes or",
"s: jsbase64.bytes_from_b64(s) self._to_str = lambda value: jsbase64.bytes_to_b64(value) elif jsstr.String(strencoding).lower().strip().__eq__('hexprefix'): self._from_str = lambda s:",
"currencies to be compared def __lt__(self, other): if not isinstance(other, Currency): return self.__lt__(Currency(other))",
"\"\"\" BinaryData is the data type used for any binary data used in",
"def rivine_binary_encode(self, encoder): \"\"\" Encode this binary data according to the Rivine Binary",
"= bytes(jsarray.new_array(self._fixed_size)) else: value = bytes(jsarray.new_array(0)) elif isinstance(value, str): value = self._from_str(value) elif",
"{}\".format(type(value))) # if fixed size, check this now lvalue = len(value) if self._fixed_size",
"def times(self, other): return self.__mul__(other) def divided_by(self, other): return self.__truediv__(other) def equal_to(self, other):",
"json(self): return self.__str__() def bytes(self): return self.value.bytes() def sia_binary_encode(self, encoder): \"\"\" Encode this",
"s class Currency(BaseDataTypeClass): \"\"\" TFChain Currency Object. \"\"\" def __init__(self, value=None): self._value =",
"import tfchain.errors as tferrors import tfchain.polyfill.encoding.base64 as jsbase64 import tfchain.polyfill.encoding.hex as jshex import",
"to be summed def __add__(self, other): if not isinstance(other, Currency): return self.__add__(Currency(other)) return",
"not isinstance(obj, str): raise TypeError( \"binary data is expected to be an encoded",
"a string , not type {}\".format(type(obj))) if obj == '': obj = None",
"data according to the Sia Binary Encoding format. Either encoded as a slice",
"s.startswith(\"0X\")) else s) self._to_str = lambda value: '0x' + jshex.bytes_to_hex(value) else: raise TypeError(",
"raise TypeError( \"Cannot compare binary data with different fixed size: self({}) != other({})\".format(",
"the value if isinstance(value, BinaryData): value = value.value elif value == None: if",
"str): raise TypeError( \"hash is expected to be an encoded string when part",
"jsstr.from_int(self.__int__()) def __str__(self): return self.str() def __repr__(self): return self.__str__() def json(self): return self.__str__()",
"s = self.value.str(precision) if lowest_unit: s = jsstr.lstrip(jsstr.replace(s, \".\", \"\"), \"0\") elif jsstr.contains(s,",
"{} is not allowed\".format( self._fixed_size, len(value))) # all good, assign the bytearray value",
"TFT\" return s def __repr__(self): return self.str(with_unit=True) def json(self): return self.str(lowest_unit=True) def sia_binary_encode(self,",
"divided def __truediv__(self, other): if not isinstance(other, Currency): return self.__truediv__(Currency(other)) return Currency(self.value.__truediv__(other.value).to_nearest(9)) #",
"and not isinstance(strencoding, str): raise TypeError( \"strencoding should be None or a str,",
"def plus(self, other): return self.__add__(other) def minus(self, other): return self.__sub__(other) def times(self, other):",
"@classmethod def sum(cls, *values): s = cls() for value in values: s.__iadd__(value) return",
"Currency(value=other) elif isinstance(other, float): other = Currency(value=jsdec.Decimal(str(other))) elif not isinstance(other, Currency): raise TypeError(",
"for value in values: s.__iadd__(value) return s @classmethod def from_str(cls, obj, lowest_unit=False): if",
"raise tferrors.CurrencyPrecisionOverflow(d.__str__()) # if sign != 0: # allow negative values for intermediate",
"sign != 0: # allow negative values for intermediate computations # raise tferrors.CurrencyNegativeValue(d.__str__())",
"if not isinstance(other, Currency): return self.__le__(Currency(other)) return self.value.__le__(other.value) def __eq__(self, other): if not",
"\"\"\" Encode this binary data according to the Sia Binary Encoding format. Either",
"when part of a JSON object, not type {}\".format(type(obj))) if obj == '':",
"TypeError( \"Cannot compare binary data with different strencoding: self({}) != other({})\".format( self._strencoding, other._strencoding))",
"least 0, {} is not allowed\".format(fixed_size)) if fixed_size != 0: self._fixed_size = fixed_size",
"\"\"\" def __init__(self, value=None): self._value = None self.value = value @classmethod def sum(cls,",
"return raise TypeError( \"cannot set value of type {} as Currency (invalid type):",
"# allow our currency to be turned into an int def __int__(self): return",
"value == None: if self._fixed_size != None: value = bytes(jsarray.new_array(self._fixed_size)) else: value =",
"def bytes(self): return self.value.bytes() def sia_binary_encode(self, encoder): \"\"\" Encode this block stake (==Currency)",
"intermediate computations # raise tferrors.CurrencyNegativeValue(d.__str__()) self._value = d return raise TypeError( \"cannot set",
"size now, if the fixed_size was 0 # based on the binary length",
"encoder): \"\"\" Encode this currency according to the Rivine Binary Encoding format. \"\"\"",
"value(self, value): value._value = Currency(value=value) # allow our block stake to be turned",
"int, not be of type {}\".format(type(fixed_size))) if fixed_size < 0: raise TypeError( \"fixed",
"str): raise TypeError( \"strencoding should be None or a str, not be of",
"return Currency(self.value.__add__(other.value)) def __radd__(self, other): return self.__add__(other) def __iadd__(self, other): if not isinstance(other,",
"== '': obj = None c = cls() c.value = jsdec.Decimal(obj) if lowest_unit:",
"\"\"\" def __init__(self, value=None): super().__init__(value, fixed_size=Hash.SIZE, strencoding='hex') @classmethod def from_json(cls, obj): if obj",
"self._from_str = lambda s: jshex.bytes_from_hex(s) self._to_str = lambda value: jshex.bytes_to_hex(value) elif jsstr.String(strencoding).lower().strip().__eq__('base64'): self._from_str",
"= jsdec.Decimal() return if isinstance(value, Currency): self._value = value.value return if isinstance(value, (int,",
"super().__init__(value, fixed_size=Hash.SIZE, strencoding='hex') @classmethod def from_json(cls, obj): if obj != None and not",
"d = jsdec.Decimal(inner_value) _, _, exp = d.as_tuple() # sign is first return",
"value if isinstance(inner_value, str): inner_value = jsstr.String(inner_value).upper().strip().value if len(inner_value) >= 4 and inner_value[-3:]",
"different strencoding: self({}) != other({})\".format( self._strencoding, other._strencoding)) return other def __hash__(self): return hash(self.__str__())",
"of a JSON object, not type {}\".format(type(obj))) if obj == '': obj =",
"type {} as Currency (invalid type): {}\".format(type(value), value)) # operator overloading to allow",
"str): raise TypeError( \"binary data is expected to be an encoded string when",
"if obj != None and not isinstance(obj, str): raise TypeError( \"block stake is",
"return self._value def plus(self, other): return self.__add__(other) def minus(self, other): return self.__sub__(other) def",
"return s @classmethod def from_str(cls, obj, lowest_unit=False): if obj != None and not",
"elif jsstr.contains(s, \".\"): s = jsstr.rstrip(jsstr.rstrip(s, \"0 \"), '.') if jsstr.isempty(s): s =",
"__str__(self): s = super().__str__() if jsstr.isempty(s): return jsstr.repeat('0', Hash.SIZE*2) return s class Currency(BaseDataTypeClass):",
"'TFT': inner_value = jsstr.rstrip(inner_value[:-3]) d = jsdec.Decimal(inner_value) _, _, exp = d.as_tuple() #",
"\"Cannot compare binary data with different strencoding: self({}) != other({})\".format( self._strencoding, other._strencoding)) return",
"self.__str__() def bytes(self): return self.value.bytes() def sia_binary_encode(self, encoder): \"\"\" Encode this block stake",
"= value @classmethod def sum(cls, *values): s = cls() for value in values:",
"\"0\") elif jsstr.contains(s, \".\"): s = jsstr.rstrip(jsstr.rstrip(s, \"0 \"), '.') if jsstr.isempty(s): s",
"size should be None or int, not be of type {}\".format(type(fixed_size))) if fixed_size",
"self.__add__(Currency(other)) return Currency(self.value.__add__(other.value)) def __radd__(self, other): return self.__add__(other) def __iadd__(self, other): if not",
"value)) # operator overloading to allow currencies to be summed def __add__(self, other):",
"other): if isinstance(other, (str, bytes, bytearray)): other = BinaryData( value=other, fixed_size=self._fixed_size, strencoding=self._strencoding) elif",
"None and not isinstance(obj, str): raise TypeError( \"binary data is expected to be",
"s.__iadd__(value) return s @classmethod def from_str(cls, obj, lowest_unit=False): if obj != None and",
"a string when part of a JSON object, not type {}\".format(type(obj))) if obj",
"strencoding: self({}) != other({})\".format( self._strencoding, other._strencoding)) return other def __hash__(self): return hash(self.__str__()) def",
"\"currency is expected to be a string , not type {}\".format(type(obj))) if obj",
"to a BinaryData, str, bytes or bytearray, not {}\".format(type(value))) # if fixed size,",
"self.__sub__(other) def times(self, other): return self.__mul__(other) def divided_by(self, other): return self.__truediv__(other) def equal_to(self,",
"__rmul__(self, other): return self.__mul__(other) def __imul__(self, other): if not isinstance(other, Currency): return self.__imul__(Currency(other))",
"def negate(self): return Currency(self.value.negate()) @value.setter def value(self, value): if value == None: self._value",
"isinstance(strencoding, str): raise TypeError( \"strencoding should be None or a str, not be",
"is fixed sized. \"\"\" if self._fixed_size == None: encoder.add_slice(self._value) else: encoder.add_array(self._value) class Hash(BinaryData):",
"if obj == '': obj = None return cls(value=obj) def __str__(self): s =",
"normalize the value if isinstance(value, BinaryData): value = value.value elif value == None:",
"encoder.add_slice(self._value) else: encoder.add_array(self._value) def rivine_binary_encode(self, encoder): \"\"\" Encode this binary data according to",
"= value.value elif value == None: if self._fixed_size != None: value = bytes(jsarray.new_array(self._fixed_size))",
"self.str(with_unit=True) def json(self): return self.str(lowest_unit=True) def sia_binary_encode(self, encoder): \"\"\" Encode this currency according",
"def sia_binary_encode(self, encoder): \"\"\" Encode this binary data according to the Sia Binary",
"Encode this currency according to the Rivine Binary Encoding format. \"\"\" b =",
"other): if not isinstance(other, Currency): return self.__ne__(Currency(other)) return self.value.__ne__(other.value) def __gt__(self, other): if",
"other = BinaryData( value=other, fixed_size=self._fixed_size, strencoding=self._strencoding) elif not isinstance(other, BinaryData): raise TypeError( \"Binary",
"return self.__gt__(other) def less_than_or_equal_to(self, other): return self.__le__(other) def greater_than_or_equal_to(self, other): return self.__ge__(other) def",
"!= 0 and lvalue != self._fixed_size: raise ValueError( \"binary data was expected to",
"if obj != None and not isinstance(obj, str): raise TypeError( \"currency is expected",
"an encoded string when part of a JSON object\") if obj == '':",
"b = self.bytes() encoder.add_int(len(b)) encoder.add_array(b) def rivine_binary_encode(self, encoder): \"\"\" Encode this block stake",
"Blockstake(BaseDataTypeClass): \"\"\" TFChain Blockstake Object. \"\"\" def __init__(self, value=None): self._value = Currency(value) @classmethod",
"BinaryData is the data type used for any binary data used in tfchain.",
"as tferrors import tfchain.polyfill.encoding.base64 as jsbase64 import tfchain.polyfill.encoding.hex as jshex import tfchain.polyfill.encoding.str as",
"def sia_binary_encode(self, encoder): \"\"\" Encode this currency according to the Sia Binary Encoding",
"other): if not isinstance(other, Currency): return self.__le__(Currency(other)) return self.value.__le__(other.value) def __eq__(self, other): if",
"check this now lvalue = len(value) if self._fixed_size != None and lvalue !=",
"self.value.str(precision) if lowest_unit: s = jsstr.lstrip(jsstr.replace(s, \".\", \"\"), \"0\") elif jsstr.contains(s, \".\"): s",
"if fixed size, check this now lvalue = len(value) if self._fixed_size != None",
"a str TFT unit-based value, optionally with the currency notation. @param with_unit: include",
"value.value return if isinstance(value, (int, str, jsdec.Decimal)): inner_value = value if isinstance(inner_value, str):",
"def equal_to(self, other): return self.__eq__(other) def not_equal_to(self, other): return self.__ne__(other) def less_than(self, other):",
"{} as Currency (invalid type): {}\".format(type(value), value)) # operator overloading to allow currencies",
"self.str(lowest_unit=True) def sia_binary_encode(self, encoder): \"\"\" Encode this currency according to the Sia Binary",
"Currency (invalid type): {}\".format(type(value), value)) # operator overloading to allow currencies to be",
"fixed size if fixed_size != None: if not isinstance(fixed_size, int): raise TypeError( \"fixed",
"0: # allow negative values for intermediate computations # raise tferrors.CurrencyNegativeValue(d.__str__()) self._value =",
"def __sub__(self, other): if not isinstance(other, Currency): return self.__sub__(Currency(other)) return Currency(self.value.__sub__(other.value)) def __rsub__(self,",
"return self.value.__lt__(other.value) def __le__(self, other): if not isinstance(other, Currency): return self.__le__(Currency(other)) return self.value.__le__(other.value)",
"currency according to the Rivine Binary Encoding format. \"\"\" b = self.bytes() encoder.add_slice(b)",
"lvalue != self._fixed_size: raise ValueError( \"binary data was expected to be of fixed",
"value(self, value): if value == None: self._value = jsdec.Decimal() return if isinstance(value, Currency):",
"import BaseDataTypeClass class BinaryData(BaseDataTypeClass): \"\"\" BinaryData is the data type used for any",
"0: self._fixed_size = fixed_size else: self._fixed_size = None # for now use no",
"return value if exp < -9: raise tferrors.CurrencyPrecisionOverflow(d.__str__()) # if sign != 0:",
"not isinstance(other, Currency): return self.__sub__(Currency(other)) return Currency(self.value.__sub__(other.value)) def __rsub__(self, other): return self.__sub__(other) def",
"elif not isinstance(value, bytes) and not jsarray.is_uint8_array(value): raise TypeError( \"binary data can only",
"return self.__imul__(Currency(other)) self._value.__imul__(other.value) return self # operator overloading to allow currencies to be",
"(==Currency) according to the Rivine Binary Encoding format. \"\"\" b = self.bytes() encoder.add_slice(b)",
"return jsstr.to_int(self.value.str(lowest_unit=False)) def str(self): return jsstr.from_int(self.__int__()) def __str__(self): return self.str() def __repr__(self): return",
"of type {} is not supported\".format(type(other))) if self._fixed_size != other._fixed_size: raise TypeError( \"Cannot",
"array, depending on whether or not it is fixed sized. \"\"\" if self._fixed_size",
"whether or not it is fixed sized. \"\"\" if self._fixed_size == None: encoder.add_slice(self._value)",
"= strencoding # define fixed size if fixed_size != None: if not isinstance(fixed_size,",
"on the binary length of the value self._fixed_size = len(self.value) @classmethod def from_json(cls,",
"jsarray from tfchain.types.BaseDataType import BaseDataTypeClass class BinaryData(BaseDataTypeClass): \"\"\" BinaryData is the data type",
"self._op_other_as_binary_data(other) return self.value == other.value def __ne__(self, other): other = self._op_other_as_binary_data(other) return self.value",
"return Currency(self.value.negate()) @value.setter def value(self, value): if value == None: self._value = jsdec.Decimal()",
"s = cls() for value in values: s.__iadd__(value) return s @classmethod def from_str(cls,",
"def __eq__(self, other): if not isinstance(other, Currency): return self.__eq__(Currency(other)) return self.value.__eq__(other.value) def __ne__(self,",
"data type used for any binary data used in tfchain. \"\"\" def __init__(self,",
"= self.bytes() encoder.add_slice(b) class Blockstake(BaseDataTypeClass): \"\"\" TFChain Blockstake Object. \"\"\" def __init__(self, value=None):",
"strencoding # define fixed size if fixed_size != None: if not isinstance(fixed_size, int):",
"as jshex import tfchain.polyfill.encoding.str as jsstr import tfchain.polyfill.encoding.decimal as jsdec import tfchain.polyfill.array as",
"return self.__ne__(other) def less_than(self, other): return self.__lt__(other) def greater_than(self, other): return self.__gt__(other) def",
"to allow currencies to be divided def __truediv__(self, other): if not isinstance(other, Currency):",
"{}\".format(strencoding)) if strencoding == None or jsstr.String(strencoding).lower().strip().__eq__('hex'): self._from_str = lambda s: jshex.bytes_from_hex(s) self._to_str",
"self._value @value.setter def value(self, value): # normalize the value if isinstance(value, BinaryData): value",
"an encoded string when part of a JSON object, not {}\".format(type(obj))) if obj",
"def __radd__(self, other): return self.__add__(other) def __iadd__(self, other): if not isinstance(other, Currency): return",
"raise TypeError( \"Cannot compare binary data with different strencoding: self({}) != other({})\".format( self._strencoding,",
"= self.value.str(precision) if lowest_unit: s = jsstr.lstrip(jsstr.replace(s, \".\", \"\"), \"0\") elif jsstr.contains(s, \".\"):",
"to be a string , not type {}\".format(type(obj))) if obj == '': obj",
"other): other = self._op_other_as_binary_data(other) return self.value == other.value def __ne__(self, other): other =",
"def _op_other_as_binary_data(self, other): if isinstance(other, (str, bytes, bytearray)): other = BinaryData( value=other, fixed_size=self._fixed_size,",
"obj = None return cls(value=obj) @property def value(self): return self._value @value.setter def value(self,",
"return s def __repr__(self): return self.str(with_unit=True) def json(self): return self.str(lowest_unit=True) def sia_binary_encode(self, encoder):",
"binary data with different fixed size: self({}) != other({})\".format( self._fixed_size, other._fixed_size)) if self._strencoding",
"fixed sized. \"\"\" if self._fixed_size == None: encoder.add_slice(self._value) else: encoder.add_array(self._value) class Hash(BinaryData): SIZE",
"= self.bytes() encoder.add_int(len(b)) encoder.add_array(b) def rivine_binary_encode(self, encoder): \"\"\" Encode this block stake (==Currency)",
"TypeError( \"{} is not a valid string encoding\".format(strencoding)) self._strencoding = strencoding # define",
"= value if fixed_size == 0: # define the fixed size now, if",
"other({})\".format( self._fixed_size, other._fixed_size)) if self._strencoding != other._strencoding: raise TypeError( \"Cannot compare binary data",
"jsstr.rstrip(inner_value[:-3]) d = jsdec.Decimal(inner_value) _, _, exp = d.as_tuple() # sign is first",
"jsdec.Decimal(obj) if lowest_unit: c.value.__imul__(jsdec.Decimal('0.000000001')) return c @classmethod def from_json(_, obj): return Currency.from_str(obj, lowest_unit=True)",
"now use no fixed size # define the value (finally) self._value = None",
"supported\".format(type(other))) return other # allow our currency to be turned into an int",
"value in values: s.__iadd__(value) return s @classmethod def from_str(cls, obj, lowest_unit=False): if obj",
"{}\".format(type(value), value)) # operator overloading to allow currencies to be summed def __add__(self,",
"encoded as a slice or an array, depending on whether or not it",
"hash(self.__str__()) def sia_binary_encode(self, encoder): \"\"\" Encode this binary data according to the Sia",
"in values: s.__iadd__(value) return s @classmethod def from_str(cls, obj, lowest_unit=False): if obj !=",
"return self.value.bytes() def sia_binary_encode(self, encoder): \"\"\" Encode this block stake (==Currency) according to",
"return self.__eq__(other) def not_equal_to(self, other): return self.__ne__(other) def less_than(self, other): return self.__lt__(other) def",
"encoding if strencoding != None and not isinstance(strencoding, str): raise TypeError( \"strencoding should",
"strencoding != None and not isinstance(strencoding, str): raise TypeError( \"strencoding should be None",
"strencoding == None or jsstr.String(strencoding).lower().strip().__eq__('hex'): self._from_str = lambda s: jshex.bytes_from_hex(s) self._to_str = lambda",
"to be turned into an int def __int__(self): return jsstr.to_int(self.value.str(lowest_unit=False)) def str(self): return",
"be of fixed size {}, length {} is not allowed\".format( self._fixed_size, len(value))) #",
"any binary data used in tfchain. \"\"\" def __init__(self, value=None, fixed_size=None, strencoding=None): #",
"the Rivine Binary Encoding format. Either encoded as a slice or an array,",
"as jsdec import tfchain.polyfill.array as jsarray from tfchain.types.BaseDataType import BaseDataTypeClass class BinaryData(BaseDataTypeClass): \"\"\"",
"isinstance(value, (int, str, jsdec.Decimal)): inner_value = value if isinstance(inner_value, str): inner_value = jsstr.String(inner_value).upper().strip().value",
"Currency): return self.__iadd__(Currency(other)) self._value.__iadd__(other.value) return self # operator overloading to allow currencies to",
"can only be set to a BinaryData, str, bytes or bytearray, not {}\".format(type(value)))",
"data according to the Rivine Binary Encoding format. Either encoded as a slice",
"data used in tfchain. \"\"\" def __init__(self, value=None, fixed_size=None, strencoding=None): # define string",
"isinstance(value, Currency): self._value = value.value return if isinstance(value, (int, str, jsdec.Decimal)): inner_value =",
"according to the Sia Binary Encoding format. Either encoded as a slice or",
"to allow currencies to be subtracted def __sub__(self, other): if not isinstance(other, Currency):",
"= len(value) if self._fixed_size != None and lvalue != 0 and lvalue !=",
"import tfchain.polyfill.encoding.base64 as jsbase64 import tfchain.polyfill.encoding.hex as jshex import tfchain.polyfill.encoding.str as jsstr import",
"is fixed sized. \"\"\" if self._fixed_size == None: encoder.add_slice(self._value) else: encoder.add_array(self._value) def rivine_binary_encode(self,",
"return c @classmethod def from_json(_, obj): return Currency.from_str(obj, lowest_unit=True) @property def value(self): return",
"= None return cls(value=obj) @property def value(self): return self._value @value.setter def value(self, value):",
"value.value elif value == None: if self._fixed_size != None: value = bytes(jsarray.new_array(self._fixed_size)) else:",
"if sign != 0: # allow negative values for intermediate computations # raise",
"assign the bytearray value self._value = value def __len__(self): return len(self.value) def __str__(self):",
"the value (finally) self._value = None self.value = value if fixed_size == 0:",
"__add__(self, other): if not isinstance(other, Currency): return self.__add__(Currency(other)) return Currency(self.value.__add__(other.value)) def __radd__(self, other):",
"return self.__str__() def json(self): return self.__str__() def __eq__(self, other): other = self._op_other_as_binary_data(other) return",
"allow currencies to be subtracted def __sub__(self, other): if not isinstance(other, Currency): return",
"self.__sub__(other) def __isub__(self, other): if not isinstance(other, Currency): return self.__isub__(Currency(other)) self._value.__isub__(other.value) return self",
"!= other({})\".format( self._fixed_size, other._fixed_size)) if self._strencoding != other._strencoding: raise TypeError( \"Cannot compare binary",
"Currency): return self.__lt__(Currency(other)) return self.value.__lt__(other.value) def __le__(self, other): if not isinstance(other, Currency): return",
"self.__ne__(other) def less_than(self, other): return self.__lt__(other) def greater_than(self, other): return self.__gt__(other) def less_than_or_equal_to(self,"
] |
[
"in range(len(labels)): if labels[i] == 1: positive.append(X[i]) else: negative.append(X[i]) positive = np.array(positive) negative",
"self.dim = dim self.matrixTransf = None def fit_transform(self, X, labels): positive = []",
"sub) self.matrixTransf = np.array(wLDA) print(\"Matriz de transformação\") print(self.matrixTransf) res = np.matmul(X, self.matrixTransf.T) return",
"from numpy import linalg as LA class LDA(): def __init__(self, dim = 2):",
"cov_pos = np.cov(positive.T) cov_neg = np.cov(negative.T) SW = cov_pos + cov_neg sub =",
"negative = [] for i in range(len(labels)): if labels[i] == 1: positive.append(X[i]) else:",
"= np.array(negative) media_pos = np.mean(positive, axis = 0) media_neg = np.mean(negative, axis =",
"self.matrixTransf = None def fit_transform(self, X, labels): positive = [] negative = []",
"(media_pos - media_neg) print(SW.shape) print(sub.shape) wLDA = np.matmul(LA.pinv(SW), sub) self.matrixTransf = np.array(wLDA) print(\"Matriz",
"np.array(positive) negative = np.array(negative) media_pos = np.mean(positive, axis = 0) media_neg = np.mean(negative,",
"= 0) cov_pos = np.cov(positive.T) cov_neg = np.cov(negative.T) SW = cov_pos + cov_neg",
"negative.append(X[i]) positive = np.array(positive) negative = np.array(negative) media_pos = np.mean(positive, axis = 0)",
"= 0) media_neg = np.mean(negative, axis = 0) cov_pos = np.cov(positive.T) cov_neg =",
"else: negative.append(X[i]) positive = np.array(positive) negative = np.array(negative) media_pos = np.mean(positive, axis =",
"wLDA = np.matmul(LA.pinv(SW), sub) self.matrixTransf = np.array(wLDA) print(\"Matriz de transformação\") print(self.matrixTransf) res =",
"== 1: positive.append(X[i]) else: negative.append(X[i]) positive = np.array(positive) negative = np.array(negative) media_pos =",
"- media_neg) print(SW.shape) print(sub.shape) wLDA = np.matmul(LA.pinv(SW), sub) self.matrixTransf = np.array(wLDA) print(\"Matriz de",
"np.mean(negative, axis = 0) cov_pos = np.cov(positive.T) cov_neg = np.cov(negative.T) SW = cov_pos",
"__init__(self, dim = 2): self.dim = dim self.matrixTransf = None def fit_transform(self, X,",
"if labels[i] == 1: positive.append(X[i]) else: negative.append(X[i]) positive = np.array(positive) negative = np.array(negative)",
"def fit_transform(self, X, labels): positive = [] negative = [] for i in",
"dim = 2): self.dim = dim self.matrixTransf = None def fit_transform(self, X, labels):",
"range(len(labels)): if labels[i] == 1: positive.append(X[i]) else: negative.append(X[i]) positive = np.array(positive) negative =",
"= np.mean(negative, axis = 0) cov_pos = np.cov(positive.T) cov_neg = np.cov(negative.T) SW =",
"= dim self.matrixTransf = None def fit_transform(self, X, labels): positive = [] negative",
"as np from numpy import linalg as LA class LDA(): def __init__(self, dim",
"np from numpy import linalg as LA class LDA(): def __init__(self, dim =",
"dim self.matrixTransf = None def fit_transform(self, X, labels): positive = [] negative =",
"= np.matmul(LA.pinv(SW), sub) self.matrixTransf = np.array(wLDA) print(\"Matriz de transformação\") print(self.matrixTransf) res = np.matmul(X,",
"None def fit_transform(self, X, labels): positive = [] negative = [] for i",
"[] negative = [] for i in range(len(labels)): if labels[i] == 1: positive.append(X[i])",
"linalg as LA class LDA(): def __init__(self, dim = 2): self.dim = dim",
"= np.mean(positive, axis = 0) media_neg = np.mean(negative, axis = 0) cov_pos =",
"sub = (media_pos - media_neg) print(SW.shape) print(sub.shape) wLDA = np.matmul(LA.pinv(SW), sub) self.matrixTransf =",
"import numpy as np from numpy import linalg as LA class LDA(): def",
"= [] for i in range(len(labels)): if labels[i] == 1: positive.append(X[i]) else: negative.append(X[i])",
"[] for i in range(len(labels)): if labels[i] == 1: positive.append(X[i]) else: negative.append(X[i]) positive",
"axis = 0) media_neg = np.mean(negative, axis = 0) cov_pos = np.cov(positive.T) cov_neg",
"labels): positive = [] negative = [] for i in range(len(labels)): if labels[i]",
"= (media_pos - media_neg) print(SW.shape) print(sub.shape) wLDA = np.matmul(LA.pinv(SW), sub) self.matrixTransf = np.array(wLDA)",
"as LA class LDA(): def __init__(self, dim = 2): self.dim = dim self.matrixTransf",
"class LDA(): def __init__(self, dim = 2): self.dim = dim self.matrixTransf = None",
"def __init__(self, dim = 2): self.dim = dim self.matrixTransf = None def fit_transform(self,",
"labels[i] == 1: positive.append(X[i]) else: negative.append(X[i]) positive = np.array(positive) negative = np.array(negative) media_pos",
"import linalg as LA class LDA(): def __init__(self, dim = 2): self.dim =",
"X, labels): positive = [] negative = [] for i in range(len(labels)): if",
"np.array(negative) media_pos = np.mean(positive, axis = 0) media_neg = np.mean(negative, axis = 0)",
"numpy as np from numpy import linalg as LA class LDA(): def __init__(self,",
"np.matmul(LA.pinv(SW), sub) self.matrixTransf = np.array(wLDA) print(\"Matriz de transformação\") print(self.matrixTransf) res = np.matmul(X, self.matrixTransf.T)",
"negative = np.array(negative) media_pos = np.mean(positive, axis = 0) media_neg = np.mean(negative, axis",
"axis = 0) cov_pos = np.cov(positive.T) cov_neg = np.cov(negative.T) SW = cov_pos +",
"0) media_neg = np.mean(negative, axis = 0) cov_pos = np.cov(positive.T) cov_neg = np.cov(negative.T)",
"2): self.dim = dim self.matrixTransf = None def fit_transform(self, X, labels): positive =",
"positive = np.array(positive) negative = np.array(negative) media_pos = np.mean(positive, axis = 0) media_neg",
"= cov_pos + cov_neg sub = (media_pos - media_neg) print(SW.shape) print(sub.shape) wLDA =",
"LDA(): def __init__(self, dim = 2): self.dim = dim self.matrixTransf = None def",
"positive.append(X[i]) else: negative.append(X[i]) positive = np.array(positive) negative = np.array(negative) media_pos = np.mean(positive, axis",
"i in range(len(labels)): if labels[i] == 1: positive.append(X[i]) else: negative.append(X[i]) positive = np.array(positive)",
"media_neg = np.mean(negative, axis = 0) cov_pos = np.cov(positive.T) cov_neg = np.cov(negative.T) SW",
"= 2): self.dim = dim self.matrixTransf = None def fit_transform(self, X, labels): positive",
"media_neg) print(SW.shape) print(sub.shape) wLDA = np.matmul(LA.pinv(SW), sub) self.matrixTransf = np.array(wLDA) print(\"Matriz de transformação\")",
"print(sub.shape) wLDA = np.matmul(LA.pinv(SW), sub) self.matrixTransf = np.array(wLDA) print(\"Matriz de transformação\") print(self.matrixTransf) res",
"print(SW.shape) print(sub.shape) wLDA = np.matmul(LA.pinv(SW), sub) self.matrixTransf = np.array(wLDA) print(\"Matriz de transformação\") print(self.matrixTransf)",
"numpy import linalg as LA class LDA(): def __init__(self, dim = 2): self.dim",
"self.matrixTransf = np.array(wLDA) print(\"Matriz de transformação\") print(self.matrixTransf) res = np.matmul(X, self.matrixTransf.T) return res",
"= [] negative = [] for i in range(len(labels)): if labels[i] == 1:",
"for i in range(len(labels)): if labels[i] == 1: positive.append(X[i]) else: negative.append(X[i]) positive =",
"media_pos = np.mean(positive, axis = 0) media_neg = np.mean(negative, axis = 0) cov_pos",
"+ cov_neg sub = (media_pos - media_neg) print(SW.shape) print(sub.shape) wLDA = np.matmul(LA.pinv(SW), sub)",
"= np.cov(positive.T) cov_neg = np.cov(negative.T) SW = cov_pos + cov_neg sub = (media_pos",
"np.cov(negative.T) SW = cov_pos + cov_neg sub = (media_pos - media_neg) print(SW.shape) print(sub.shape)",
"1: positive.append(X[i]) else: negative.append(X[i]) positive = np.array(positive) negative = np.array(negative) media_pos = np.mean(positive,",
"cov_neg sub = (media_pos - media_neg) print(SW.shape) print(sub.shape) wLDA = np.matmul(LA.pinv(SW), sub) self.matrixTransf",
"LA class LDA(): def __init__(self, dim = 2): self.dim = dim self.matrixTransf =",
"cov_neg = np.cov(negative.T) SW = cov_pos + cov_neg sub = (media_pos - media_neg)",
"positive = [] negative = [] for i in range(len(labels)): if labels[i] ==",
"cov_pos + cov_neg sub = (media_pos - media_neg) print(SW.shape) print(sub.shape) wLDA = np.matmul(LA.pinv(SW),",
"np.mean(positive, axis = 0) media_neg = np.mean(negative, axis = 0) cov_pos = np.cov(positive.T)",
"= np.cov(negative.T) SW = cov_pos + cov_neg sub = (media_pos - media_neg) print(SW.shape)",
"= np.array(positive) negative = np.array(negative) media_pos = np.mean(positive, axis = 0) media_neg =",
"= None def fit_transform(self, X, labels): positive = [] negative = [] for",
"fit_transform(self, X, labels): positive = [] negative = [] for i in range(len(labels)):",
"SW = cov_pos + cov_neg sub = (media_pos - media_neg) print(SW.shape) print(sub.shape) wLDA",
"0) cov_pos = np.cov(positive.T) cov_neg = np.cov(negative.T) SW = cov_pos + cov_neg sub",
"np.cov(positive.T) cov_neg = np.cov(negative.T) SW = cov_pos + cov_neg sub = (media_pos -"
] |
[
"__license__ = 'MIT' from tweepy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory,",
"from tweepy.limit import RateLimitHandler from tweepy.streaming import Stream, StreamListener from tweepy.cursor import Cursor",
"debug(enable=True, level=1): from six.moves.http_client import HTTPConnection HTTPConnection.debuglevel = level def chunks(l, n): for",
"Copyright 2009-2010 <NAME> # See LICENSE for details. \"\"\" Tweepy Twitter API library",
"for i in xrange(0, len(l), n): yield l[i:i+n] class Twitter(object): \"\"\" Twitter API",
"LICENSE for details. \"\"\" Tweepy Twitter API library \"\"\" __version__ = '3.5.0' __author__",
"tweepy.streaming import Stream, StreamListener from tweepy.cursor import Cursor # Global, unauthenticated instance of",
"n): for i in xrange(0, len(l), n): yield l[i:i+n] class Twitter(object): \"\"\" Twitter",
"and splits input param lists in chunks if neccessary. \"\"\" def __init__(self, consumer_key,",
"Param `access_tokens` must be a dictionary but it can be loaded later just",
"API library \"\"\" __version__ = '3.5.0' __author__ = '<NAME>' __license__ = 'MIT' from",
"in xrange(0, len(l), n): yield l[i:i+n] class Twitter(object): \"\"\" Twitter API wrapper based",
"# wait_on_rate_limit=True, wait_on_rate_limit_notify=True @property def api(self): \"Lazy loaded Tweepy API object.\" if not",
"level def chunks(l, n): for i in xrange(0, len(l), n): yield l[i:i+n] class",
"def debug(enable=True, level=1): from six.moves.http_client import HTTPConnection HTTPConnection.debuglevel = level def chunks(l, n):",
"FileCache from tweepy.auth import OAuthHandler, AppAuthHandler from tweepy.limit import RateLimitHandler from tweepy.streaming import",
"%d' % len(auth.tokens) return API(auth) # retry_count=2, retry_delay=3, # wait_on_rate_limit=True, wait_on_rate_limit_notify=True @property def",
"method cursors and splits input param lists in chunks if neccessary. \"\"\" def",
"import Status, User, DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory, Category from tweepy.error import TweepError,",
"chunks if neccessary. \"\"\" def __init__(self, consumer_key, consumer_secret, access_tokens=None): \"\"\" Initialize params for",
"dictionary but it can be loaded later just before the first API method",
"`access_tokens` must be a dictionary but it can be loaded later just before",
"based on Tweepy using the RateLimitHandler with multiple access tokens (see https://github.com/svven/tweepy). It",
"secret in self.access_tokens.values(): auth.add_access_token(key, secret) # print 'Token pool size: %d' % len(auth.tokens)",
"OAuthHandler, AppAuthHandler from tweepy.limit import RateLimitHandler from tweepy.streaming import Stream, StreamListener from tweepy.cursor",
"import OAuthHandler, AppAuthHandler from tweepy.limit import RateLimitHandler from tweepy.streaming import Stream, StreamListener from",
"from six.moves.http_client import HTTPConnection HTTPConnection.debuglevel = level def chunks(l, n): for i in",
"print 'Token pool size: %d' % len(auth.tokens) return API(auth) # retry_count=2, retry_delay=3, #",
"RateLimitHandler with multiple access tokens (see https://github.com/svven/tweepy). It also handles API method cursors",
"API wrapper based on Tweepy using the RateLimitHandler with multiple access tokens (see",
"# Tweepy # Copyright 2009-2010 <NAME> # See LICENSE for details. \"\"\" Tweepy",
"import API from tweepy.cache import Cache, MemoryCache, FileCache from tweepy.auth import OAuthHandler, AppAuthHandler",
"self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.access_tokens = access_tokens _api = None def",
"from tweepy.auth import OAuthHandler, AppAuthHandler from tweepy.limit import RateLimitHandler from tweepy.streaming import Stream,",
"with RateLimitHandler auth.\" auth = RateLimitHandler(self.consumer_key, self.consumer_secret) for key, secret in self.access_tokens.values(): auth.add_access_token(key,",
"from tweepy.cursor import Cursor # Global, unauthenticated instance of API api = API()",
"\"\"\" self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.access_tokens = access_tokens _api = None",
"tweepy.auth import OAuthHandler, AppAuthHandler from tweepy.limit import RateLimitHandler from tweepy.streaming import Stream, StreamListener",
"len(auth.tokens) return API(auth) # retry_count=2, retry_delay=3, # wait_on_rate_limit=True, wait_on_rate_limit_notify=True @property def api(self): \"Lazy",
"\"\"\" Twitter API wrapper based on Tweepy using the RateLimitHandler with multiple access",
"neccessary. \"\"\" def __init__(self, consumer_key, consumer_secret, access_tokens=None): \"\"\" Initialize params for RateLimitHandler to",
"= None def _get_api(self): \"Initialize Tweepy API object with RateLimitHandler auth.\" auth =",
"def __init__(self, consumer_key, consumer_secret, access_tokens=None): \"\"\" Initialize params for RateLimitHandler to pass to",
"tweepy.error import TweepError, RateLimitError from tweepy.api import API from tweepy.cache import Cache, MemoryCache,",
"be loaded later just before the first API method call, and has to",
"from tweepy.streaming import Stream, StreamListener from tweepy.cursor import Cursor # Global, unauthenticated instance",
"Global, unauthenticated instance of API api = API() def debug(enable=True, level=1): from six.moves.http_client",
"_get_api(self): \"Initialize Tweepy API object with RateLimitHandler auth.\" auth = RateLimitHandler(self.consumer_key, self.consumer_secret) for",
"= consumer_key self.consumer_secret = consumer_secret self.access_tokens = access_tokens _api = None def _get_api(self):",
"\"\"\" __version__ = '3.5.0' __author__ = '<NAME>' __license__ = 'MIT' from tweepy.models import",
"RateLimitHandler auth.\" auth = RateLimitHandler(self.consumer_key, self.consumer_secret) for key, secret in self.access_tokens.values(): auth.add_access_token(key, secret)",
"Tweepy # Copyright 2009-2010 <NAME> # See LICENSE for details. \"\"\" Tweepy Twitter",
"def chunks(l, n): for i in xrange(0, len(l), n): yield l[i:i+n] class Twitter(object):",
"library \"\"\" __version__ = '3.5.0' __author__ = '<NAME>' __license__ = 'MIT' from tweepy.models",
"'Token pool size: %d' % len(auth.tokens) return API(auth) # retry_count=2, retry_delay=3, # wait_on_rate_limit=True,",
"retry_count=2, retry_delay=3, # wait_on_rate_limit=True, wait_on_rate_limit_notify=True @property def api(self): \"Lazy loaded Tweepy API object.\"",
"Twitter(object): \"\"\" Twitter API wrapper based on Tweepy using the RateLimitHandler with multiple",
"wrapper based on Tweepy using the RateLimitHandler with multiple access tokens (see https://github.com/svven/tweepy).",
"API(auth) # retry_count=2, retry_delay=3, # wait_on_rate_limit=True, wait_on_rate_limit_notify=True @property def api(self): \"Lazy loaded Tweepy",
"DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory, Category from tweepy.error import TweepError, RateLimitError from tweepy.api",
"API. Param `access_tokens` must be a dictionary but it can be loaded later",
"access_tokens _api = None def _get_api(self): \"Initialize Tweepy API object with RateLimitHandler auth.\"",
"len(l), n): yield l[i:i+n] class Twitter(object): \"\"\" Twitter API wrapper based on Tweepy",
"from tweepy.api import API from tweepy.cache import Cache, MemoryCache, FileCache from tweepy.auth import",
"API method cursors and splits input param lists in chunks if neccessary. \"\"\"",
"(access_token_key, access_token_secret)}. \"\"\" self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.access_tokens = access_tokens _api",
"\"\"\" Initialize params for RateLimitHandler to pass to Tweepy API. Param `access_tokens` must",
"object with RateLimitHandler auth.\" auth = RateLimitHandler(self.consumer_key, self.consumer_secret) for key, secret in self.access_tokens.values():",
"import RateLimitHandler from tweepy.streaming import Stream, StreamListener from tweepy.cursor import Cursor # Global,",
"i in xrange(0, len(l), n): yield l[i:i+n] class Twitter(object): \"\"\" Twitter API wrapper",
"consumer_key self.consumer_secret = consumer_secret self.access_tokens = access_tokens _api = None def _get_api(self): \"Initialize",
"a dictionary but it can be loaded later just before the first API",
"tweepy.api import API from tweepy.cache import Cache, MemoryCache, FileCache from tweepy.auth import OAuthHandler,",
"auth.\" auth = RateLimitHandler(self.consumer_key, self.consumer_secret) for key, secret in self.access_tokens.values(): auth.add_access_token(key, secret) #",
"wait_on_rate_limit=True, wait_on_rate_limit_notify=True @property def api(self): \"Lazy loaded Tweepy API object.\" if not self._api:",
"six.moves.http_client import HTTPConnection HTTPConnection.debuglevel = level def chunks(l, n): for i in xrange(0,",
"StreamListener from tweepy.cursor import Cursor # Global, unauthenticated instance of API api =",
"cursors and splits input param lists in chunks if neccessary. \"\"\" def __init__(self,",
"has to be like {user_id: (access_token_key, access_token_secret)}. \"\"\" self.consumer_key = consumer_key self.consumer_secret =",
"'MIT' from tweepy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory, Category from",
"l[i:i+n] class Twitter(object): \"\"\" Twitter API wrapper based on Tweepy using the RateLimitHandler",
"tweepy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory, Category from tweepy.error import",
"if neccessary. \"\"\" def __init__(self, consumer_key, consumer_secret, access_tokens=None): \"\"\" Initialize params for RateLimitHandler",
"import Cursor # Global, unauthenticated instance of API api = API() def debug(enable=True,",
"using the RateLimitHandler with multiple access tokens (see https://github.com/svven/tweepy). It also handles API",
"be a dictionary but it can be loaded later just before the first",
"from tweepy.cache import Cache, MemoryCache, FileCache from tweepy.auth import OAuthHandler, AppAuthHandler from tweepy.limit",
"tokens (see https://github.com/svven/tweepy). It also handles API method cursors and splits input param",
"RateLimitError from tweepy.api import API from tweepy.cache import Cache, MemoryCache, FileCache from tweepy.auth",
"def api(self): \"Lazy loaded Tweepy API object.\" if not self._api: self._api = self._get_api()",
"multiple access tokens (see https://github.com/svven/tweepy). It also handles API method cursors and splits",
"'3.5.0' __author__ = '<NAME>' __license__ = 'MIT' from tweepy.models import Status, User, DirectMessage,",
"Twitter API library \"\"\" __version__ = '3.5.0' __author__ = '<NAME>' __license__ = 'MIT'",
"{user_id: (access_token_key, access_token_secret)}. \"\"\" self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.access_tokens = access_tokens",
"from tweepy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory, Category from tweepy.error",
"SearchResults, ModelFactory, Category from tweepy.error import TweepError, RateLimitError from tweepy.api import API from",
"2009-2010 <NAME> # See LICENSE for details. \"\"\" Tweepy Twitter API library \"\"\"",
"Tweepy Twitter API library \"\"\" __version__ = '3.5.0' __author__ = '<NAME>' __license__ =",
"MemoryCache, FileCache from tweepy.auth import OAuthHandler, AppAuthHandler from tweepy.limit import RateLimitHandler from tweepy.streaming",
"chunks(l, n): for i in xrange(0, len(l), n): yield l[i:i+n] class Twitter(object): \"\"\"",
"tweepy.cache import Cache, MemoryCache, FileCache from tweepy.auth import OAuthHandler, AppAuthHandler from tweepy.limit import",
"# retry_count=2, retry_delay=3, # wait_on_rate_limit=True, wait_on_rate_limit_notify=True @property def api(self): \"Lazy loaded Tweepy API",
"import TweepError, RateLimitError from tweepy.api import API from tweepy.cache import Cache, MemoryCache, FileCache",
"Tweepy API. Param `access_tokens` must be a dictionary but it can be loaded",
"def _get_api(self): \"Initialize Tweepy API object with RateLimitHandler auth.\" auth = RateLimitHandler(self.consumer_key, self.consumer_secret)",
"wait_on_rate_limit_notify=True @property def api(self): \"Lazy loaded Tweepy API object.\" if not self._api: self._api",
"\"\"\" Tweepy Twitter API library \"\"\" __version__ = '3.5.0' __author__ = '<NAME>' __license__",
"# Global, unauthenticated instance of API api = API() def debug(enable=True, level=1): from",
"It also handles API method cursors and splits input param lists in chunks",
"self.consumer_secret = consumer_secret self.access_tokens = access_tokens _api = None def _get_api(self): \"Initialize Tweepy",
"details. \"\"\" Tweepy Twitter API library \"\"\" __version__ = '3.5.0' __author__ = '<NAME>'",
"(see https://github.com/svven/tweepy). It also handles API method cursors and splits input param lists",
"in self.access_tokens.values(): auth.add_access_token(key, secret) # print 'Token pool size: %d' % len(auth.tokens) return",
"Friendship, SavedSearch, SearchResults, ModelFactory, Category from tweepy.error import TweepError, RateLimitError from tweepy.api import",
"splits input param lists in chunks if neccessary. \"\"\" def __init__(self, consumer_key, consumer_secret,",
"= 'MIT' from tweepy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory, Category",
"<NAME> # See LICENSE for details. \"\"\" Tweepy Twitter API library \"\"\" __version__",
"just before the first API method call, and has to be like {user_id:",
"API from tweepy.cache import Cache, MemoryCache, FileCache from tweepy.auth import OAuthHandler, AppAuthHandler from",
"first API method call, and has to be like {user_id: (access_token_key, access_token_secret)}. \"\"\"",
"User, DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory, Category from tweepy.error import TweepError, RateLimitError from",
"consumer_secret self.access_tokens = access_tokens _api = None def _get_api(self): \"Initialize Tweepy API object",
"for RateLimitHandler to pass to Tweepy API. Param `access_tokens` must be a dictionary",
"auth.add_access_token(key, secret) # print 'Token pool size: %d' % len(auth.tokens) return API(auth) #",
"RateLimitHandler from tweepy.streaming import Stream, StreamListener from tweepy.cursor import Cursor # Global, unauthenticated",
"xrange(0, len(l), n): yield l[i:i+n] class Twitter(object): \"\"\" Twitter API wrapper based on",
"__init__(self, consumer_key, consumer_secret, access_tokens=None): \"\"\" Initialize params for RateLimitHandler to pass to Tweepy",
"access_tokens=None): \"\"\" Initialize params for RateLimitHandler to pass to Tweepy API. Param `access_tokens`",
"lists in chunks if neccessary. \"\"\" def __init__(self, consumer_key, consumer_secret, access_tokens=None): \"\"\" Initialize",
"Category from tweepy.error import TweepError, RateLimitError from tweepy.api import API from tweepy.cache import",
"ModelFactory, Category from tweepy.error import TweepError, RateLimitError from tweepy.api import API from tweepy.cache",
"= consumer_secret self.access_tokens = access_tokens _api = None def _get_api(self): \"Initialize Tweepy API",
"retry_delay=3, # wait_on_rate_limit=True, wait_on_rate_limit_notify=True @property def api(self): \"Lazy loaded Tweepy API object.\" if",
"level=1): from six.moves.http_client import HTTPConnection HTTPConnection.debuglevel = level def chunks(l, n): for i",
"size: %d' % len(auth.tokens) return API(auth) # retry_count=2, retry_delay=3, # wait_on_rate_limit=True, wait_on_rate_limit_notify=True @property",
"API object with RateLimitHandler auth.\" auth = RateLimitHandler(self.consumer_key, self.consumer_secret) for key, secret in",
"key, secret in self.access_tokens.values(): auth.add_access_token(key, secret) # print 'Token pool size: %d' %",
"method call, and has to be like {user_id: (access_token_key, access_token_secret)}. \"\"\" self.consumer_key =",
"__version__ = '3.5.0' __author__ = '<NAME>' __license__ = 'MIT' from tweepy.models import Status,",
"must be a dictionary but it can be loaded later just before the",
"self.access_tokens = access_tokens _api = None def _get_api(self): \"Initialize Tweepy API object with",
"% len(auth.tokens) return API(auth) # retry_count=2, retry_delay=3, # wait_on_rate_limit=True, wait_on_rate_limit_notify=True @property def api(self):",
"the first API method call, and has to be like {user_id: (access_token_key, access_token_secret)}.",
"to Tweepy API. Param `access_tokens` must be a dictionary but it can be",
"= API() def debug(enable=True, level=1): from six.moves.http_client import HTTPConnection HTTPConnection.debuglevel = level def",
"later just before the first API method call, and has to be like",
"None def _get_api(self): \"Initialize Tweepy API object with RateLimitHandler auth.\" auth = RateLimitHandler(self.consumer_key,",
"Cursor # Global, unauthenticated instance of API api = API() def debug(enable=True, level=1):",
"Tweepy API object with RateLimitHandler auth.\" auth = RateLimitHandler(self.consumer_key, self.consumer_secret) for key, secret",
"secret) # print 'Token pool size: %d' % len(auth.tokens) return API(auth) # retry_count=2,",
"handles API method cursors and splits input param lists in chunks if neccessary.",
"consumer_key, consumer_secret, access_tokens=None): \"\"\" Initialize params for RateLimitHandler to pass to Tweepy API.",
"= access_tokens _api = None def _get_api(self): \"Initialize Tweepy API object with RateLimitHandler",
"# print 'Token pool size: %d' % len(auth.tokens) return API(auth) # retry_count=2, retry_delay=3,",
"= level def chunks(l, n): for i in xrange(0, len(l), n): yield l[i:i+n]",
"AppAuthHandler from tweepy.limit import RateLimitHandler from tweepy.streaming import Stream, StreamListener from tweepy.cursor import",
"See LICENSE for details. \"\"\" Tweepy Twitter API library \"\"\" __version__ = '3.5.0'",
"unauthenticated instance of API api = API() def debug(enable=True, level=1): from six.moves.http_client import",
"Tweepy using the RateLimitHandler with multiple access tokens (see https://github.com/svven/tweepy). It also handles",
"https://github.com/svven/tweepy). It also handles API method cursors and splits input param lists in",
"input param lists in chunks if neccessary. \"\"\" def __init__(self, consumer_key, consumer_secret, access_tokens=None):",
"RateLimitHandler(self.consumer_key, self.consumer_secret) for key, secret in self.access_tokens.values(): auth.add_access_token(key, secret) # print 'Token pool",
"be like {user_id: (access_token_key, access_token_secret)}. \"\"\" self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.access_tokens",
"call, and has to be like {user_id: (access_token_key, access_token_secret)}. \"\"\" self.consumer_key = consumer_key",
"self.consumer_secret) for key, secret in self.access_tokens.values(): auth.add_access_token(key, secret) # print 'Token pool size:",
"access tokens (see https://github.com/svven/tweepy). It also handles API method cursors and splits input",
"= '<NAME>' __license__ = 'MIT' from tweepy.models import Status, User, DirectMessage, Friendship, SavedSearch,",
"from tweepy.error import TweepError, RateLimitError from tweepy.api import API from tweepy.cache import Cache,",
"tweepy.limit import RateLimitHandler from tweepy.streaming import Stream, StreamListener from tweepy.cursor import Cursor #",
"access_token_secret)}. \"\"\" self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.access_tokens = access_tokens _api =",
"it can be loaded later just before the first API method call, and",
"@property def api(self): \"Lazy loaded Tweepy API object.\" if not self._api: self._api =",
"also handles API method cursors and splits input param lists in chunks if",
"param lists in chunks if neccessary. \"\"\" def __init__(self, consumer_key, consumer_secret, access_tokens=None): \"\"\"",
"api(self): \"Lazy loaded Tweepy API object.\" if not self._api: self._api = self._get_api() return",
"Twitter API wrapper based on Tweepy using the RateLimitHandler with multiple access tokens",
"API method call, and has to be like {user_id: (access_token_key, access_token_secret)}. \"\"\" self.consumer_key",
"Stream, StreamListener from tweepy.cursor import Cursor # Global, unauthenticated instance of API api",
"the RateLimitHandler with multiple access tokens (see https://github.com/svven/tweepy). It also handles API method",
"import HTTPConnection HTTPConnection.debuglevel = level def chunks(l, n): for i in xrange(0, len(l),",
"self.access_tokens.values(): auth.add_access_token(key, secret) # print 'Token pool size: %d' % len(auth.tokens) return API(auth)",
"API() def debug(enable=True, level=1): from six.moves.http_client import HTTPConnection HTTPConnection.debuglevel = level def chunks(l,",
"Status, User, DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory, Category from tweepy.error import TweepError, RateLimitError",
"and has to be like {user_id: (access_token_key, access_token_secret)}. \"\"\" self.consumer_key = consumer_key self.consumer_secret",
"api = API() def debug(enable=True, level=1): from six.moves.http_client import HTTPConnection HTTPConnection.debuglevel = level",
"loaded later just before the first API method call, and has to be",
"\"Lazy loaded Tweepy API object.\" if not self._api: self._api = self._get_api() return self._api",
"on Tweepy using the RateLimitHandler with multiple access tokens (see https://github.com/svven/tweepy). It also",
"TweepError, RateLimitError from tweepy.api import API from tweepy.cache import Cache, MemoryCache, FileCache from",
"can be loaded later just before the first API method call, and has",
"HTTPConnection.debuglevel = level def chunks(l, n): for i in xrange(0, len(l), n): yield",
"tweepy.cursor import Cursor # Global, unauthenticated instance of API api = API() def",
"HTTPConnection HTTPConnection.debuglevel = level def chunks(l, n): for i in xrange(0, len(l), n):",
"yield l[i:i+n] class Twitter(object): \"\"\" Twitter API wrapper based on Tweepy using the",
"before the first API method call, and has to be like {user_id: (access_token_key,",
"# Copyright 2009-2010 <NAME> # See LICENSE for details. \"\"\" Tweepy Twitter API",
"API api = API() def debug(enable=True, level=1): from six.moves.http_client import HTTPConnection HTTPConnection.debuglevel =",
"_api = None def _get_api(self): \"Initialize Tweepy API object with RateLimitHandler auth.\" auth",
"for key, secret in self.access_tokens.values(): auth.add_access_token(key, secret) # print 'Token pool size: %d'",
"\"\"\" def __init__(self, consumer_key, consumer_secret, access_tokens=None): \"\"\" Initialize params for RateLimitHandler to pass",
"with multiple access tokens (see https://github.com/svven/tweepy). It also handles API method cursors and",
"instance of API api = API() def debug(enable=True, level=1): from six.moves.http_client import HTTPConnection",
"return API(auth) # retry_count=2, retry_delay=3, # wait_on_rate_limit=True, wait_on_rate_limit_notify=True @property def api(self): \"Lazy loaded",
"in chunks if neccessary. \"\"\" def __init__(self, consumer_key, consumer_secret, access_tokens=None): \"\"\" Initialize params",
"'<NAME>' __license__ = 'MIT' from tweepy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResults,",
"Initialize params for RateLimitHandler to pass to Tweepy API. Param `access_tokens` must be",
"auth = RateLimitHandler(self.consumer_key, self.consumer_secret) for key, secret in self.access_tokens.values(): auth.add_access_token(key, secret) # print",
"n): yield l[i:i+n] class Twitter(object): \"\"\" Twitter API wrapper based on Tweepy using",
"params for RateLimitHandler to pass to Tweepy API. Param `access_tokens` must be a",
"import Stream, StreamListener from tweepy.cursor import Cursor # Global, unauthenticated instance of API",
"import Cache, MemoryCache, FileCache from tweepy.auth import OAuthHandler, AppAuthHandler from tweepy.limit import RateLimitHandler",
"# See LICENSE for details. \"\"\" Tweepy Twitter API library \"\"\" __version__ =",
"to be like {user_id: (access_token_key, access_token_secret)}. \"\"\" self.consumer_key = consumer_key self.consumer_secret = consumer_secret",
"of API api = API() def debug(enable=True, level=1): from six.moves.http_client import HTTPConnection HTTPConnection.debuglevel",
"to pass to Tweepy API. Param `access_tokens` must be a dictionary but it",
"pass to Tweepy API. Param `access_tokens` must be a dictionary but it can",
"consumer_secret, access_tokens=None): \"\"\" Initialize params for RateLimitHandler to pass to Tweepy API. Param",
"like {user_id: (access_token_key, access_token_secret)}. \"\"\" self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.access_tokens =",
"__author__ = '<NAME>' __license__ = 'MIT' from tweepy.models import Status, User, DirectMessage, Friendship,",
"\"Initialize Tweepy API object with RateLimitHandler auth.\" auth = RateLimitHandler(self.consumer_key, self.consumer_secret) for key,",
"pool size: %d' % len(auth.tokens) return API(auth) # retry_count=2, retry_delay=3, # wait_on_rate_limit=True, wait_on_rate_limit_notify=True",
"RateLimitHandler to pass to Tweepy API. Param `access_tokens` must be a dictionary but",
"but it can be loaded later just before the first API method call,",
"= RateLimitHandler(self.consumer_key, self.consumer_secret) for key, secret in self.access_tokens.values(): auth.add_access_token(key, secret) # print 'Token",
"SavedSearch, SearchResults, ModelFactory, Category from tweepy.error import TweepError, RateLimitError from tweepy.api import API",
"Cache, MemoryCache, FileCache from tweepy.auth import OAuthHandler, AppAuthHandler from tweepy.limit import RateLimitHandler from",
"= '3.5.0' __author__ = '<NAME>' __license__ = 'MIT' from tweepy.models import Status, User,",
"for details. \"\"\" Tweepy Twitter API library \"\"\" __version__ = '3.5.0' __author__ =",
"class Twitter(object): \"\"\" Twitter API wrapper based on Tweepy using the RateLimitHandler with"
] |
[
"PDST # eMail: <EMAIL> # Purpose: Solution to Q5 page 53 from turtle",
"lineLen = randint(50, 100) left(angle) forward(lineLen) angle = randint(0, 360) lineLen = randint(50,",
"Solution to Q5 page 53 from turtle import * from random import *",
"randint(50, 100) left(angle) forward(lineLen) angle = randint(0, 360) lineLen = randint(50, 100) left(angle)",
"eMail: <EMAIL> # Purpose: Solution to Q5 page 53 from turtle import *",
"<NAME>, PDST # eMail: <EMAIL> # Purpose: Solution to Q5 page 53 from",
"to Q5 page 53 from turtle import * from random import * angle",
"Workshop # Date: May 2018 # Author: <NAME>, PDST # eMail: <EMAIL> #",
"* angle = randint(0, 360) lineLen = randint(50, 100) left(angle) forward(lineLen) angle =",
"angle = randint(0, 360) lineLen = randint(50, 100) left(angle) forward(lineLen) angle = randint(0,",
"* from random import * angle = randint(0, 360) lineLen = randint(50, 100)",
"May 2018 # Author: <NAME>, PDST # eMail: <EMAIL> # Purpose: Solution to",
"<gh_stars>1-10 # Event: LCCS Python Fundamental Skills Workshop # Date: May 2018 #",
"= randint(0, 360) lineLen = randint(50, 100) left(angle) forward(lineLen) angle = randint(0, 360)",
"Date: May 2018 # Author: <NAME>, PDST # eMail: <EMAIL> # Purpose: Solution",
"turtle import * from random import * angle = randint(0, 360) lineLen =",
"Event: LCCS Python Fundamental Skills Workshop # Date: May 2018 # Author: <NAME>,",
"<EMAIL> # Purpose: Solution to Q5 page 53 from turtle import * from",
"random import * angle = randint(0, 360) lineLen = randint(50, 100) left(angle) forward(lineLen)",
"randint(0, 360) lineLen = randint(50, 100) left(angle) forward(lineLen) angle = randint(0, 360) lineLen",
"# Date: May 2018 # Author: <NAME>, PDST # eMail: <EMAIL> # Purpose:",
"# Purpose: Solution to Q5 page 53 from turtle import * from random",
"page 53 from turtle import * from random import * angle = randint(0,",
"from turtle import * from random import * angle = randint(0, 360) lineLen",
"from random import * angle = randint(0, 360) lineLen = randint(50, 100) left(angle)",
"Fundamental Skills Workshop # Date: May 2018 # Author: <NAME>, PDST # eMail:",
"# Author: <NAME>, PDST # eMail: <EMAIL> # Purpose: Solution to Q5 page",
"Author: <NAME>, PDST # eMail: <EMAIL> # Purpose: Solution to Q5 page 53",
"forward(lineLen) angle = randint(0, 360) lineLen = randint(50, 100) left(angle) forward(lineLen) angle =",
"Q5 page 53 from turtle import * from random import * angle =",
"import * angle = randint(0, 360) lineLen = randint(50, 100) left(angle) forward(lineLen) angle",
"360) lineLen = randint(50, 100) left(angle) forward(lineLen) angle = randint(0, 360) lineLen =",
"# eMail: <EMAIL> # Purpose: Solution to Q5 page 53 from turtle import",
"LCCS Python Fundamental Skills Workshop # Date: May 2018 # Author: <NAME>, PDST",
"2018 # Author: <NAME>, PDST # eMail: <EMAIL> # Purpose: Solution to Q5",
"import * from random import * angle = randint(0, 360) lineLen = randint(50,",
"left(angle) forward(lineLen) angle = randint(0, 360) lineLen = randint(50, 100) left(angle) forward(lineLen) angle",
"Purpose: Solution to Q5 page 53 from turtle import * from random import",
"Python Fundamental Skills Workshop # Date: May 2018 # Author: <NAME>, PDST #",
"Skills Workshop # Date: May 2018 # Author: <NAME>, PDST # eMail: <EMAIL>",
"53 from turtle import * from random import * angle = randint(0, 360)",
"# Event: LCCS Python Fundamental Skills Workshop # Date: May 2018 # Author:",
"100) left(angle) forward(lineLen) angle = randint(0, 360) lineLen = randint(50, 100) left(angle) forward(lineLen)",
"= randint(50, 100) left(angle) forward(lineLen) angle = randint(0, 360) lineLen = randint(50, 100)"
] |
[
"which to place results') args = construct_hyper_param(parser) return args def load_models(args): BERT_PT_PATH =",
"pass def read_scripts(txt_path): nlu = [] with open(txt_path, 'r') as f: line =",
"'__main__': dset_name = 'qian' save_path = './Qian_data/' ### model args = get_args() model,",
"tb.append(data_tables[tbid]) hds.append(data_tables[tbid]['header']) return nlu, nlu_t, tb, hds def my_predict( data_loader, data_table, model, model_bert,",
"= generate_sql_q(pr_sql_i, tb) for b, (pr_sql_i1, pr_sql_q1) in enumerate(zip(pr_sql_i, pr_sql_q)): results1 = {}",
"== '__main__': dset_name = 'qian' save_path = './Qian_data/' ### model args = get_args()",
"engine = DBEngine(path_db) results = [] for _, t in enumerate(data_loader): nlu, nlu_t,",
"nlu, beam_size=beam_size) # sort and generate pr_wc, pr_wo, pr_wv, pr_sql_i = sort_and_generate_pr_w(pr_sql_i) #",
"sort and generate pr_wc, pr_wo, pr_wv, pr_sql_i = sort_and_generate_pr_w(pr_sql_i) # Following variables are",
"merged! ) ### predict with torch.no_grad(): results = my_predict(data_loader, data_table, model, model_bert, bert_config,",
"hds, max_seq_length, num_out_layers_n=num_target_layers, num_out_layers_h=num_target_layers) if not EG: # No Execution guided decoding s_sc,",
"DBEngine(os.path.join(path_db, f\"{dset_name}.db\")) engine = DBEngine(path_db) results = [] for _, t in enumerate(data_loader):",
"with torch.no_grad(): results = my_predict(data_loader, data_table, model, model_bert, bert_config, tokenizer, max_seq_length=args.max_seq_length, num_target_layers=args.num_target_layers, path_db=db_path,",
"'table_id': tbid[i], }) return data if __name__ == '__main__': dset_name = 'qian' save_path",
"= argparse.ArgumentParser() # parser.add_argument(\"--model_file\", required=True, help='model file to use (e.g. model_best.pt)') # parser.add_argument(\"--bert_model_file\",",
"not EG: # No Execution guided decoding s_sc, s_sa, s_wn, s_wc, s_wo, s_wv",
"import torch import json import os from add_csv import csv_to_sqlite, csv_to_json from sqlnet.dbengine",
"tb, hds def my_predict( data_loader, data_table, model, model_bert, bert_config, tokenizer, max_seq_length, num_target_layers, path_db,",
"### data db_path = './Qian_data/qian.db' tb_path = './Qian_data/qian.tables.jsonl' data_table = get_tables(tb_path) data =",
"def read_csv_to_table(csv_path): # file_name as table_id table_id = csv_path.split('/')[-1][:-4] df = pd.read_csv(csv_path) headers",
"tokenizer, bert_config def my_get_fields(t, data_tables): ### t: list of dict ### data_tables: dict",
"def create_table_and_db(): pass def read_scripts(txt_path): nlu = [] with open(txt_path, 'r') as f:",
"prepare_data() data_loader = torch.utils.data.DataLoader( batch_size=args.bS, dataset=data, shuffle=False, num_workers=1, collate_fn=lambda x: x # now",
"parser.add_argument(\"--model_file\", required=True, help='model file to use (e.g. model_best.pt)') # parser.add_argument(\"--bert_model_file\", required=True, help='bert model",
"prediction #################### def get_args(): parser = argparse.ArgumentParser() # parser.add_argument(\"--model_file\", required=True, help='model file to",
"t1['table_id'] tb.append(data_tables[tbid]) hds.append(data_tables[tbid]['header']) return nlu, nlu_t, tb, hds def my_predict( data_loader, data_table, model,",
"[] with open(txt_path, 'r') as f: line = f.readline() while line: if line.endswith('\\n'):",
"max_seq_length, num_out_layers_n=num_target_layers, num_out_layers_h=num_target_layers) if not EG: # No Execution guided decoding s_sc, s_sa,",
"t_to_tt_idx, tt_to_t_idx \\ = get_wemb_bert(bert_config, model_bert, tokenizer, nlu_t, hds, max_seq_length, num_out_layers_n=num_target_layers, num_out_layers_h=num_target_layers) if",
"nlu_t = [] tbid = [] for i in range(len(sc_paths)): nlu_i = read_scripts(sc_paths[i])",
"pr_sql_i \\ = model.beam_forward(wemb_n, l_n, wemb_h, l_hpu, l_hs, engine, tb, nlu_t, nlu_tt, tt_to_t_idx,",
"as pd import argparse import torch import json import os from add_csv import",
"model_best.pt)') # parser.add_argument(\"--bert_model_file\", required=True, help='bert model file to use (e.g. model_bert_best.pt)') # parser.add_argument(\"--bert_path\",",
"prepare_data(): sc_paths = [ './Qian_data/company_script.txt', './Qian_data/product_script.txt',] sc_tableids = [ 'company_table', 'product_table',] nlu =",
"save_path = './Qian_data/' ### model args = get_args() model, model_bert, tokenizer, bert_config =",
"pr_wn, pr_sql_i \\ = model.beam_forward(wemb_n, l_n, wemb_h, l_hpu, l_hs, engine, tb, nlu_t, nlu_tt,",
"parser.add_argument(\"--data_path\", required=True, help='path to *.jsonl and *.db files') # parser.add_argument(\"--split\", required=True, help='prefix of",
"nlu_tt, t_to_tt_idx, tt_to_t_idx \\ = get_wemb_bert(bert_config, model_bert, tokenizer, nlu_t, hds, max_seq_length, num_out_layers_n=num_target_layers, num_out_layers_h=num_target_layers)",
"[] for t1 in t: nlu.append( t1['question']) nlu_t.append( t1['question_tok']) tbid = t1['table_id'] tb.append(data_tables[tbid])",
"required=True, help='bert model file to use (e.g. model_bert_best.pt)') # parser.add_argument(\"--bert_path\", required=True, help='path to",
"def load_models(args): BERT_PT_PATH = './data_and_model' path_model_bert = './model_bert_best.pt' path_model = './model_best.pt' model, model_bert,",
"s_wc, s_wo, s_wv = model(wemb_n, l_n, wemb_h, l_hpu, l_hs) pr_sc, pr_sa, pr_wn, pr_wc,",
"if __name__ == '__main__': dset_name = 'qian' save_path = './Qian_data/' ### model args",
"#### prediction #################### def get_args(): parser = argparse.ArgumentParser() # parser.add_argument(\"--model_file\", required=True, help='model file",
"pr_sql_q1 results.append(results1) return results #### deal with data ################### ## 不需要了 def read_csv_to_table(csv_path):",
"\\ = get_wemb_bert(bert_config, model_bert, tokenizer, nlu_t, hds, max_seq_length, num_out_layers_n=num_target_layers, num_out_layers_h=num_target_layers) if not EG:",
"wemb_h, l_hpu, l_hs) pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi = pred_sw_se(s_sc, s_sa, s_wn,",
"__name__ == '__main__': dset_name = 'qian' save_path = './Qian_data/' ### model args =",
"_, t in enumerate(data_loader): nlu, nlu_t, tb, hds = my_get_fields(t, data_table) wemb_n, wemb_h,",
"of jsonl and db files (e.g. dev)') # parser.add_argument(\"--result_path\", required=True, help='directory in which",
"bert_config = get_models(args, BERT_PT_PATH, True, path_model_bert, path_model) return model, model_bert, tokenizer, bert_config def",
"s_wv, ) pr_wv_str, pr_wv_str_wp = convert_pr_wvi_to_string(pr_wvi, nlu_t, nlu_tt, tt_to_t_idx, nlu) pr_sql_i = generate_sql_i(pr_sc,",
"'./model_best.pt' model, model_bert, tokenizer, bert_config = get_models(args, BERT_PT_PATH, True, path_model_bert, path_model) return model,",
"tbid.extend([sc_tableids[i]] * len(nlu_i)) data = [] for i in range(len(nlu)): data.append({ 'question': nlu[i],",
"bert_config, tokenizer, max_seq_length=args.max_seq_length, num_target_layers=args.num_target_layers, path_db=db_path, dset_name=dset_name, EG=False, #args.EG, ) # save results save_for_evaluation(save_path,",
"l_n, l_hpu, l_hs, \\ nlu_tt, t_to_tt_idx, tt_to_t_idx \\ = get_wemb_bert(bert_config, model_bert, tokenizer, nlu_t,",
"= './data_and_model' path_model_bert = './model_bert_best.pt' path_model = './model_best.pt' model, model_bert, tokenizer, bert_config =",
"[] for nlu1 in nlu: nlu_t.append(nlu1.split(' ')) return nlu_t def get_tables(tb_path): table =",
"sort_and_generate_pr_w(pr_sql_i) # Following variables are just for consistency with no-EG case. pr_wvi =",
"nlu: nlu_t.append(nlu1.split(' ')) return nlu_t def get_tables(tb_path): table = {} with open(tb_path) as",
"tbid = [] for i in range(len(sc_paths)): nlu_i = read_scripts(sc_paths[i]) nlu_t_i = split_scripts(nlu_i)",
"= [] with open(txt_path, 'r') as f: line = f.readline() while line: if",
"with open(txt_path, 'r') as f: line = f.readline() while line: if line.endswith('\\n'): nlu.append(line[:-1])",
"args = get_args() model, model_bert, tokenizer, bert_config = load_models(args) ### data db_path =",
"pr_wo, pr_wv, pr_sql_i = sort_and_generate_pr_w(pr_sql_i) # Following variables are just for consistency with",
"# parser.add_argument(\"--bert_path\", required=True, help='path to bert files (bert_config*.json etc)') # parser.add_argument(\"--data_path\", required=True, help='path",
"*.db files') # parser.add_argument(\"--split\", required=True, help='prefix of jsonl and db files (e.g. dev)')",
"model, model_bert, tokenizer, bert_config = get_models(args, BERT_PT_PATH, True, path_model_bert, path_model) return model, model_bert,",
"parser = argparse.ArgumentParser() # parser.add_argument(\"--model_file\", required=True, help='model file to use (e.g. model_best.pt)') #",
"data db_path = './Qian_data/qian.db' tb_path = './Qian_data/qian.tables.jsonl' data_table = get_tables(tb_path) data = prepare_data()",
"= 'qian' save_path = './Qian_data/' ### model args = get_args() model, model_bert, tokenizer,",
"and db files (e.g. dev)') # parser.add_argument(\"--result_path\", required=True, help='directory in which to place",
"enumerate(f): t1 = json.loads(line.strip()) table[t1['id']] = t1 return table def prepare_data(): sc_paths =",
"sqlova.utils.utils_wikisql import * from train import construct_hyper_param, get_models #### prediction #################### def get_args():",
"wemb_n, wemb_h, l_n, l_hpu, l_hs, \\ nlu_tt, t_to_tt_idx, tt_to_t_idx \\ = get_wemb_bert(bert_config, model_bert,",
"file to use (e.g. model_best.pt)') # parser.add_argument(\"--bert_model_file\", required=True, help='bert model file to use",
"no-EG case. pr_wvi = None # not used pr_wv_str=None pr_wv_str_wp=None pr_sql_q = generate_sql_q(pr_sql_i,",
"line = f.readline() return nlu ## TODO: with tools in annotate_ws.py def split_scripts(nlu):",
"= [] nlu_t = [] tbid = [] for i in range(len(sc_paths)): nlu_i",
"are just for consistency with no-EG case. pr_wvi = None # not used",
"nlu.append( t1['question']) nlu_t.append( t1['question_tok']) tbid = t1['table_id'] tb.append(data_tables[tbid]) hds.append(data_tables[tbid]['header']) return nlu, nlu_t, tb,",
"nlu_t, hds, max_seq_length, num_out_layers_n=num_target_layers, num_out_layers_h=num_target_layers) if not EG: # No Execution guided decoding",
"read_csv_to_table(csv_path): # file_name as table_id table_id = csv_path.split('/')[-1][:-4] df = pd.read_csv(csv_path) headers =",
"dictionary values are not merged! ) ### predict with torch.no_grad(): results = my_predict(data_loader,",
"from add_csv import csv_to_sqlite, csv_to_json from sqlnet.dbengine import DBEngine from sqlova.utils.utils_wikisql import *",
"engine, tb, nlu_t, nlu_tt, tt_to_t_idx, nlu, beam_size=beam_size) # sort and generate pr_wc, pr_wo,",
"import json import os from add_csv import csv_to_sqlite, csv_to_json from sqlnet.dbengine import DBEngine",
"use (e.g. model_bert_best.pt)') # parser.add_argument(\"--bert_path\", required=True, help='path to bert files (bert_config*.json etc)') #",
"num_out_layers_h=num_target_layers) if not EG: # No Execution guided decoding s_sc, s_sa, s_wn, s_wc,",
"s_wc, s_wo, s_wv, ) pr_wv_str, pr_wv_str_wp = convert_pr_wvi_to_string(pr_wvi, nlu_t, nlu_tt, tt_to_t_idx, nlu) pr_sql_i",
"= sort_and_generate_pr_w(pr_sql_i) # Following variables are just for consistency with no-EG case. pr_wvi",
"'company_table', 'product_table',] nlu = [] nlu_t = [] tbid = [] for i",
"EG=False, beam_size=4): model.eval() model_bert.eval() # engine = DBEngine(os.path.join(path_db, f\"{dset_name}.db\")) engine = DBEngine(path_db) results",
"[], [], [] for t1 in t: nlu.append( t1['question']) nlu_t.append( t1['question_tok']) tbid =",
"dset_name, EG=False, beam_size=4): model.eval() model_bert.eval() # engine = DBEngine(os.path.join(path_db, f\"{dset_name}.db\")) engine = DBEngine(path_db)",
"def my_get_fields(t, data_tables): ### t: list of dict ### data_tables: dict nlu, nlu_t,",
"data_table, model, model_bert, bert_config, tokenizer, max_seq_length=args.max_seq_length, num_target_layers=args.num_target_layers, path_db=db_path, dset_name=dset_name, EG=False, #args.EG, ) #",
"l_hs, engine, tb, nlu_t, nlu_tt, tt_to_t_idx, nlu, beam_size=beam_size) # sort and generate pr_wc,",
"df.iterrows(): rows.append(row.tolist()) print(rows) ## TODO: add_csv def create_table_and_db(): pass def read_scripts(txt_path): nlu =",
"for i in range(len(nlu)): data.append({ 'question': nlu[i], 'question_tok': nlu_t[i], 'table_id': tbid[i], }) return",
"parser.add_argument(\"--bert_model_file\", required=True, help='bert model file to use (e.g. model_bert_best.pt)') # parser.add_argument(\"--bert_path\", required=True, help='path",
"pr_wv_str_wp=None pr_sql_q = generate_sql_q(pr_sql_i, tb) for b, (pr_sql_i1, pr_sql_q1) in enumerate(zip(pr_sql_i, pr_sql_q)): results1",
"#################### def get_args(): parser = argparse.ArgumentParser() # parser.add_argument(\"--model_file\", required=True, help='model file to use",
"parser.add_argument(\"--result_path\", required=True, help='directory in which to place results') args = construct_hyper_param(parser) return args",
"# file_name as table_id table_id = csv_path.split('/')[-1][:-4] df = pd.read_csv(csv_path) headers = df.columns.tolist()",
"return nlu_t def get_tables(tb_path): table = {} with open(tb_path) as f: for _,",
"not merged! ) ### predict with torch.no_grad(): results = my_predict(data_loader, data_table, model, model_bert,",
"table_id table_id = csv_path.split('/')[-1][:-4] df = pd.read_csv(csv_path) headers = df.columns.tolist() rows = []",
"open(tb_path) as f: for _, line in enumerate(f): t1 = json.loads(line.strip()) table[t1['id']] =",
"[ 'company_table', 'product_table',] nlu = [] nlu_t = [] tbid = [] for",
"pred_sw_se(s_sc, s_sa, s_wn, s_wc, s_wo, s_wv, ) pr_wv_str, pr_wv_str_wp = convert_pr_wvi_to_string(pr_wvi, nlu_t, nlu_tt,",
"nlu = [] nlu_t = [] tbid = [] for i in range(len(sc_paths)):",
"*.jsonl and *.db files') # parser.add_argument(\"--split\", required=True, help='prefix of jsonl and db files",
"nlu_t.extend(nlu_t_i) tbid.extend([sc_tableids[i]] * len(nlu_i)) data = [] for i in range(len(nlu)): data.append({ 'question':",
"x: x # now dictionary values are not merged! ) ### predict with",
"(e.g. model_best.pt)') # parser.add_argument(\"--bert_model_file\", required=True, help='bert model file to use (e.g. model_bert_best.pt)') #",
"data_loader, data_table, model, model_bert, bert_config, tokenizer, max_seq_length, num_target_layers, path_db, dset_name, EG=False, beam_size=4): model.eval()",
"model, model_bert, bert_config, tokenizer, max_seq_length, num_target_layers, path_db, dset_name, EG=False, beam_size=4): model.eval() model_bert.eval() #",
"df.columns.tolist() rows = [] for _, row in df.iterrows(): rows.append(row.tolist()) print(rows) ## TODO:",
"results1[\"table_id\"] = tb[b][\"id\"] results1[\"nlu\"] = nlu[b] results1[\"sql\"] = pr_sql_q1 results.append(results1) return results ####",
"import construct_hyper_param, get_models #### prediction #################### def get_args(): parser = argparse.ArgumentParser() # parser.add_argument(\"--model_file\",",
"from datetime import timedelta import numpy as np import pandas as pd import",
"import argparse import torch import json import os from add_csv import csv_to_sqlite, csv_to_json",
"= nlu[b] results1[\"sql\"] = pr_sql_q1 results.append(results1) return results #### deal with data ###################",
"tt_to_t_idx, nlu, beam_size=beam_size) # sort and generate pr_wc, pr_wo, pr_wv, pr_sql_i = sort_and_generate_pr_w(pr_sql_i)",
"values are not merged! ) ### predict with torch.no_grad(): results = my_predict(data_loader, data_table,",
"file_name as table_id table_id = csv_path.split('/')[-1][:-4] df = pd.read_csv(csv_path) headers = df.columns.tolist() rows",
"= [] tbid = [] for i in range(len(sc_paths)): nlu_i = read_scripts(sc_paths[i]) nlu_t_i",
"import csv_to_sqlite, csv_to_json from sqlnet.dbengine import DBEngine from sqlova.utils.utils_wikisql import * from train",
"line in enumerate(f): t1 = json.loads(line.strip()) table[t1['id']] = t1 return table def prepare_data():",
"parser.add_argument(\"--bert_path\", required=True, help='path to bert files (bert_config*.json etc)') # parser.add_argument(\"--data_path\", required=True, help='path to",
"hds def my_predict( data_loader, data_table, model, model_bert, bert_config, tokenizer, max_seq_length, num_target_layers, path_db, dset_name,",
"return data if __name__ == '__main__': dset_name = 'qian' save_path = './Qian_data/' ###",
"generate_sql_i(pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wv_str, nlu) else: # Execution guided decoding prob_sca,",
"(e.g. dev)') # parser.add_argument(\"--result_path\", required=True, help='directory in which to place results') args =",
"BERT_PT_PATH = './data_and_model' path_model_bert = './model_bert_best.pt' path_model = './model_best.pt' model, model_bert, tokenizer, bert_config",
"return nlu, nlu_t, tb, hds def my_predict( data_loader, data_table, model, model_bert, bert_config, tokenizer,",
"as np import pandas as pd import argparse import torch import json import",
"= [ './Qian_data/company_script.txt', './Qian_data/product_script.txt',] sc_tableids = [ 'company_table', 'product_table',] nlu = [] nlu_t",
"etc)') # parser.add_argument(\"--data_path\", required=True, help='path to *.jsonl and *.db files') # parser.add_argument(\"--split\", required=True,",
"parser.add_argument(\"--split\", required=True, help='prefix of jsonl and db files (e.g. dev)') # parser.add_argument(\"--result_path\", required=True,",
"generate_sql_q(pr_sql_i, tb) for b, (pr_sql_i1, pr_sql_q1) in enumerate(zip(pr_sql_i, pr_sql_q)): results1 = {} results1[\"query\"]",
"pr_wc, pr_wo, pr_wv, pr_sql_i = sort_and_generate_pr_w(pr_sql_i) # Following variables are just for consistency",
"get_args() model, model_bert, tokenizer, bert_config = load_models(args) ### data db_path = './Qian_data/qian.db' tb_path",
"# No Execution guided decoding s_sc, s_sa, s_wn, s_wc, s_wo, s_wv = model(wemb_n,",
"= [ 'company_table', 'product_table',] nlu = [] nlu_t = [] tbid = []",
"timedelta import numpy as np import pandas as pd import argparse import torch",
"dict nlu, nlu_t, tb, hds = [], [], [], [] for t1 in",
"prob_wn_w, \\ pr_sc, pr_sa, pr_wn, pr_sql_i \\ = model.beam_forward(wemb_n, l_n, wemb_h, l_hpu, l_hs,",
"True, path_model_bert, path_model) return model, model_bert, tokenizer, bert_config def my_get_fields(t, data_tables): ### t:",
"l_n, wemb_h, l_hpu, l_hs) pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi = pred_sw_se(s_sc, s_sa,",
"'product_table',] nlu = [] nlu_t = [] tbid = [] for i in",
"f\"{dset_name}.db\")) engine = DBEngine(path_db) results = [] for _, t in enumerate(data_loader): nlu,",
"torch import json import os from add_csv import csv_to_sqlite, csv_to_json from sqlnet.dbengine import",
"t: nlu.append( t1['question']) nlu_t.append( t1['question_tok']) tbid = t1['table_id'] tb.append(data_tables[tbid]) hds.append(data_tables[tbid]['header']) return nlu, nlu_t,",
"to use (e.g. model_bert_best.pt)') # parser.add_argument(\"--bert_path\", required=True, help='path to bert files (bert_config*.json etc)')",
"# parser.add_argument(\"--result_path\", required=True, help='directory in which to place results') args = construct_hyper_param(parser) return",
"'./Qian_data/' ### model args = get_args() model, model_bert, tokenizer, bert_config = load_models(args) ###",
"sqlnet.dbengine import DBEngine from sqlova.utils.utils_wikisql import * from train import construct_hyper_param, get_models ####",
"= DBEngine(path_db) results = [] for _, t in enumerate(data_loader): nlu, nlu_t, tb,",
"train import construct_hyper_param, get_models #### prediction #################### def get_args(): parser = argparse.ArgumentParser() #",
"= my_get_fields(t, data_table) wemb_n, wemb_h, l_n, l_hpu, l_hs, \\ nlu_tt, t_to_tt_idx, tt_to_t_idx \\",
"# not used pr_wv_str=None pr_wv_str_wp=None pr_sql_q = generate_sql_q(pr_sql_i, tb) for b, (pr_sql_i1, pr_sql_q1)",
"[], [] for t1 in t: nlu.append( t1['question']) nlu_t.append( t1['question_tok']) tbid = t1['table_id']",
"import timedelta import numpy as np import pandas as pd import argparse import",
"results.append(results1) return results #### deal with data ################### ## 不需要了 def read_csv_to_table(csv_path): #",
"dataset=data, shuffle=False, num_workers=1, collate_fn=lambda x: x # now dictionary values are not merged!",
"pr_sql_i = generate_sql_i(pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wv_str, nlu) else: # Execution guided",
"and *.db files') # parser.add_argument(\"--split\", required=True, help='prefix of jsonl and db files (e.g.",
"tokenizer, bert_config = get_models(args, BERT_PT_PATH, True, path_model_bert, path_model) return model, model_bert, tokenizer, bert_config",
"# Execution guided decoding prob_sca, prob_w, prob_wn_w, \\ pr_sc, pr_sa, pr_wn, pr_sql_i \\",
"= load_models(args) ### data db_path = './Qian_data/qian.db' tb_path = './Qian_data/qian.tables.jsonl' data_table = get_tables(tb_path)",
"return table def prepare_data(): sc_paths = [ './Qian_data/company_script.txt', './Qian_data/product_script.txt',] sc_tableids = [ 'company_table',",
"help='prefix of jsonl and db files (e.g. dev)') # parser.add_argument(\"--result_path\", required=True, help='directory in",
"nlu_t, tb, hds = my_get_fields(t, data_table) wemb_n, wemb_h, l_n, l_hpu, l_hs, \\ nlu_tt,",
"t1['question_tok']) tbid = t1['table_id'] tb.append(data_tables[tbid]) hds.append(data_tables[tbid]['header']) return nlu, nlu_t, tb, hds def my_predict(",
"pr_sql_i = sort_and_generate_pr_w(pr_sql_i) # Following variables are just for consistency with no-EG case.",
"'question_tok': nlu_t[i], 'table_id': tbid[i], }) return data if __name__ == '__main__': dset_name =",
"engine = DBEngine(os.path.join(path_db, f\"{dset_name}.db\")) engine = DBEngine(path_db) results = [] for _, t",
"tb) for b, (pr_sql_i1, pr_sql_q1) in enumerate(zip(pr_sql_i, pr_sql_q)): results1 = {} results1[\"query\"] =",
"enumerate(data_loader): nlu, nlu_t, tb, hds = my_get_fields(t, data_table) wemb_n, wemb_h, l_n, l_hpu, l_hs,",
"used pr_wv_str=None pr_wv_str_wp=None pr_sql_q = generate_sql_q(pr_sql_i, tb) for b, (pr_sql_i1, pr_sql_q1) in enumerate(zip(pr_sql_i,",
"= './model_best.pt' model, model_bert, tokenizer, bert_config = get_models(args, BERT_PT_PATH, True, path_model_bert, path_model) return",
"generate pr_wc, pr_wo, pr_wv, pr_sql_i = sort_and_generate_pr_w(pr_sql_i) # Following variables are just for",
"not used pr_wv_str=None pr_wv_str_wp=None pr_sql_q = generate_sql_q(pr_sql_i, tb) for b, (pr_sql_i1, pr_sql_q1) in",
"row in df.iterrows(): rows.append(row.tolist()) print(rows) ## TODO: add_csv def create_table_and_db(): pass def read_scripts(txt_path):",
"tokenizer, max_seq_length=args.max_seq_length, num_target_layers=args.num_target_layers, path_db=db_path, dset_name=dset_name, EG=False, #args.EG, ) # save results save_for_evaluation(save_path, results,",
"tokenizer, max_seq_length, num_target_layers, path_db, dset_name, EG=False, beam_size=4): model.eval() model_bert.eval() # engine = DBEngine(os.path.join(path_db,",
"\\ pr_sc, pr_sa, pr_wn, pr_sql_i \\ = model.beam_forward(wemb_n, l_n, wemb_h, l_hpu, l_hs, engine,",
"def get_args(): parser = argparse.ArgumentParser() # parser.add_argument(\"--model_file\", required=True, help='model file to use (e.g.",
"= [] for nlu1 in nlu: nlu_t.append(nlu1.split(' ')) return nlu_t def get_tables(tb_path): table",
"pd.read_csv(csv_path) headers = df.columns.tolist() rows = [] for _, row in df.iterrows(): rows.append(row.tolist())",
"nlu_tt, tt_to_t_idx, nlu) pr_sql_i = generate_sql_i(pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wv_str, nlu) else:",
"return model, model_bert, tokenizer, bert_config def my_get_fields(t, data_tables): ### t: list of dict",
"t1 return table def prepare_data(): sc_paths = [ './Qian_data/company_script.txt', './Qian_data/product_script.txt',] sc_tableids = [",
"def get_tables(tb_path): table = {} with open(tb_path) as f: for _, line in",
"line = f.readline() while line: if line.endswith('\\n'): nlu.append(line[:-1]) else: nlu.append(line) line = f.readline()",
"## TODO: add_csv def create_table_and_db(): pass def read_scripts(txt_path): nlu = [] with open(txt_path,",
"TODO: add_csv def create_table_and_db(): pass def read_scripts(txt_path): nlu = [] with open(txt_path, 'r')",
"nlu) pr_sql_i = generate_sql_i(pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wv_str, nlu) else: # Execution",
"model_bert, tokenizer, bert_config def my_get_fields(t, data_tables): ### t: list of dict ### data_tables:",
"data ################### ## 不需要了 def read_csv_to_table(csv_path): # file_name as table_id table_id = csv_path.split('/')[-1][:-4]",
"(e.g. model_bert_best.pt)') # parser.add_argument(\"--bert_path\", required=True, help='path to bert files (bert_config*.json etc)') # parser.add_argument(\"--data_path\",",
"nlu_t_i = split_scripts(nlu_i) nlu.extend(nlu_i) nlu_t.extend(nlu_t_i) tbid.extend([sc_tableids[i]] * len(nlu_i)) data = [] for i",
"help='bert model file to use (e.g. model_bert_best.pt)') # parser.add_argument(\"--bert_path\", required=True, help='path to bert",
"import DBEngine from sqlova.utils.utils_wikisql import * from train import construct_hyper_param, get_models #### prediction",
"dset_name = 'qian' save_path = './Qian_data/' ### model args = get_args() model, model_bert,",
"################### ## 不需要了 def read_csv_to_table(csv_path): # file_name as table_id table_id = csv_path.split('/')[-1][:-4] df",
"load_models(args): BERT_PT_PATH = './data_and_model' path_model_bert = './model_bert_best.pt' path_model = './model_best.pt' model, model_bert, tokenizer,",
"in enumerate(data_loader): nlu, nlu_t, tb, hds = my_get_fields(t, data_table) wemb_n, wemb_h, l_n, l_hpu,",
"pd import argparse import torch import json import os from add_csv import csv_to_sqlite,",
"in range(len(sc_paths)): nlu_i = read_scripts(sc_paths[i]) nlu_t_i = split_scripts(nlu_i) nlu.extend(nlu_i) nlu_t.extend(nlu_t_i) tbid.extend([sc_tableids[i]] * len(nlu_i))",
"s_sc, s_sa, s_wn, s_wc, s_wo, s_wv = model(wemb_n, l_n, wemb_h, l_hpu, l_hs) pr_sc,",
"results = my_predict(data_loader, data_table, model, model_bert, bert_config, tokenizer, max_seq_length=args.max_seq_length, num_target_layers=args.num_target_layers, path_db=db_path, dset_name=dset_name, EG=False,",
"data_tables): ### t: list of dict ### data_tables: dict nlu, nlu_t, tb, hds",
"in enumerate(zip(pr_sql_i, pr_sql_q)): results1 = {} results1[\"query\"] = pr_sql_i1 results1[\"table_id\"] = tb[b][\"id\"] results1[\"nlu\"]",
"batch_size=args.bS, dataset=data, shuffle=False, num_workers=1, collate_fn=lambda x: x # now dictionary values are not",
"= read_scripts(sc_paths[i]) nlu_t_i = split_scripts(nlu_i) nlu.extend(nlu_i) nlu_t.extend(nlu_t_i) tbid.extend([sc_tableids[i]] * len(nlu_i)) data = []",
"{} results1[\"query\"] = pr_sql_i1 results1[\"table_id\"] = tb[b][\"id\"] results1[\"nlu\"] = nlu[b] results1[\"sql\"] = pr_sql_q1",
"b, (pr_sql_i1, pr_sql_q1) in enumerate(zip(pr_sql_i, pr_sql_q)): results1 = {} results1[\"query\"] = pr_sql_i1 results1[\"table_id\"]",
"## TODO: with tools in annotate_ws.py def split_scripts(nlu): nlu_t = [] for nlu1",
"collate_fn=lambda x: x # now dictionary values are not merged! ) ### predict",
"pr_wv_str, nlu) else: # Execution guided decoding prob_sca, prob_w, prob_wn_w, \\ pr_sc, pr_sa,",
"while line: if line.endswith('\\n'): nlu.append(line[:-1]) else: nlu.append(line) line = f.readline() return nlu ##",
"nlu[b] results1[\"sql\"] = pr_sql_q1 results.append(results1) return results #### deal with data ################### ##",
"in nlu: nlu_t.append(nlu1.split(' ')) return nlu_t def get_tables(tb_path): table = {} with open(tb_path)",
"my_predict( data_loader, data_table, model, model_bert, bert_config, tokenizer, max_seq_length, num_target_layers, path_db, dset_name, EG=False, beam_size=4):",
"pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi = pred_sw_se(s_sc, s_sa, s_wn, s_wc, s_wo, s_wv, )",
"nlu ## TODO: with tools in annotate_ws.py def split_scripts(nlu): nlu_t = [] for",
"my_predict(data_loader, data_table, model, model_bert, bert_config, tokenizer, max_seq_length=args.max_seq_length, num_target_layers=args.num_target_layers, path_db=db_path, dset_name=dset_name, EG=False, #args.EG, )",
"for b, (pr_sql_i1, pr_sql_q1) in enumerate(zip(pr_sql_i, pr_sql_q)): results1 = {} results1[\"query\"] = pr_sql_i1",
"= {} with open(tb_path) as f: for _, line in enumerate(f): t1 =",
"f.readline() while line: if line.endswith('\\n'): nlu.append(line[:-1]) else: nlu.append(line) line = f.readline() return nlu",
"BERT_PT_PATH, True, path_model_bert, path_model) return model, model_bert, tokenizer, bert_config def my_get_fields(t, data_tables): ###",
"= './model_bert_best.pt' path_model = './model_best.pt' model, model_bert, tokenizer, bert_config = get_models(args, BERT_PT_PATH, True,",
"tbid[i], }) return data if __name__ == '__main__': dset_name = 'qian' save_path =",
"pr_sql_q1) in enumerate(zip(pr_sql_i, pr_sql_q)): results1 = {} results1[\"query\"] = pr_sql_i1 results1[\"table_id\"] = tb[b][\"id\"]",
"model_bert, tokenizer, bert_config = load_models(args) ### data db_path = './Qian_data/qian.db' tb_path = './Qian_data/qian.tables.jsonl'",
"path_model_bert, path_model) return model, model_bert, tokenizer, bert_config def my_get_fields(t, data_tables): ### t: list",
"as f: line = f.readline() while line: if line.endswith('\\n'): nlu.append(line[:-1]) else: nlu.append(line) line",
"db_path = './Qian_data/qian.db' tb_path = './Qian_data/qian.tables.jsonl' data_table = get_tables(tb_path) data = prepare_data() data_loader",
"# sort and generate pr_wc, pr_wo, pr_wv, pr_sql_i = sort_and_generate_pr_w(pr_sql_i) # Following variables",
"import numpy as np import pandas as pd import argparse import torch import",
"hds = my_get_fields(t, data_table) wemb_n, wemb_h, l_n, l_hpu, l_hs, \\ nlu_tt, t_to_tt_idx, tt_to_t_idx",
"json import os from add_csv import csv_to_sqlite, csv_to_json from sqlnet.dbengine import DBEngine from",
"get_tables(tb_path) data = prepare_data() data_loader = torch.utils.data.DataLoader( batch_size=args.bS, dataset=data, shuffle=False, num_workers=1, collate_fn=lambda x:",
"* len(nlu_i)) data = [] for i in range(len(nlu)): data.append({ 'question': nlu[i], 'question_tok':",
"i in range(len(nlu)): data.append({ 'question': nlu[i], 'question_tok': nlu_t[i], 'table_id': tbid[i], }) return data",
"# engine = DBEngine(os.path.join(path_db, f\"{dset_name}.db\")) engine = DBEngine(path_db) results = [] for _,",
"'./Qian_data/company_script.txt', './Qian_data/product_script.txt',] sc_tableids = [ 'company_table', 'product_table',] nlu = [] nlu_t = []",
"')) return nlu_t def get_tables(tb_path): table = {} with open(tb_path) as f: for",
"pr_sql_q = generate_sql_q(pr_sql_i, tb) for b, (pr_sql_i1, pr_sql_q1) in enumerate(zip(pr_sql_i, pr_sql_q)): results1 =",
"load_models(args) ### data db_path = './Qian_data/qian.db' tb_path = './Qian_data/qian.tables.jsonl' data_table = get_tables(tb_path) data",
"\\ = model.beam_forward(wemb_n, l_n, wemb_h, l_hpu, l_hs, engine, tb, nlu_t, nlu_tt, tt_to_t_idx, nlu,",
"place results') args = construct_hyper_param(parser) return args def load_models(args): BERT_PT_PATH = './data_and_model' path_model_bert",
"pr_sc, pr_sa, pr_wn, pr_sql_i \\ = model.beam_forward(wemb_n, l_n, wemb_h, l_hpu, l_hs, engine, tb,",
"np import pandas as pd import argparse import torch import json import os",
"### data_tables: dict nlu, nlu_t, tb, hds = [], [], [], [] for",
"model, model_bert, tokenizer, bert_config def my_get_fields(t, data_tables): ### t: list of dict ###",
"t in enumerate(data_loader): nlu, nlu_t, tb, hds = my_get_fields(t, data_table) wemb_n, wemb_h, l_n,",
"nlu.append(line) line = f.readline() return nlu ## TODO: with tools in annotate_ws.py def",
"rows = [] for _, row in df.iterrows(): rows.append(row.tolist()) print(rows) ## TODO: add_csv",
"* from train import construct_hyper_param, get_models #### prediction #################### def get_args(): parser =",
"# parser.add_argument(\"--split\", required=True, help='prefix of jsonl and db files (e.g. dev)') # parser.add_argument(\"--result_path\",",
"for i in range(len(sc_paths)): nlu_i = read_scripts(sc_paths[i]) nlu_t_i = split_scripts(nlu_i) nlu.extend(nlu_i) nlu_t.extend(nlu_t_i) tbid.extend([sc_tableids[i]]",
"= model.beam_forward(wemb_n, l_n, wemb_h, l_hpu, l_hs, engine, tb, nlu_t, nlu_tt, tt_to_t_idx, nlu, beam_size=beam_size)",
"shuffle=False, num_workers=1, collate_fn=lambda x: x # now dictionary values are not merged! )",
"results #### deal with data ################### ## 不需要了 def read_csv_to_table(csv_path): # file_name as",
"for _, row in df.iterrows(): rows.append(row.tolist()) print(rows) ## TODO: add_csv def create_table_and_db(): pass",
"get_args(): parser = argparse.ArgumentParser() # parser.add_argument(\"--model_file\", required=True, help='model file to use (e.g. model_best.pt)')",
"= get_args() model, model_bert, tokenizer, bert_config = load_models(args) ### data db_path = './Qian_data/qian.db'",
"just for consistency with no-EG case. pr_wvi = None # not used pr_wv_str=None",
"不需要了 def read_csv_to_table(csv_path): # file_name as table_id table_id = csv_path.split('/')[-1][:-4] df = pd.read_csv(csv_path)",
"nlu.append(line[:-1]) else: nlu.append(line) line = f.readline() return nlu ## TODO: with tools in",
"from sqlnet.dbengine import DBEngine from sqlova.utils.utils_wikisql import * from train import construct_hyper_param, get_models",
"max_seq_length, num_target_layers, path_db, dset_name, EG=False, beam_size=4): model.eval() model_bert.eval() # engine = DBEngine(os.path.join(path_db, f\"{dset_name}.db\"))",
"required=True, help='directory in which to place results') args = construct_hyper_param(parser) return args def",
"data if __name__ == '__main__': dset_name = 'qian' save_path = './Qian_data/' ### model",
"args = construct_hyper_param(parser) return args def load_models(args): BERT_PT_PATH = './data_and_model' path_model_bert = './model_bert_best.pt'",
"list of dict ### data_tables: dict nlu, nlu_t, tb, hds = [], [],",
"torch.utils.data.DataLoader( batch_size=args.bS, dataset=data, shuffle=False, num_workers=1, collate_fn=lambda x: x # now dictionary values are",
"(bert_config*.json etc)') # parser.add_argument(\"--data_path\", required=True, help='path to *.jsonl and *.db files') # parser.add_argument(\"--split\",",
"in enumerate(f): t1 = json.loads(line.strip()) table[t1['id']] = t1 return table def prepare_data(): sc_paths",
"pr_wn, pr_wc, pr_wo, pr_wvi = pred_sw_se(s_sc, s_sa, s_wn, s_wc, s_wo, s_wv, ) pr_wv_str,",
"s_wn, s_wc, s_wo, s_wv = model(wemb_n, l_n, wemb_h, l_hpu, l_hs) pr_sc, pr_sa, pr_wn,",
"= get_tables(tb_path) data = prepare_data() data_loader = torch.utils.data.DataLoader( batch_size=args.bS, dataset=data, shuffle=False, num_workers=1, collate_fn=lambda",
"use (e.g. model_best.pt)') # parser.add_argument(\"--bert_model_file\", required=True, help='bert model file to use (e.g. model_bert_best.pt)')",
"= prepare_data() data_loader = torch.utils.data.DataLoader( batch_size=args.bS, dataset=data, shuffle=False, num_workers=1, collate_fn=lambda x: x #",
"num_out_layers_n=num_target_layers, num_out_layers_h=num_target_layers) if not EG: # No Execution guided decoding s_sc, s_sa, s_wn,",
"my_get_fields(t, data_table) wemb_n, wemb_h, l_n, l_hpu, l_hs, \\ nlu_tt, t_to_tt_idx, tt_to_t_idx \\ =",
"required=True, help='model file to use (e.g. model_best.pt)') # parser.add_argument(\"--bert_model_file\", required=True, help='bert model file",
"= get_wemb_bert(bert_config, model_bert, tokenizer, nlu_t, hds, max_seq_length, num_out_layers_n=num_target_layers, num_out_layers_h=num_target_layers) if not EG: #",
"nlu_t[i], 'table_id': tbid[i], }) return data if __name__ == '__main__': dset_name = 'qian'",
"import pandas as pd import argparse import torch import json import os from",
"l_hs, \\ nlu_tt, t_to_tt_idx, tt_to_t_idx \\ = get_wemb_bert(bert_config, model_bert, tokenizer, nlu_t, hds, max_seq_length,",
"t1 = json.loads(line.strip()) table[t1['id']] = t1 return table def prepare_data(): sc_paths = [",
"beam_size=beam_size) # sort and generate pr_wc, pr_wo, pr_wv, pr_sql_i = sort_and_generate_pr_w(pr_sql_i) # Following",
"num_workers=1, collate_fn=lambda x: x # now dictionary values are not merged! ) ###",
"results') args = construct_hyper_param(parser) return args def load_models(args): BERT_PT_PATH = './data_and_model' path_model_bert =",
"= f.readline() while line: if line.endswith('\\n'): nlu.append(line[:-1]) else: nlu.append(line) line = f.readline() return",
"results1[\"query\"] = pr_sql_i1 results1[\"table_id\"] = tb[b][\"id\"] results1[\"nlu\"] = nlu[b] results1[\"sql\"] = pr_sql_q1 results.append(results1)",
"_, line in enumerate(f): t1 = json.loads(line.strip()) table[t1['id']] = t1 return table def",
"max_seq_length=args.max_seq_length, num_target_layers=args.num_target_layers, path_db=db_path, dset_name=dset_name, EG=False, #args.EG, ) # save results save_for_evaluation(save_path, results, dset_name)",
"s_wn, s_wc, s_wo, s_wv, ) pr_wv_str, pr_wv_str_wp = convert_pr_wvi_to_string(pr_wvi, nlu_t, nlu_tt, tt_to_t_idx, nlu)",
"hds = [], [], [], [] for t1 in t: nlu.append( t1['question']) nlu_t.append(",
"= './Qian_data/' ### model args = get_args() model, model_bert, tokenizer, bert_config = load_models(args)",
"dev)') # parser.add_argument(\"--result_path\", required=True, help='directory in which to place results') args = construct_hyper_param(parser)",
"results1[\"sql\"] = pr_sql_q1 results.append(results1) return results #### deal with data ################### ## 不需要了",
"guided decoding s_sc, s_sa, s_wn, s_wc, s_wo, s_wv = model(wemb_n, l_n, wemb_h, l_hpu,",
"tokenizer, nlu_t, hds, max_seq_length, num_out_layers_n=num_target_layers, num_out_layers_h=num_target_layers) if not EG: # No Execution guided",
"'qian' save_path = './Qian_data/' ### model args = get_args() model, model_bert, tokenizer, bert_config",
"sc_paths = [ './Qian_data/company_script.txt', './Qian_data/product_script.txt',] sc_tableids = [ 'company_table', 'product_table',] nlu = []",
"if line.endswith('\\n'): nlu.append(line[:-1]) else: nlu.append(line) line = f.readline() return nlu ## TODO: with",
"= json.loads(line.strip()) table[t1['id']] = t1 return table def prepare_data(): sc_paths = [ './Qian_data/company_script.txt',",
"split_scripts(nlu_i) nlu.extend(nlu_i) nlu_t.extend(nlu_t_i) tbid.extend([sc_tableids[i]] * len(nlu_i)) data = [] for i in range(len(nlu)):",
"construct_hyper_param(parser) return args def load_models(args): BERT_PT_PATH = './data_and_model' path_model_bert = './model_bert_best.pt' path_model =",
"model_bert, bert_config, tokenizer, max_seq_length, num_target_layers, path_db, dset_name, EG=False, beam_size=4): model.eval() model_bert.eval() # engine",
"l_hs) pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi = pred_sw_se(s_sc, s_sa, s_wn, s_wc, s_wo,",
") ### predict with torch.no_grad(): results = my_predict(data_loader, data_table, model, model_bert, bert_config, tokenizer,",
"x # now dictionary values are not merged! ) ### predict with torch.no_grad():",
"DBEngine from sqlova.utils.utils_wikisql import * from train import construct_hyper_param, get_models #### prediction ####################",
"required=True, help='path to *.jsonl and *.db files') # parser.add_argument(\"--split\", required=True, help='prefix of jsonl",
"model.eval() model_bert.eval() # engine = DBEngine(os.path.join(path_db, f\"{dset_name}.db\")) engine = DBEngine(path_db) results = []",
"csv_path.split('/')[-1][:-4] df = pd.read_csv(csv_path) headers = df.columns.tolist() rows = [] for _, row",
"### model args = get_args() model, model_bert, tokenizer, bert_config = load_models(args) ### data",
"= get_models(args, BERT_PT_PATH, True, path_model_bert, path_model) return model, model_bert, tokenizer, bert_config def my_get_fields(t,",
"model(wemb_n, l_n, wemb_h, l_hpu, l_hs) pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi = pred_sw_se(s_sc,",
"[] tbid = [] for i in range(len(sc_paths)): nlu_i = read_scripts(sc_paths[i]) nlu_t_i =",
"nlu[i], 'question_tok': nlu_t[i], 'table_id': tbid[i], }) return data if __name__ == '__main__': dset_name",
"{} with open(tb_path) as f: for _, line in enumerate(f): t1 = json.loads(line.strip())",
"s_wv = model(wemb_n, l_n, wemb_h, l_hpu, l_hs) pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi",
"nlu, nlu_t, tb, hds = my_get_fields(t, data_table) wemb_n, wemb_h, l_n, l_hpu, l_hs, \\",
"## 不需要了 def read_csv_to_table(csv_path): # file_name as table_id table_id = csv_path.split('/')[-1][:-4] df =",
"annotate_ws.py def split_scripts(nlu): nlu_t = [] for nlu1 in nlu: nlu_t.append(nlu1.split(' ')) return",
"rows.append(row.tolist()) print(rows) ## TODO: add_csv def create_table_and_db(): pass def read_scripts(txt_path): nlu = []",
"= './Qian_data/qian.db' tb_path = './Qian_data/qian.tables.jsonl' data_table = get_tables(tb_path) data = prepare_data() data_loader =",
"Following variables are just for consistency with no-EG case. pr_wvi = None #",
"for consistency with no-EG case. pr_wvi = None # not used pr_wv_str=None pr_wv_str_wp=None",
"bert_config def my_get_fields(t, data_tables): ### t: list of dict ### data_tables: dict nlu,",
"t1['question']) nlu_t.append( t1['question_tok']) tbid = t1['table_id'] tb.append(data_tables[tbid]) hds.append(data_tables[tbid]['header']) return nlu, nlu_t, tb, hds",
"path_model) return model, model_bert, tokenizer, bert_config def my_get_fields(t, data_tables): ### t: list of",
"split_scripts(nlu): nlu_t = [] for nlu1 in nlu: nlu_t.append(nlu1.split(' ')) return nlu_t def",
"s_sa, s_wn, s_wc, s_wo, s_wv, ) pr_wv_str, pr_wv_str_wp = convert_pr_wvi_to_string(pr_wvi, nlu_t, nlu_tt, tt_to_t_idx,",
"to bert files (bert_config*.json etc)') # parser.add_argument(\"--data_path\", required=True, help='path to *.jsonl and *.db",
"= [], [], [], [] for t1 in t: nlu.append( t1['question']) nlu_t.append( t1['question_tok'])",
"tb, nlu_t, nlu_tt, tt_to_t_idx, nlu, beam_size=beam_size) # sort and generate pr_wc, pr_wo, pr_wv,",
"get_wemb_bert(bert_config, model_bert, tokenizer, nlu_t, hds, max_seq_length, num_out_layers_n=num_target_layers, num_out_layers_h=num_target_layers) if not EG: # No",
"EG: # No Execution guided decoding s_sc, s_sa, s_wn, s_wc, s_wo, s_wv =",
"'./Qian_data/qian.tables.jsonl' data_table = get_tables(tb_path) data = prepare_data() data_loader = torch.utils.data.DataLoader( batch_size=args.bS, dataset=data, shuffle=False,",
"\\ nlu_tt, t_to_tt_idx, tt_to_t_idx \\ = get_wemb_bert(bert_config, model_bert, tokenizer, nlu_t, hds, max_seq_length, num_out_layers_n=num_target_layers,",
"### t: list of dict ### data_tables: dict nlu, nlu_t, tb, hds =",
"guided decoding prob_sca, prob_w, prob_wn_w, \\ pr_sc, pr_sa, pr_wn, pr_sql_i \\ = model.beam_forward(wemb_n,",
"df = pd.read_csv(csv_path) headers = df.columns.tolist() rows = [] for _, row in",
"(pr_sql_i1, pr_sql_q1) in enumerate(zip(pr_sql_i, pr_sql_q)): results1 = {} results1[\"query\"] = pr_sql_i1 results1[\"table_id\"] =",
"beam_size=4): model.eval() model_bert.eval() # engine = DBEngine(os.path.join(path_db, f\"{dset_name}.db\")) engine = DBEngine(path_db) results =",
"headers = df.columns.tolist() rows = [] for _, row in df.iterrows(): rows.append(row.tolist()) print(rows)",
"with data ################### ## 不需要了 def read_csv_to_table(csv_path): # file_name as table_id table_id =",
"sc_tableids = [ 'company_table', 'product_table',] nlu = [] nlu_t = [] tbid =",
"add_csv def create_table_and_db(): pass def read_scripts(txt_path): nlu = [] with open(txt_path, 'r') as",
"help='path to bert files (bert_config*.json etc)') # parser.add_argument(\"--data_path\", required=True, help='path to *.jsonl and",
"nlu_tt, tt_to_t_idx, nlu, beam_size=beam_size) # sort and generate pr_wc, pr_wo, pr_wv, pr_sql_i =",
"path_model = './model_best.pt' model, model_bert, tokenizer, bert_config = get_models(args, BERT_PT_PATH, True, path_model_bert, path_model)",
"nlu_t def get_tables(tb_path): table = {} with open(tb_path) as f: for _, line",
") pr_wv_str, pr_wv_str_wp = convert_pr_wvi_to_string(pr_wvi, nlu_t, nlu_tt, tt_to_t_idx, nlu) pr_sql_i = generate_sql_i(pr_sc, pr_sa,",
"read_scripts(sc_paths[i]) nlu_t_i = split_scripts(nlu_i) nlu.extend(nlu_i) nlu_t.extend(nlu_t_i) tbid.extend([sc_tableids[i]] * len(nlu_i)) data = [] for",
"tokenizer, bert_config = load_models(args) ### data db_path = './Qian_data/qian.db' tb_path = './Qian_data/qian.tables.jsonl' data_table",
"line.endswith('\\n'): nlu.append(line[:-1]) else: nlu.append(line) line = f.readline() return nlu ## TODO: with tools",
"data_table) wemb_n, wemb_h, l_n, l_hpu, l_hs, \\ nlu_tt, t_to_tt_idx, tt_to_t_idx \\ = get_wemb_bert(bert_config,",
"required=True, help='prefix of jsonl and db files (e.g. dev)') # parser.add_argument(\"--result_path\", required=True, help='directory",
"pr_wc, pr_wo, pr_wv_str, nlu) else: # Execution guided decoding prob_sca, prob_w, prob_wn_w, \\",
"convert_pr_wvi_to_string(pr_wvi, nlu_t, nlu_tt, tt_to_t_idx, nlu) pr_sql_i = generate_sql_i(pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wv_str,",
"# parser.add_argument(\"--bert_model_file\", required=True, help='bert model file to use (e.g. model_bert_best.pt)') # parser.add_argument(\"--bert_path\", required=True,",
"nlu_t.append(nlu1.split(' ')) return nlu_t def get_tables(tb_path): table = {} with open(tb_path) as f:",
"= construct_hyper_param(parser) return args def load_models(args): BERT_PT_PATH = './data_and_model' path_model_bert = './model_bert_best.pt' path_model",
"= pr_sql_i1 results1[\"table_id\"] = tb[b][\"id\"] results1[\"nlu\"] = nlu[b] results1[\"sql\"] = pr_sql_q1 results.append(results1) return",
"json.loads(line.strip()) table[t1['id']] = t1 return table def prepare_data(): sc_paths = [ './Qian_data/company_script.txt', './Qian_data/product_script.txt',]",
"with tools in annotate_ws.py def split_scripts(nlu): nlu_t = [] for nlu1 in nlu:",
"Execution guided decoding prob_sca, prob_w, prob_wn_w, \\ pr_sc, pr_sa, pr_wn, pr_sql_i \\ =",
"tb[b][\"id\"] results1[\"nlu\"] = nlu[b] results1[\"sql\"] = pr_sql_q1 results.append(results1) return results #### deal with",
"pr_sa, pr_wn, pr_sql_i \\ = model.beam_forward(wemb_n, l_n, wemb_h, l_hpu, l_hs, engine, tb, nlu_t,",
"[] for i in range(len(nlu)): data.append({ 'question': nlu[i], 'question_tok': nlu_t[i], 'table_id': tbid[i], })",
"model_bert, tokenizer, nlu_t, hds, max_seq_length, num_out_layers_n=num_target_layers, num_out_layers_h=num_target_layers) if not EG: # No Execution",
"table def prepare_data(): sc_paths = [ './Qian_data/company_script.txt', './Qian_data/product_script.txt',] sc_tableids = [ 'company_table', 'product_table',]",
"= [] for _, t in enumerate(data_loader): nlu, nlu_t, tb, hds = my_get_fields(t,",
"= model(wemb_n, l_n, wemb_h, l_hpu, l_hs) pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi =",
"tt_to_t_idx, nlu) pr_sql_i = generate_sql_i(pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wv_str, nlu) else: #",
"pr_wv_str_wp = convert_pr_wvi_to_string(pr_wvi, nlu_t, nlu_tt, tt_to_t_idx, nlu) pr_sql_i = generate_sql_i(pr_sc, pr_sa, pr_wn, pr_wc,",
"'./Qian_data/qian.db' tb_path = './Qian_data/qian.tables.jsonl' data_table = get_tables(tb_path) data = prepare_data() data_loader = torch.utils.data.DataLoader(",
"import os from add_csv import csv_to_sqlite, csv_to_json from sqlnet.dbengine import DBEngine from sqlova.utils.utils_wikisql",
"line: if line.endswith('\\n'): nlu.append(line[:-1]) else: nlu.append(line) line = f.readline() return nlu ## TODO:",
"= t1['table_id'] tb.append(data_tables[tbid]) hds.append(data_tables[tbid]['header']) return nlu, nlu_t, tb, hds def my_predict( data_loader, data_table,",
"_, row in df.iterrows(): rows.append(row.tolist()) print(rows) ## TODO: add_csv def create_table_and_db(): pass def",
"table = {} with open(tb_path) as f: for _, line in enumerate(f): t1",
"= None # not used pr_wv_str=None pr_wv_str_wp=None pr_sql_q = generate_sql_q(pr_sql_i, tb) for b,",
"get_tables(tb_path): table = {} with open(tb_path) as f: for _, line in enumerate(f):",
"else: nlu.append(line) line = f.readline() return nlu ## TODO: with tools in annotate_ws.py",
"wemb_h, l_hpu, l_hs, engine, tb, nlu_t, nlu_tt, tt_to_t_idx, nlu, beam_size=beam_size) # sort and",
"def split_scripts(nlu): nlu_t = [] for nlu1 in nlu: nlu_t.append(nlu1.split(' ')) return nlu_t",
"get_models(args, BERT_PT_PATH, True, path_model_bert, path_model) return model, model_bert, tokenizer, bert_config def my_get_fields(t, data_tables):",
"wemb_h, l_n, l_hpu, l_hs, \\ nlu_tt, t_to_tt_idx, tt_to_t_idx \\ = get_wemb_bert(bert_config, model_bert, tokenizer,",
"nlu_t.append( t1['question_tok']) tbid = t1['table_id'] tb.append(data_tables[tbid]) hds.append(data_tables[tbid]['header']) return nlu, nlu_t, tb, hds def",
"= './Qian_data/qian.tables.jsonl' data_table = get_tables(tb_path) data = prepare_data() data_loader = torch.utils.data.DataLoader( batch_size=args.bS, dataset=data,",
"path_model_bert = './model_bert_best.pt' path_model = './model_best.pt' model, model_bert, tokenizer, bert_config = get_models(args, BERT_PT_PATH,",
"read_scripts(txt_path): nlu = [] with open(txt_path, 'r') as f: line = f.readline() while",
"= my_predict(data_loader, data_table, model, model_bert, bert_config, tokenizer, max_seq_length=args.max_seq_length, num_target_layers=args.num_target_layers, path_db=db_path, dset_name=dset_name, EG=False, #args.EG,",
"model_bert.eval() # engine = DBEngine(os.path.join(path_db, f\"{dset_name}.db\")) engine = DBEngine(path_db) results = [] for",
"pr_wn, pr_wc, pr_wo, pr_wv_str, nlu) else: # Execution guided decoding prob_sca, prob_w, prob_wn_w,",
"data = [] for i in range(len(nlu)): data.append({ 'question': nlu[i], 'question_tok': nlu_t[i], 'table_id':",
"model_bert, bert_config, tokenizer, max_seq_length=args.max_seq_length, num_target_layers=args.num_target_layers, path_db=db_path, dset_name=dset_name, EG=False, #args.EG, ) # save results",
"[] for _, row in df.iterrows(): rows.append(row.tolist()) print(rows) ## TODO: add_csv def create_table_and_db():",
"= f.readline() return nlu ## TODO: with tools in annotate_ws.py def split_scripts(nlu): nlu_t",
"table_id = csv_path.split('/')[-1][:-4] df = pd.read_csv(csv_path) headers = df.columns.tolist() rows = [] for",
"= t1 return table def prepare_data(): sc_paths = [ './Qian_data/company_script.txt', './Qian_data/product_script.txt',] sc_tableids =",
"print(rows) ## TODO: add_csv def create_table_and_db(): pass def read_scripts(txt_path): nlu = [] with",
"pr_sa, pr_wn, pr_wc, pr_wo, pr_wv_str, nlu) else: # Execution guided decoding prob_sca, prob_w,",
"now dictionary values are not merged! ) ### predict with torch.no_grad(): results =",
"nlu = [] with open(txt_path, 'r') as f: line = f.readline() while line:",
"add_csv import csv_to_sqlite, csv_to_json from sqlnet.dbengine import DBEngine from sqlova.utils.utils_wikisql import * from",
"}) return data if __name__ == '__main__': dset_name = 'qian' save_path = './Qian_data/'",
"= tb[b][\"id\"] results1[\"nlu\"] = nlu[b] results1[\"sql\"] = pr_sql_q1 results.append(results1) return results #### deal",
"argparse import torch import json import os from add_csv import csv_to_sqlite, csv_to_json from",
"return nlu ## TODO: with tools in annotate_ws.py def split_scripts(nlu): nlu_t = []",
"return results #### deal with data ################### ## 不需要了 def read_csv_to_table(csv_path): # file_name",
"t1 in t: nlu.append( t1['question']) nlu_t.append( t1['question_tok']) tbid = t1['table_id'] tb.append(data_tables[tbid]) hds.append(data_tables[tbid]['header']) return",
"os from add_csv import csv_to_sqlite, csv_to_json from sqlnet.dbengine import DBEngine from sqlova.utils.utils_wikisql import",
"args def load_models(args): BERT_PT_PATH = './data_and_model' path_model_bert = './model_bert_best.pt' path_model = './model_best.pt' model,",
"tb, hds = [], [], [], [] for t1 in t: nlu.append( t1['question'])",
"#### deal with data ################### ## 不需要了 def read_csv_to_table(csv_path): # file_name as table_id",
"'question': nlu[i], 'question_tok': nlu_t[i], 'table_id': tbid[i], }) return data if __name__ == '__main__':",
"in range(len(nlu)): data.append({ 'question': nlu[i], 'question_tok': nlu_t[i], 'table_id': tbid[i], }) return data if",
"pr_wo, pr_wv_str, nlu) else: # Execution guided decoding prob_sca, prob_w, prob_wn_w, \\ pr_sc,",
"l_hpu, l_hs, engine, tb, nlu_t, nlu_tt, tt_to_t_idx, nlu, beam_size=beam_size) # sort and generate",
"pr_wv_str=None pr_wv_str_wp=None pr_sql_q = generate_sql_q(pr_sql_i, tb) for b, (pr_sql_i1, pr_sql_q1) in enumerate(zip(pr_sql_i, pr_sql_q)):",
"nlu1 in nlu: nlu_t.append(nlu1.split(' ')) return nlu_t def get_tables(tb_path): table = {} with",
"model, model_bert, bert_config, tokenizer, max_seq_length=args.max_seq_length, num_target_layers=args.num_target_layers, path_db=db_path, dset_name=dset_name, EG=False, #args.EG, ) # save",
"nlu_i = read_scripts(sc_paths[i]) nlu_t_i = split_scripts(nlu_i) nlu.extend(nlu_i) nlu_t.extend(nlu_t_i) tbid.extend([sc_tableids[i]] * len(nlu_i)) data =",
"# now dictionary values are not merged! ) ### predict with torch.no_grad(): results",
"import * from train import construct_hyper_param, get_models #### prediction #################### def get_args(): parser",
"model args = get_args() model, model_bert, tokenizer, bert_config = load_models(args) ### data db_path",
"required=True, help='path to bert files (bert_config*.json etc)') # parser.add_argument(\"--data_path\", required=True, help='path to *.jsonl",
"are not merged! ) ### predict with torch.no_grad(): results = my_predict(data_loader, data_table, model,",
"[] for _, t in enumerate(data_loader): nlu, nlu_t, tb, hds = my_get_fields(t, data_table)",
"with open(tb_path) as f: for _, line in enumerate(f): t1 = json.loads(line.strip()) table[t1['id']]",
"= torch.utils.data.DataLoader( batch_size=args.bS, dataset=data, shuffle=False, num_workers=1, collate_fn=lambda x: x # now dictionary values",
"= [] for _, row in df.iterrows(): rows.append(row.tolist()) print(rows) ## TODO: add_csv def",
"in which to place results') args = construct_hyper_param(parser) return args def load_models(args): BERT_PT_PATH",
"model_bert, tokenizer, bert_config = get_models(args, BERT_PT_PATH, True, path_model_bert, path_model) return model, model_bert, tokenizer,",
"if not EG: # No Execution guided decoding s_sc, s_sa, s_wn, s_wc, s_wo,",
"nlu_t, nlu_tt, tt_to_t_idx, nlu, beam_size=beam_size) # sort and generate pr_wc, pr_wo, pr_wv, pr_sql_i",
"None # not used pr_wv_str=None pr_wv_str_wp=None pr_sql_q = generate_sql_q(pr_sql_i, tb) for b, (pr_sql_i1,",
"pandas as pd import argparse import torch import json import os from add_csv",
"model_bert_best.pt)') # parser.add_argument(\"--bert_path\", required=True, help='path to bert files (bert_config*.json etc)') # parser.add_argument(\"--data_path\", required=True,",
"file to use (e.g. model_bert_best.pt)') # parser.add_argument(\"--bert_path\", required=True, help='path to bert files (bert_config*.json",
"data_table = get_tables(tb_path) data = prepare_data() data_loader = torch.utils.data.DataLoader( batch_size=args.bS, dataset=data, shuffle=False, num_workers=1,",
"from sqlova.utils.utils_wikisql import * from train import construct_hyper_param, get_models #### prediction #################### def",
"'r') as f: line = f.readline() while line: if line.endswith('\\n'): nlu.append(line[:-1]) else: nlu.append(line)",
"i in range(len(sc_paths)): nlu_i = read_scripts(sc_paths[i]) nlu_t_i = split_scripts(nlu_i) nlu.extend(nlu_i) nlu_t.extend(nlu_t_i) tbid.extend([sc_tableids[i]] *",
"= [] for i in range(len(nlu)): data.append({ 'question': nlu[i], 'question_tok': nlu_t[i], 'table_id': tbid[i],",
"# Following variables are just for consistency with no-EG case. pr_wvi = None",
"consistency with no-EG case. pr_wvi = None # not used pr_wv_str=None pr_wv_str_wp=None pr_sql_q",
"data = prepare_data() data_loader = torch.utils.data.DataLoader( batch_size=args.bS, dataset=data, shuffle=False, num_workers=1, collate_fn=lambda x: x",
"nlu_t, tb, hds = [], [], [], [] for t1 in t: nlu.append(",
"data_tables: dict nlu, nlu_t, tb, hds = [], [], [], [] for t1",
"decoding prob_sca, prob_w, prob_wn_w, \\ pr_sc, pr_sa, pr_wn, pr_sql_i \\ = model.beam_forward(wemb_n, l_n,",
"model file to use (e.g. model_bert_best.pt)') # parser.add_argument(\"--bert_path\", required=True, help='path to bert files",
"to use (e.g. model_best.pt)') # parser.add_argument(\"--bert_model_file\", required=True, help='bert model file to use (e.g.",
"def my_predict( data_loader, data_table, model, model_bert, bert_config, tokenizer, max_seq_length, num_target_layers, path_db, dset_name, EG=False,",
"s_sa, s_wn, s_wc, s_wo, s_wv = model(wemb_n, l_n, wemb_h, l_hpu, l_hs) pr_sc, pr_sa,",
"TODO: with tools in annotate_ws.py def split_scripts(nlu): nlu_t = [] for nlu1 in",
"tt_to_t_idx \\ = get_wemb_bert(bert_config, model_bert, tokenizer, nlu_t, hds, max_seq_length, num_out_layers_n=num_target_layers, num_out_layers_h=num_target_layers) if not",
"No Execution guided decoding s_sc, s_sa, s_wn, s_wc, s_wo, s_wv = model(wemb_n, l_n,",
"in df.iterrows(): rows.append(row.tolist()) print(rows) ## TODO: add_csv def create_table_and_db(): pass def read_scripts(txt_path): nlu",
"data.append({ 'question': nlu[i], 'question_tok': nlu_t[i], 'table_id': tbid[i], }) return data if __name__ ==",
"bert files (bert_config*.json etc)') # parser.add_argument(\"--data_path\", required=True, help='path to *.jsonl and *.db files')",
"for _, t in enumerate(data_loader): nlu, nlu_t, tb, hds = my_get_fields(t, data_table) wemb_n,",
"= pred_sw_se(s_sc, s_sa, s_wn, s_wc, s_wo, s_wv, ) pr_wv_str, pr_wv_str_wp = convert_pr_wvi_to_string(pr_wvi, nlu_t,",
"dict ### data_tables: dict nlu, nlu_t, tb, hds = [], [], [], []",
"def prepare_data(): sc_paths = [ './Qian_data/company_script.txt', './Qian_data/product_script.txt',] sc_tableids = [ 'company_table', 'product_table',] nlu",
"l_hpu, l_hs, \\ nlu_tt, t_to_tt_idx, tt_to_t_idx \\ = get_wemb_bert(bert_config, model_bert, tokenizer, nlu_t, hds,",
"for t1 in t: nlu.append( t1['question']) nlu_t.append( t1['question_tok']) tbid = t1['table_id'] tb.append(data_tables[tbid]) hds.append(data_tables[tbid]['header'])",
"torch.no_grad(): results = my_predict(data_loader, data_table, model, model_bert, bert_config, tokenizer, max_seq_length=args.max_seq_length, num_target_layers=args.num_target_layers, path_db=db_path, dset_name=dset_name,",
"l_hpu, l_hs) pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi = pred_sw_se(s_sc, s_sa, s_wn, s_wc,",
"= csv_path.split('/')[-1][:-4] df = pd.read_csv(csv_path) headers = df.columns.tolist() rows = [] for _,",
"prob_sca, prob_w, prob_wn_w, \\ pr_sc, pr_sa, pr_wn, pr_sql_i \\ = model.beam_forward(wemb_n, l_n, wemb_h,",
"to place results') args = construct_hyper_param(parser) return args def load_models(args): BERT_PT_PATH = './data_and_model'",
"bert_config = load_models(args) ### data db_path = './Qian_data/qian.db' tb_path = './Qian_data/qian.tables.jsonl' data_table =",
"= {} results1[\"query\"] = pr_sql_i1 results1[\"table_id\"] = tb[b][\"id\"] results1[\"nlu\"] = nlu[b] results1[\"sql\"] =",
"hds.append(data_tables[tbid]['header']) return nlu, nlu_t, tb, hds def my_predict( data_loader, data_table, model, model_bert, bert_config,",
"pr_wv, pr_sql_i = sort_and_generate_pr_w(pr_sql_i) # Following variables are just for consistency with no-EG",
"'./model_bert_best.pt' path_model = './model_best.pt' model, model_bert, tokenizer, bert_config = get_models(args, BERT_PT_PATH, True, path_model_bert,",
"enumerate(zip(pr_sql_i, pr_sql_q)): results1 = {} results1[\"query\"] = pr_sql_i1 results1[\"table_id\"] = tb[b][\"id\"] results1[\"nlu\"] =",
"and generate pr_wc, pr_wo, pr_wv, pr_sql_i = sort_and_generate_pr_w(pr_sql_i) # Following variables are just",
"decoding s_sc, s_sa, s_wn, s_wc, s_wo, s_wv = model(wemb_n, l_n, wemb_h, l_hpu, l_hs)",
"case. pr_wvi = None # not used pr_wv_str=None pr_wv_str_wp=None pr_sql_q = generate_sql_q(pr_sql_i, tb)",
"files (bert_config*.json etc)') # parser.add_argument(\"--data_path\", required=True, help='path to *.jsonl and *.db files') #",
"= [] for i in range(len(sc_paths)): nlu_i = read_scripts(sc_paths[i]) nlu_t_i = split_scripts(nlu_i) nlu.extend(nlu_i)",
"num_target_layers, path_db, dset_name, EG=False, beam_size=4): model.eval() model_bert.eval() # engine = DBEngine(os.path.join(path_db, f\"{dset_name}.db\")) engine",
"in annotate_ws.py def split_scripts(nlu): nlu_t = [] for nlu1 in nlu: nlu_t.append(nlu1.split(' '))",
"nlu, nlu_t, tb, hds = [], [], [], [] for t1 in t:",
"as f: for _, line in enumerate(f): t1 = json.loads(line.strip()) table[t1['id']] = t1",
"predict with torch.no_grad(): results = my_predict(data_loader, data_table, model, model_bert, bert_config, tokenizer, max_seq_length=args.max_seq_length, num_target_layers=args.num_target_layers,",
"path_db, dset_name, EG=False, beam_size=4): model.eval() model_bert.eval() # engine = DBEngine(os.path.join(path_db, f\"{dset_name}.db\")) engine =",
"pr_wc, pr_wo, pr_wvi = pred_sw_se(s_sc, s_sa, s_wn, s_wc, s_wo, s_wv, ) pr_wv_str, pr_wv_str_wp",
"Execution guided decoding s_sc, s_sa, s_wn, s_wc, s_wo, s_wv = model(wemb_n, l_n, wemb_h,",
"f.readline() return nlu ## TODO: with tools in annotate_ws.py def split_scripts(nlu): nlu_t =",
"DBEngine(path_db) results = [] for _, t in enumerate(data_loader): nlu, nlu_t, tb, hds",
"range(len(sc_paths)): nlu_i = read_scripts(sc_paths[i]) nlu_t_i = split_scripts(nlu_i) nlu.extend(nlu_i) nlu_t.extend(nlu_t_i) tbid.extend([sc_tableids[i]] * len(nlu_i)) data",
"s_wo, s_wv, ) pr_wv_str, pr_wv_str_wp = convert_pr_wvi_to_string(pr_wvi, nlu_t, nlu_tt, tt_to_t_idx, nlu) pr_sql_i =",
"db files (e.g. dev)') # parser.add_argument(\"--result_path\", required=True, help='directory in which to place results')",
"nlu.extend(nlu_i) nlu_t.extend(nlu_t_i) tbid.extend([sc_tableids[i]] * len(nlu_i)) data = [] for i in range(len(nlu)): data.append({",
"numpy as np import pandas as pd import argparse import torch import json",
"argparse.ArgumentParser() # parser.add_argument(\"--model_file\", required=True, help='model file to use (e.g. model_best.pt)') # parser.add_argument(\"--bert_model_file\", required=True,",
"results1[\"nlu\"] = nlu[b] results1[\"sql\"] = pr_sql_q1 results.append(results1) return results #### deal with data",
"results1 = {} results1[\"query\"] = pr_sql_i1 results1[\"table_id\"] = tb[b][\"id\"] results1[\"nlu\"] = nlu[b] results1[\"sql\"]",
"as table_id table_id = csv_path.split('/')[-1][:-4] df = pd.read_csv(csv_path) headers = df.columns.tolist() rows =",
"for _, line in enumerate(f): t1 = json.loads(line.strip()) table[t1['id']] = t1 return table",
"nlu_t, nlu_tt, tt_to_t_idx, nlu) pr_sql_i = generate_sql_i(pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wv_str, nlu)",
"from train import construct_hyper_param, get_models #### prediction #################### def get_args(): parser = argparse.ArgumentParser()",
"f: for _, line in enumerate(f): t1 = json.loads(line.strip()) table[t1['id']] = t1 return",
"= convert_pr_wvi_to_string(pr_wvi, nlu_t, nlu_tt, tt_to_t_idx, nlu) pr_sql_i = generate_sql_i(pr_sc, pr_sa, pr_wn, pr_wc, pr_wo,",
"model, model_bert, tokenizer, bert_config = load_models(args) ### data db_path = './Qian_data/qian.db' tb_path =",
"def read_scripts(txt_path): nlu = [] with open(txt_path, 'r') as f: line = f.readline()",
"model.beam_forward(wemb_n, l_n, wemb_h, l_hpu, l_hs, engine, tb, nlu_t, nlu_tt, tt_to_t_idx, nlu, beam_size=beam_size) #",
"jsonl and db files (e.g. dev)') # parser.add_argument(\"--result_path\", required=True, help='directory in which to",
"# parser.add_argument(\"--model_file\", required=True, help='model file to use (e.g. model_best.pt)') # parser.add_argument(\"--bert_model_file\", required=True, help='bert",
"nlu_t, tb, hds def my_predict( data_loader, data_table, model, model_bert, bert_config, tokenizer, max_seq_length, num_target_layers,",
"prob_w, prob_wn_w, \\ pr_sc, pr_sa, pr_wn, pr_sql_i \\ = model.beam_forward(wemb_n, l_n, wemb_h, l_hpu,",
"help='path to *.jsonl and *.db files') # parser.add_argument(\"--split\", required=True, help='prefix of jsonl and",
"pr_wv_str, pr_wv_str_wp = convert_pr_wvi_to_string(pr_wvi, nlu_t, nlu_tt, tt_to_t_idx, nlu) pr_sql_i = generate_sql_i(pr_sc, pr_sa, pr_wn,",
"[ './Qian_data/company_script.txt', './Qian_data/product_script.txt',] sc_tableids = [ 'company_table', 'product_table',] nlu = [] nlu_t =",
"= generate_sql_i(pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wv_str, nlu) else: # Execution guided decoding",
"help='model file to use (e.g. model_best.pt)') # parser.add_argument(\"--bert_model_file\", required=True, help='bert model file to",
"data_loader = torch.utils.data.DataLoader( batch_size=args.bS, dataset=data, shuffle=False, num_workers=1, collate_fn=lambda x: x # now dictionary",
"bert_config, tokenizer, max_seq_length, num_target_layers, path_db, dset_name, EG=False, beam_size=4): model.eval() model_bert.eval() # engine =",
"tb_path = './Qian_data/qian.tables.jsonl' data_table = get_tables(tb_path) data = prepare_data() data_loader = torch.utils.data.DataLoader( batch_size=args.bS,",
"f: line = f.readline() while line: if line.endswith('\\n'): nlu.append(line[:-1]) else: nlu.append(line) line =",
"get_models #### prediction #################### def get_args(): parser = argparse.ArgumentParser() # parser.add_argument(\"--model_file\", required=True, help='model",
"= pd.read_csv(csv_path) headers = df.columns.tolist() rows = [] for _, row in df.iterrows():",
"for nlu1 in nlu: nlu_t.append(nlu1.split(' ')) return nlu_t def get_tables(tb_path): table = {}",
"= pr_sql_q1 results.append(results1) return results #### deal with data ################### ## 不需要了 def",
"create_table_and_db(): pass def read_scripts(txt_path): nlu = [] with open(txt_path, 'r') as f: line",
"[] for i in range(len(sc_paths)): nlu_i = read_scripts(sc_paths[i]) nlu_t_i = split_scripts(nlu_i) nlu.extend(nlu_i) nlu_t.extend(nlu_t_i)",
"help='directory in which to place results') args = construct_hyper_param(parser) return args def load_models(args):",
"open(txt_path, 'r') as f: line = f.readline() while line: if line.endswith('\\n'): nlu.append(line[:-1]) else:",
"return args def load_models(args): BERT_PT_PATH = './data_and_model' path_model_bert = './model_bert_best.pt' path_model = './model_best.pt'",
"construct_hyper_param, get_models #### prediction #################### def get_args(): parser = argparse.ArgumentParser() # parser.add_argument(\"--model_file\", required=True,",
"t: list of dict ### data_tables: dict nlu, nlu_t, tb, hds = [],",
"= split_scripts(nlu_i) nlu.extend(nlu_i) nlu_t.extend(nlu_t_i) tbid.extend([sc_tableids[i]] * len(nlu_i)) data = [] for i in",
"= DBEngine(os.path.join(path_db, f\"{dset_name}.db\")) engine = DBEngine(path_db) results = [] for _, t in",
"datetime import timedelta import numpy as np import pandas as pd import argparse",
"tb, hds = my_get_fields(t, data_table) wemb_n, wemb_h, l_n, l_hpu, l_hs, \\ nlu_tt, t_to_tt_idx,",
"l_n, wemb_h, l_hpu, l_hs, engine, tb, nlu_t, nlu_tt, tt_to_t_idx, nlu, beam_size=beam_size) # sort",
"tbid = t1['table_id'] tb.append(data_tables[tbid]) hds.append(data_tables[tbid]['header']) return nlu, nlu_t, tb, hds def my_predict( data_loader,",
"'./Qian_data/product_script.txt',] sc_tableids = [ 'company_table', 'product_table',] nlu = [] nlu_t = [] tbid",
"files') # parser.add_argument(\"--split\", required=True, help='prefix of jsonl and db files (e.g. dev)') #",
"data_table, model, model_bert, bert_config, tokenizer, max_seq_length, num_target_layers, path_db, dset_name, EG=False, beam_size=4): model.eval() model_bert.eval()",
"pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi = pred_sw_se(s_sc, s_sa, s_wn, s_wc, s_wo, s_wv,",
"[] nlu_t = [] tbid = [] for i in range(len(sc_paths)): nlu_i =",
"to *.jsonl and *.db files') # parser.add_argument(\"--split\", required=True, help='prefix of jsonl and db",
"files (e.g. dev)') # parser.add_argument(\"--result_path\", required=True, help='directory in which to place results') args",
"tools in annotate_ws.py def split_scripts(nlu): nlu_t = [] for nlu1 in nlu: nlu_t.append(nlu1.split('",
"pr_sql_q)): results1 = {} results1[\"query\"] = pr_sql_i1 results1[\"table_id\"] = tb[b][\"id\"] results1[\"nlu\"] = nlu[b]",
"s_wo, s_wv = model(wemb_n, l_n, wemb_h, l_hpu, l_hs) pr_sc, pr_sa, pr_wn, pr_wc, pr_wo,",
"in t: nlu.append( t1['question']) nlu_t.append( t1['question_tok']) tbid = t1['table_id'] tb.append(data_tables[tbid]) hds.append(data_tables[tbid]['header']) return nlu,",
"nlu) else: # Execution guided decoding prob_sca, prob_w, prob_wn_w, \\ pr_sc, pr_sa, pr_wn,",
"pr_sql_i1 results1[\"table_id\"] = tb[b][\"id\"] results1[\"nlu\"] = nlu[b] results1[\"sql\"] = pr_sql_q1 results.append(results1) return results",
"range(len(nlu)): data.append({ 'question': nlu[i], 'question_tok': nlu_t[i], 'table_id': tbid[i], }) return data if __name__",
"with no-EG case. pr_wvi = None # not used pr_wv_str=None pr_wv_str_wp=None pr_sql_q =",
"[], [], [], [] for t1 in t: nlu.append( t1['question']) nlu_t.append( t1['question_tok']) tbid",
"pr_wvi = pred_sw_se(s_sc, s_sa, s_wn, s_wc, s_wo, s_wv, ) pr_wv_str, pr_wv_str_wp = convert_pr_wvi_to_string(pr_wvi,",
"else: # Execution guided decoding prob_sca, prob_w, prob_wn_w, \\ pr_sc, pr_sa, pr_wn, pr_sql_i",
"nlu_t = [] for nlu1 in nlu: nlu_t.append(nlu1.split(' ')) return nlu_t def get_tables(tb_path):",
"table[t1['id']] = t1 return table def prepare_data(): sc_paths = [ './Qian_data/company_script.txt', './Qian_data/product_script.txt',] sc_tableids",
"# parser.add_argument(\"--data_path\", required=True, help='path to *.jsonl and *.db files') # parser.add_argument(\"--split\", required=True, help='prefix",
"= df.columns.tolist() rows = [] for _, row in df.iterrows(): rows.append(row.tolist()) print(rows) ##",
"len(nlu_i)) data = [] for i in range(len(nlu)): data.append({ 'question': nlu[i], 'question_tok': nlu_t[i],",
"nlu, nlu_t, tb, hds def my_predict( data_loader, data_table, model, model_bert, bert_config, tokenizer, max_seq_length,",
"variables are just for consistency with no-EG case. pr_wvi = None # not",
"### predict with torch.no_grad(): results = my_predict(data_loader, data_table, model, model_bert, bert_config, tokenizer, max_seq_length=args.max_seq_length,",
"of dict ### data_tables: dict nlu, nlu_t, tb, hds = [], [], [],",
"pr_wo, pr_wvi = pred_sw_se(s_sc, s_sa, s_wn, s_wc, s_wo, s_wv, ) pr_wv_str, pr_wv_str_wp =",
"csv_to_sqlite, csv_to_json from sqlnet.dbengine import DBEngine from sqlova.utils.utils_wikisql import * from train import",
"csv_to_json from sqlnet.dbengine import DBEngine from sqlova.utils.utils_wikisql import * from train import construct_hyper_param,",
"'./data_and_model' path_model_bert = './model_bert_best.pt' path_model = './model_best.pt' model, model_bert, tokenizer, bert_config = get_models(args,",
"deal with data ################### ## 不需要了 def read_csv_to_table(csv_path): # file_name as table_id table_id",
"pr_wvi = None # not used pr_wv_str=None pr_wv_str_wp=None pr_sql_q = generate_sql_q(pr_sql_i, tb) for",
"results = [] for _, t in enumerate(data_loader): nlu, nlu_t, tb, hds =",
"my_get_fields(t, data_tables): ### t: list of dict ### data_tables: dict nlu, nlu_t, tb,"
] |
[
"positive integer\") self.priorities += [msgType] self.buffers[msgType] = bytearray(0) def sizeHandler(data): \"\"\" Size of",
"in self.priorities: raise ValueError(\"Message type not defined\") self.buffers[msgType] += data def getMessage(self): \"\"\"Extract",
"\"\"\" Helper package for handling fragmentation of messages \"\"\" from __future__ import generators",
"else: return size self.decoders[msgType] = sizeHandler def addDynamicSize(self, msgType, sizeOffset, sizeOfSize): \"\"\"Add a",
"file for legal information regarding use of this file. \"\"\" Helper package for",
"of urgency. Supports messages with given size (like Alerts) or with a length",
"in specific place (like Handshake messages). :ivar priorities: order in which messages from",
"complete message from buffer\"\"\" for msgType in self.priorities: length = self.decoders[msgType](self.buffers[msgType]) if length",
"package for handling fragmentation of messages \"\"\" from __future__ import generators from .utils.codec",
"type is complete \"\"\" def __init__(self): \"\"\"Set up empty defregmenter\"\"\" self.priorities = []",
"header parser.getFixBytes(sizeOffset) payloadLength = parser.get(sizeOfSize) if parser.getRemainingLength() < payloadLength: # not enough bytes",
"Helper package for handling fragmentation of messages \"\"\" from __future__ import generators from",
"type which all messages are of same length\"\"\" if msgType in self.priorities: raise",
"<gh_stars>0 # Copyright (c) 2015, <NAME> # # See the LICENSE file for",
"self.priorities = [] self.buffers = {} self.decoders = {} def addStaticSize(self, msgType, size):",
"msgType in self.priorities: length = self.decoders[msgType](self.buffers[msgType]) if length is None: continue # extract",
"clearBuffers(self): \"\"\"Remove all data from buffers\"\"\" for key in self.buffers.keys(): self.buffers[key] = bytearray(0)",
"< 1: raise ValueError(\"Message size must be positive integer\") self.priorities += [msgType] self.buffers[msgType]",
"continue # extract message data = self.buffers[msgType][:length] # remove it from buffer self.buffers[msgType]",
"which messages from given types should be returned. :ivar buffers: data buffers for",
"header in specific place (like Handshake messages). :ivar priorities: order in which messages",
"\"\"\" if len(data) < size: return None else: return size self.decoders[msgType] = sizeHandler",
"message type which all messages are of same length\"\"\" if msgType in self.priorities:",
"(like Handshake messages). :ivar priorities: order in which messages from given types should",
"Class for demultiplexing TLS messages. Since the messages can be interleaved and fragmented",
"= self.buffers[msgType][length:] return (msgType, data) return None def clearBuffers(self): \"\"\"Remove all data from",
"if size < 1: raise ValueError(\"Message size must be positive integer\") self.priorities +=",
"is None: continue # extract message data = self.buffers[msgType][:length] # remove it from",
"specific place (like Handshake messages). :ivar priorities: order in which messages from given",
"self.buffers[msgType] += data def getMessage(self): \"\"\"Extract the highest priority complete message from buffer\"\"\"",
":ivar decoders: functions which check buffers if a message of given type is",
"msgType in self.priorities: raise ValueError(\"Message type already defined\") if size < 1: raise",
"information regarding use of this file. \"\"\" Helper package for handling fragmentation of",
"Parser(data) # skip the header parser.getFixBytes(sizeOffset) payloadLength = parser.get(sizeOfSize) if parser.getRemainingLength() < payloadLength:",
"parser.getRemainingLength() < payloadLength: # not enough bytes in buffer return None return sizeOffset",
"return (msgType, data) return None def clearBuffers(self): \"\"\"Remove all data from buffers\"\"\" for",
"need to cache not complete ones and return in order of urgency. Supports",
"complete ones and return in order of urgency. Supports messages with given size",
"return None else: parser = Parser(data) # skip the header parser.getFixBytes(sizeOffset) payloadLength =",
"data buffers for message types :ivar decoders: functions which check buffers if a",
"from __future__ import generators from .utils.codec import Parser class Defragmenter(object): \"\"\" Class for",
"for demultiplexing TLS messages. Since the messages can be interleaved and fragmented between",
"+= data def getMessage(self): \"\"\"Extract the highest priority complete message from buffer\"\"\" for",
"if sizeOfSize < 1: raise ValueError(\"Size of size must be positive integer\") if",
"be returned. :ivar buffers: data buffers for message types :ivar decoders: functions which",
"return in order of urgency. Supports messages with given size (like Alerts) or",
"messages can be interleaved and fragmented between each other we need to cache",
"return None def clearBuffers(self): \"\"\"Remove all data from buffers\"\"\" for key in self.buffers.keys():",
"< sizeOffset+sizeOfSize: return None else: parser = Parser(data) # skip the header parser.getFixBytes(sizeOffset)",
"the header parser.getFixBytes(sizeOffset) payloadLength = parser.get(sizeOfSize) if parser.getRemainingLength() < payloadLength: # not enough",
"ValueError(\"Size of size must be positive integer\") if sizeOffset < 0: raise ValueError(\"Offset",
"dynamic size set in a header\"\"\" if msgType in self.priorities: raise ValueError(\"Message type",
"message data = self.buffers[msgType][:length] # remove it from buffer self.buffers[msgType] = self.buffers[msgType][length:] return",
"if msgType in self.priorities: raise ValueError(\"Message type already defined\") if sizeOfSize < 1:",
"interleaved and fragmented between each other we need to cache not complete ones",
"has a dynamic size set in a header\"\"\" if msgType in self.priorities: raise",
"sizeOffset+sizeOfSize: return None else: parser = Parser(data) # skip the header parser.getFixBytes(sizeOffset) payloadLength",
"complete \"\"\" def __init__(self): \"\"\"Set up empty defregmenter\"\"\" self.priorities = [] self.buffers =",
"be positive integer\") if sizeOffset < 0: raise ValueError(\"Offset can't be negative\") self.priorities",
"if a message of given type is complete \"\"\" def __init__(self): \"\"\"Set up",
"messages. Since the messages can be interleaved and fragmented between each other we",
"header\"\"\" if msgType in self.priorities: raise ValueError(\"Message type already defined\") if sizeOfSize <",
"buffers: data buffers for message types :ivar decoders: functions which check buffers if",
":ivar buffers: data buffers for message types :ivar decoders: functions which check buffers",
"payloadLength self.decoders[msgType] = sizeHandler def addData(self, msgType, data): \"\"\"Adds data to buffers\"\"\" if",
"return size self.decoders[msgType] = sizeHandler def addDynamicSize(self, msgType, sizeOffset, sizeOfSize): \"\"\"Add a message",
"parser.get(sizeOfSize) if parser.getRemainingLength() < payloadLength: # not enough bytes in buffer return None",
"if sizeOffset < 0: raise ValueError(\"Offset can't be negative\") self.priorities += [msgType] self.buffers[msgType]",
"complete message is present in parameter returns its size, None otherwise. \"\"\" if",
"parser.getFixBytes(sizeOffset) payloadLength = parser.get(sizeOfSize) if parser.getRemainingLength() < payloadLength: # not enough bytes in",
"def clearBuffers(self): \"\"\"Remove all data from buffers\"\"\" for key in self.buffers.keys(): self.buffers[key] =",
"1: raise ValueError(\"Size of size must be positive integer\") if sizeOffset < 0:",
"and return in order of urgency. Supports messages with given size (like Alerts)",
"def sizeHandler(data): \"\"\" Size of message in parameter If complete message is present",
"functions which check buffers if a message of given type is complete \"\"\"",
"are of same length\"\"\" if msgType in self.priorities: raise ValueError(\"Message type already defined\")",
"self.priorities: raise ValueError(\"Message type already defined\") if sizeOfSize < 1: raise ValueError(\"Size of",
"length header in specific place (like Handshake messages). :ivar priorities: order in which",
"parameter returns its size, None otherwise. \"\"\" if len(data) < size: return None",
"message is present in parameter returns its size, None otherwise. \"\"\" if len(data)",
"# Copyright (c) 2015, <NAME> # # See the LICENSE file for legal",
"self.priorities += [msgType] self.buffers[msgType] = bytearray(0) def sizeHandler(data): \"\"\" Size of message in",
"in buffer return None return sizeOffset + sizeOfSize + payloadLength self.decoders[msgType] = sizeHandler",
"a message type which has a dynamic size set in a header\"\"\" if",
"buffer return None return sizeOffset + sizeOfSize + payloadLength self.decoders[msgType] = sizeHandler def",
"\"\"\" from __future__ import generators from .utils.codec import Parser class Defragmenter(object): \"\"\" Class",
"bytearray(0) def sizeHandler(data): \"\"\" Size of message in parameter If complete message is",
"See the LICENSE file for legal information regarding use of this file. \"\"\"",
"the LICENSE file for legal information regarding use of this file. \"\"\" Helper",
"given size (like Alerts) or with a length header in specific place (like",
"urgency. Supports messages with given size (like Alerts) or with a length header",
"size, None otherwise. \"\"\" if len(data) < sizeOffset+sizeOfSize: return None else: parser =",
"raise ValueError(\"Message type already defined\") if sizeOfSize < 1: raise ValueError(\"Size of size",
"(msgType, data) return None def clearBuffers(self): \"\"\"Remove all data from buffers\"\"\" for key",
"which all messages are of same length\"\"\" if msgType in self.priorities: raise ValueError(\"Message",
"can be interleaved and fragmented between each other we need to cache not",
"\"\"\" def __init__(self): \"\"\"Set up empty defregmenter\"\"\" self.priorities = [] self.buffers = {}",
"given type is complete \"\"\" def __init__(self): \"\"\"Set up empty defregmenter\"\"\" self.priorities =",
"data) return None def clearBuffers(self): \"\"\"Remove all data from buffers\"\"\" for key in",
"= self.buffers[msgType][:length] # remove it from buffer self.buffers[msgType] = self.buffers[msgType][length:] return (msgType, data)",
"defined\") if size < 1: raise ValueError(\"Message size must be positive integer\") self.priorities",
"# # See the LICENSE file for legal information regarding use of this",
"sizeHandler def addDynamicSize(self, msgType, sizeOffset, sizeOfSize): \"\"\"Add a message type which has a",
"addDynamicSize(self, msgType, sizeOffset, sizeOfSize): \"\"\"Add a message type which has a dynamic size",
"def addData(self, msgType, data): \"\"\"Adds data to buffers\"\"\" if msgType not in self.priorities:",
"messages are of same length\"\"\" if msgType in self.priorities: raise ValueError(\"Message type already",
"self.priorities: raise ValueError(\"Message type not defined\") self.buffers[msgType] += data def getMessage(self): \"\"\"Extract the",
"up empty defregmenter\"\"\" self.priorities = [] self.buffers = {} self.decoders = {} def",
"raise ValueError(\"Message type not defined\") self.buffers[msgType] += data def getMessage(self): \"\"\"Extract the highest",
"of this file. \"\"\" Helper package for handling fragmentation of messages \"\"\" from",
"type already defined\") if sizeOfSize < 1: raise ValueError(\"Size of size must be",
"message types :ivar decoders: functions which check buffers if a message of given",
"length is None: continue # extract message data = self.buffers[msgType][:length] # remove it",
"priorities: order in which messages from given types should be returned. :ivar buffers:",
"for legal information regarding use of this file. \"\"\" Helper package for handling",
"__init__(self): \"\"\"Set up empty defregmenter\"\"\" self.priorities = [] self.buffers = {} self.decoders =",
"+= [msgType] self.buffers[msgType] = bytearray(0) def sizeHandler(data): \"\"\" Size of message in parameter",
"= {} def addStaticSize(self, msgType, size): \"\"\"Add a message type which all messages",
"with given size (like Alerts) or with a length header in specific place",
"self.decoders = {} def addStaticSize(self, msgType, size): \"\"\"Add a message type which all",
"self.priorities: raise ValueError(\"Message type already defined\") if size < 1: raise ValueError(\"Message size",
"type already defined\") if size < 1: raise ValueError(\"Message size must be positive",
"order in which messages from given types should be returned. :ivar buffers: data",
"for handling fragmentation of messages \"\"\" from __future__ import generators from .utils.codec import",
"size self.decoders[msgType] = sizeHandler def addDynamicSize(self, msgType, sizeOffset, sizeOfSize): \"\"\"Add a message type",
"in self.priorities: raise ValueError(\"Message type already defined\") if sizeOfSize < 1: raise ValueError(\"Size",
"of same length\"\"\" if msgType in self.priorities: raise ValueError(\"Message type already defined\") if",
"a length header in specific place (like Handshake messages). :ivar priorities: order in",
"None otherwise. \"\"\" if len(data) < sizeOffset+sizeOfSize: return None else: parser = Parser(data)",
"return None return sizeOffset + sizeOfSize + payloadLength self.decoders[msgType] = sizeHandler def addData(self,",
"return None else: return size self.decoders[msgType] = sizeHandler def addDynamicSize(self, msgType, sizeOffset, sizeOfSize):",
"data def getMessage(self): \"\"\"Extract the highest priority complete message from buffer\"\"\" for msgType",
"= self.decoders[msgType](self.buffers[msgType]) if length is None: continue # extract message data = self.buffers[msgType][:length]",
"generators from .utils.codec import Parser class Defragmenter(object): \"\"\" Class for demultiplexing TLS messages.",
"types :ivar decoders: functions which check buffers if a message of given type",
"None else: parser = Parser(data) # skip the header parser.getFixBytes(sizeOffset) payloadLength = parser.get(sizeOfSize)",
"size, None otherwise. \"\"\" if len(data) < size: return None else: return size",
"to cache not complete ones and return in order of urgency. Supports messages",
"Parser class Defragmenter(object): \"\"\" Class for demultiplexing TLS messages. Since the messages can",
"sizeOffset + sizeOfSize + payloadLength self.decoders[msgType] = sizeHandler def addData(self, msgType, data): \"\"\"Adds",
"returned. :ivar buffers: data buffers for message types :ivar decoders: functions which check",
"if parser.getRemainingLength() < payloadLength: # not enough bytes in buffer return None return",
"in parameter returns its size, None otherwise. \"\"\" if len(data) < size: return",
"Since the messages can be interleaved and fragmented between each other we need",
"if msgType not in self.priorities: raise ValueError(\"Message type not defined\") self.buffers[msgType] += data",
"buffer self.buffers[msgType] = self.buffers[msgType][length:] return (msgType, data) return None def clearBuffers(self): \"\"\"Remove all",
"be negative\") self.priorities += [msgType] self.buffers[msgType] = bytearray(0) def sizeHandler(data): \"\"\" Size of",
"not enough bytes in buffer return None return sizeOffset + sizeOfSize + payloadLength",
"import generators from .utils.codec import Parser class Defragmenter(object): \"\"\" Class for demultiplexing TLS",
"buffers if a message of given type is complete \"\"\" def __init__(self): \"\"\"Set",
"self.decoders[msgType](self.buffers[msgType]) if length is None: continue # extract message data = self.buffers[msgType][:length] #",
"def addStaticSize(self, msgType, size): \"\"\"Add a message type which all messages are of",
"< payloadLength: # not enough bytes in buffer return None return sizeOffset +",
"size: return None else: return size self.decoders[msgType] = sizeHandler def addDynamicSize(self, msgType, sizeOffset,",
"< size: return None else: return size self.decoders[msgType] = sizeHandler def addDynamicSize(self, msgType,",
"is complete \"\"\" def __init__(self): \"\"\"Set up empty defregmenter\"\"\" self.priorities = [] self.buffers",
"If complete message is present in parameter returns its size, None otherwise. \"\"\"",
"check buffers if a message of given type is complete \"\"\" def __init__(self):",
"# extract message data = self.buffers[msgType][:length] # remove it from buffer self.buffers[msgType] =",
"msgType, data): \"\"\"Adds data to buffers\"\"\" if msgType not in self.priorities: raise ValueError(\"Message",
"ValueError(\"Message type already defined\") if sizeOfSize < 1: raise ValueError(\"Size of size must",
"order of urgency. Supports messages with given size (like Alerts) or with a",
"we need to cache not complete ones and return in order of urgency.",
"decoders: functions which check buffers if a message of given type is complete",
"extract message data = self.buffers[msgType][:length] # remove it from buffer self.buffers[msgType] = self.buffers[msgType][length:]",
"message type which has a dynamic size set in a header\"\"\" if msgType",
"addData(self, msgType, data): \"\"\"Adds data to buffers\"\"\" if msgType not in self.priorities: raise",
"sizeOffset < 0: raise ValueError(\"Offset can't be negative\") self.priorities += [msgType] self.buffers[msgType] =",
"payloadLength: # not enough bytes in buffer return None return sizeOffset + sizeOfSize",
"self.buffers = {} self.decoders = {} def addStaticSize(self, msgType, size): \"\"\"Add a message",
"parameter returns its size, None otherwise. \"\"\" if len(data) < sizeOffset+sizeOfSize: return None",
"Copyright (c) 2015, <NAME> # # See the LICENSE file for legal information",
"buffers for message types :ivar decoders: functions which check buffers if a message",
"integer\") self.priorities += [msgType] self.buffers[msgType] = bytearray(0) def sizeHandler(data): \"\"\" Size of message",
"between each other we need to cache not complete ones and return in",
"returns its size, None otherwise. \"\"\" if len(data) < size: return None else:",
"not complete ones and return in order of urgency. Supports messages with given",
"type not defined\") self.buffers[msgType] += data def getMessage(self): \"\"\"Extract the highest priority complete",
"from buffer\"\"\" for msgType in self.priorities: length = self.decoders[msgType](self.buffers[msgType]) if length is None:",
"\"\"\" if len(data) < sizeOffset+sizeOfSize: return None else: parser = Parser(data) # skip",
"message from buffer\"\"\" for msgType in self.priorities: length = self.decoders[msgType](self.buffers[msgType]) if length is",
"__future__ import generators from .utils.codec import Parser class Defragmenter(object): \"\"\" Class for demultiplexing",
"fragmentation of messages \"\"\" from __future__ import generators from .utils.codec import Parser class",
"present in parameter returns its size, None otherwise. \"\"\" if len(data) < size:",
"positive integer\") if sizeOffset < 0: raise ValueError(\"Offset can't be negative\") self.priorities +=",
"= [] self.buffers = {} self.decoders = {} def addStaticSize(self, msgType, size): \"\"\"Add",
"not in self.priorities: raise ValueError(\"Message type not defined\") self.buffers[msgType] += data def getMessage(self):",
"this file. \"\"\" Helper package for handling fragmentation of messages \"\"\" from __future__",
"size < 1: raise ValueError(\"Message size must be positive integer\") self.priorities += [msgType]",
"payloadLength = parser.get(sizeOfSize) if parser.getRemainingLength() < payloadLength: # not enough bytes in buffer",
"demultiplexing TLS messages. Since the messages can be interleaved and fragmented between each",
"given types should be returned. :ivar buffers: data buffers for message types :ivar",
"fragmented between each other we need to cache not complete ones and return",
"in parameter If complete message is present in parameter returns its size, None",
"is present in parameter returns its size, None otherwise. \"\"\" if len(data) <",
"size (like Alerts) or with a length header in specific place (like Handshake",
"sizeHandler(data): \"\"\" Size of message in parameter If complete message is present in",
"type which has a dynamic size set in a header\"\"\" if msgType in",
"{} def addStaticSize(self, msgType, size): \"\"\"Add a message type which all messages are",
"= sizeHandler def addDynamicSize(self, msgType, sizeOffset, sizeOfSize): \"\"\"Add a message type which has",
"len(data) < sizeOffset+sizeOfSize: return None else: parser = Parser(data) # skip the header",
"from .utils.codec import Parser class Defragmenter(object): \"\"\" Class for demultiplexing TLS messages. Since",
"otherwise. \"\"\" if len(data) < size: return None else: return size self.decoders[msgType] =",
"be positive integer\") self.priorities += [msgType] self.buffers[msgType] = bytearray(0) def sizeHandler(data): \"\"\" Size",
"[] self.buffers = {} self.decoders = {} def addStaticSize(self, msgType, size): \"\"\"Add a",
"a dynamic size set in a header\"\"\" if msgType in self.priorities: raise ValueError(\"Message",
"sizeHandler def addData(self, msgType, data): \"\"\"Adds data to buffers\"\"\" if msgType not in",
"\"\"\"Extract the highest priority complete message from buffer\"\"\" for msgType in self.priorities: length",
"sizeOfSize < 1: raise ValueError(\"Size of size must be positive integer\") if sizeOffset",
"for msgType in self.priorities: length = self.decoders[msgType](self.buffers[msgType]) if length is None: continue #",
"handling fragmentation of messages \"\"\" from __future__ import generators from .utils.codec import Parser",
"data): \"\"\"Adds data to buffers\"\"\" if msgType not in self.priorities: raise ValueError(\"Message type",
"be interleaved and fragmented between each other we need to cache not complete",
"set in a header\"\"\" if msgType in self.priorities: raise ValueError(\"Message type already defined\")",
"must be positive integer\") self.priorities += [msgType] self.buffers[msgType] = bytearray(0) def sizeHandler(data): \"\"\"",
"messages from given types should be returned. :ivar buffers: data buffers for message",
"must be positive integer\") if sizeOffset < 0: raise ValueError(\"Offset can't be negative\")",
"all messages are of same length\"\"\" if msgType in self.priorities: raise ValueError(\"Message type",
"= parser.get(sizeOfSize) if parser.getRemainingLength() < payloadLength: # not enough bytes in buffer return",
"if len(data) < size: return None else: return size self.decoders[msgType] = sizeHandler def",
"else: parser = Parser(data) # skip the header parser.getFixBytes(sizeOffset) payloadLength = parser.get(sizeOfSize) if",
"should be returned. :ivar buffers: data buffers for message types :ivar decoders: functions",
"the highest priority complete message from buffer\"\"\" for msgType in self.priorities: length =",
"if msgType in self.priorities: raise ValueError(\"Message type already defined\") if size < 1:",
"(c) 2015, <NAME> # # See the LICENSE file for legal information regarding",
"same length\"\"\" if msgType in self.priorities: raise ValueError(\"Message type already defined\") if size",
"integer\") if sizeOffset < 0: raise ValueError(\"Offset can't be negative\") self.priorities += [msgType]",
"from buffer self.buffers[msgType] = self.buffers[msgType][length:] return (msgType, data) return None def clearBuffers(self): \"\"\"Remove",
"msgType, sizeOffset, sizeOfSize): \"\"\"Add a message type which has a dynamic size set",
"if len(data) < sizeOffset+sizeOfSize: return None else: parser = Parser(data) # skip the",
"skip the header parser.getFixBytes(sizeOffset) payloadLength = parser.get(sizeOfSize) if parser.getRemainingLength() < payloadLength: # not",
"in which messages from given types should be returned. :ivar buffers: data buffers",
"self.priorities: length = self.decoders[msgType](self.buffers[msgType]) if length is None: continue # extract message data",
"messages). :ivar priorities: order in which messages from given types should be returned.",
"not defined\") self.buffers[msgType] += data def getMessage(self): \"\"\"Extract the highest priority complete message",
"in self.priorities: raise ValueError(\"Message type already defined\") if size < 1: raise ValueError(\"Message",
"self.buffers[msgType] = self.buffers[msgType][length:] return (msgType, data) return None def clearBuffers(self): \"\"\"Remove all data",
"sizeOfSize + payloadLength self.decoders[msgType] = sizeHandler def addData(self, msgType, data): \"\"\"Adds data to",
"its size, None otherwise. \"\"\" if len(data) < size: return None else: return",
"already defined\") if sizeOfSize < 1: raise ValueError(\"Size of size must be positive",
"from given types should be returned. :ivar buffers: data buffers for message types",
"# remove it from buffer self.buffers[msgType] = self.buffers[msgType][length:] return (msgType, data) return None",
"self.buffers[msgType][length:] return (msgType, data) return None def clearBuffers(self): \"\"\"Remove all data from buffers\"\"\"",
"parser = Parser(data) # skip the header parser.getFixBytes(sizeOffset) payloadLength = parser.get(sizeOfSize) if parser.getRemainingLength()",
"\"\"\" Class for demultiplexing TLS messages. Since the messages can be interleaved and",
"ValueError(\"Message type not defined\") self.buffers[msgType] += data def getMessage(self): \"\"\"Extract the highest priority",
"ValueError(\"Offset can't be negative\") self.priorities += [msgType] self.buffers[msgType] = bytearray(0) def sizeHandler(data): \"\"\"",
"getMessage(self): \"\"\"Extract the highest priority complete message from buffer\"\"\" for msgType in self.priorities:",
"self.decoders[msgType] = sizeHandler def addDynamicSize(self, msgType, sizeOffset, sizeOfSize): \"\"\"Add a message type which",
"data = self.buffers[msgType][:length] # remove it from buffer self.buffers[msgType] = self.buffers[msgType][length:] return (msgType,",
"with a length header in specific place (like Handshake messages). :ivar priorities: order",
"of message in parameter If complete message is present in parameter returns its",
"buffers\"\"\" if msgType not in self.priorities: raise ValueError(\"Message type not defined\") self.buffers[msgType] +=",
"1: raise ValueError(\"Message size must be positive integer\") self.priorities += [msgType] self.buffers[msgType] =",
"file. \"\"\" Helper package for handling fragmentation of messages \"\"\" from __future__ import",
"TLS messages. Since the messages can be interleaved and fragmented between each other",
"raise ValueError(\"Offset can't be negative\") self.priorities += [msgType] self.buffers[msgType] = bytearray(0) def sizeHandler(data):",
"= {} self.decoders = {} def addStaticSize(self, msgType, size): \"\"\"Add a message type",
"< 0: raise ValueError(\"Offset can't be negative\") self.priorities += [msgType] self.buffers[msgType] = bytearray(0)",
"other we need to cache not complete ones and return in order of",
"which has a dynamic size set in a header\"\"\" if msgType in self.priorities:",
"in a header\"\"\" if msgType in self.priorities: raise ValueError(\"Message type already defined\") if",
"place (like Handshake messages). :ivar priorities: order in which messages from given types",
"self.buffers[msgType][:length] # remove it from buffer self.buffers[msgType] = self.buffers[msgType][length:] return (msgType, data) return",
"Alerts) or with a length header in specific place (like Handshake messages). :ivar",
"parameter If complete message is present in parameter returns its size, None otherwise.",
"which check buffers if a message of given type is complete \"\"\" def",
"\"\"\"Add a message type which all messages are of same length\"\"\" if msgType",
"= sizeHandler def addData(self, msgType, data): \"\"\"Adds data to buffers\"\"\" if msgType not",
"Handshake messages). :ivar priorities: order in which messages from given types should be",
"length\"\"\" if msgType in self.priorities: raise ValueError(\"Message type already defined\") if size <",
"None else: return size self.decoders[msgType] = sizeHandler def addDynamicSize(self, msgType, sizeOffset, sizeOfSize): \"\"\"Add",
"ValueError(\"Message size must be positive integer\") self.priorities += [msgType] self.buffers[msgType] = bytearray(0) def",
"<NAME> # # See the LICENSE file for legal information regarding use of",
"msgType, size): \"\"\"Add a message type which all messages are of same length\"\"\"",
"self.buffers[msgType] = bytearray(0) def sizeHandler(data): \"\"\" Size of message in parameter If complete",
"\"\"\" Size of message in parameter If complete message is present in parameter",
"0: raise ValueError(\"Offset can't be negative\") self.priorities += [msgType] self.buffers[msgType] = bytearray(0) def",
"LICENSE file for legal information regarding use of this file. \"\"\" Helper package",
"a message of given type is complete \"\"\" def __init__(self): \"\"\"Set up empty",
"return sizeOffset + sizeOfSize + payloadLength self.decoders[msgType] = sizeHandler def addData(self, msgType, data):",
"def addDynamicSize(self, msgType, sizeOffset, sizeOfSize): \"\"\"Add a message type which has a dynamic",
"of size must be positive integer\") if sizeOffset < 0: raise ValueError(\"Offset can't",
"in parameter returns its size, None otherwise. \"\"\" if len(data) < sizeOffset+sizeOfSize: return",
"it from buffer self.buffers[msgType] = self.buffers[msgType][length:] return (msgType, data) return None def clearBuffers(self):",
"enough bytes in buffer return None return sizeOffset + sizeOfSize + payloadLength self.decoders[msgType]",
"size must be positive integer\") if sizeOffset < 0: raise ValueError(\"Offset can't be",
"+ sizeOfSize + payloadLength self.decoders[msgType] = sizeHandler def addData(self, msgType, data): \"\"\"Adds data",
"message in parameter If complete message is present in parameter returns its size,",
"messages with given size (like Alerts) or with a length header in specific",
"+ payloadLength self.decoders[msgType] = sizeHandler def addData(self, msgType, data): \"\"\"Adds data to buffers\"\"\"",
"or with a length header in specific place (like Handshake messages). :ivar priorities:",
"# skip the header parser.getFixBytes(sizeOffset) payloadLength = parser.get(sizeOfSize) if parser.getRemainingLength() < payloadLength: #",
"for message types :ivar decoders: functions which check buffers if a message of",
"raise ValueError(\"Size of size must be positive integer\") if sizeOffset < 0: raise",
"defined\") if sizeOfSize < 1: raise ValueError(\"Size of size must be positive integer\")",
"bytes in buffer return None return sizeOffset + sizeOfSize + payloadLength self.decoders[msgType] =",
"ones and return in order of urgency. Supports messages with given size (like",
"raise ValueError(\"Message size must be positive integer\") self.priorities += [msgType] self.buffers[msgType] = bytearray(0)",
"size): \"\"\"Add a message type which all messages are of same length\"\"\" if",
"size must be positive integer\") self.priorities += [msgType] self.buffers[msgType] = bytearray(0) def sizeHandler(data):",
"Size of message in parameter If complete message is present in parameter returns",
"negative\") self.priorities += [msgType] self.buffers[msgType] = bytearray(0) def sizeHandler(data): \"\"\" Size of message",
"2015, <NAME> # # See the LICENSE file for legal information regarding use",
"raise ValueError(\"Message type already defined\") if size < 1: raise ValueError(\"Message size must",
"of messages \"\"\" from __future__ import generators from .utils.codec import Parser class Defragmenter(object):",
"already defined\") if size < 1: raise ValueError(\"Message size must be positive integer\")",
"sizeOfSize): \"\"\"Add a message type which has a dynamic size set in a",
"len(data) < size: return None else: return size self.decoders[msgType] = sizeHandler def addDynamicSize(self,",
"its size, None otherwise. \"\"\" if len(data) < sizeOffset+sizeOfSize: return None else: parser",
".utils.codec import Parser class Defragmenter(object): \"\"\" Class for demultiplexing TLS messages. Since the",
"data to buffers\"\"\" if msgType not in self.priorities: raise ValueError(\"Message type not defined\")",
"cache not complete ones and return in order of urgency. Supports messages with",
"if length is None: continue # extract message data = self.buffers[msgType][:length] # remove",
"in self.priorities: length = self.decoders[msgType](self.buffers[msgType]) if length is None: continue # extract message",
"a header\"\"\" if msgType in self.priorities: raise ValueError(\"Message type already defined\") if sizeOfSize",
"= bytearray(0) def sizeHandler(data): \"\"\" Size of message in parameter If complete message",
"addStaticSize(self, msgType, size): \"\"\"Add a message type which all messages are of same",
"msgType in self.priorities: raise ValueError(\"Message type already defined\") if sizeOfSize < 1: raise",
"regarding use of this file. \"\"\" Helper package for handling fragmentation of messages",
"each other we need to cache not complete ones and return in order",
"{} self.decoders = {} def addStaticSize(self, msgType, size): \"\"\"Add a message type which",
"the messages can be interleaved and fragmented between each other we need to",
"None otherwise. \"\"\" if len(data) < size: return None else: return size self.decoders[msgType]",
"Defragmenter(object): \"\"\" Class for demultiplexing TLS messages. Since the messages can be interleaved",
"and fragmented between each other we need to cache not complete ones and",
"can't be negative\") self.priorities += [msgType] self.buffers[msgType] = bytearray(0) def sizeHandler(data): \"\"\" Size",
"# See the LICENSE file for legal information regarding use of this file.",
"buffer\"\"\" for msgType in self.priorities: length = self.decoders[msgType](self.buffers[msgType]) if length is None: continue",
"< 1: raise ValueError(\"Size of size must be positive integer\") if sizeOffset <",
"def __init__(self): \"\"\"Set up empty defregmenter\"\"\" self.priorities = [] self.buffers = {} self.decoders",
"(like Alerts) or with a length header in specific place (like Handshake messages).",
"[msgType] self.buffers[msgType] = bytearray(0) def sizeHandler(data): \"\"\" Size of message in parameter If",
"None return sizeOffset + sizeOfSize + payloadLength self.decoders[msgType] = sizeHandler def addData(self, msgType,",
"import Parser class Defragmenter(object): \"\"\" Class for demultiplexing TLS messages. Since the messages",
"length = self.decoders[msgType](self.buffers[msgType]) if length is None: continue # extract message data =",
"remove it from buffer self.buffers[msgType] = self.buffers[msgType][length:] return (msgType, data) return None def",
"messages \"\"\" from __future__ import generators from .utils.codec import Parser class Defragmenter(object): \"\"\"",
"priority complete message from buffer\"\"\" for msgType in self.priorities: length = self.decoders[msgType](self.buffers[msgType]) if",
"defregmenter\"\"\" self.priorities = [] self.buffers = {} self.decoders = {} def addStaticSize(self, msgType,",
"present in parameter returns its size, None otherwise. \"\"\" if len(data) < sizeOffset+sizeOfSize:",
"None def clearBuffers(self): \"\"\"Remove all data from buffers\"\"\" for key in self.buffers.keys(): self.buffers[key]",
"\"\"\"Set up empty defregmenter\"\"\" self.priorities = [] self.buffers = {} self.decoders = {}",
"of given type is complete \"\"\" def __init__(self): \"\"\"Set up empty defregmenter\"\"\" self.priorities",
"sizeOffset, sizeOfSize): \"\"\"Add a message type which has a dynamic size set in",
"size set in a header\"\"\" if msgType in self.priorities: raise ValueError(\"Message type already",
"legal information regarding use of this file. \"\"\" Helper package for handling fragmentation",
"msgType not in self.priorities: raise ValueError(\"Message type not defined\") self.buffers[msgType] += data def",
"# not enough bytes in buffer return None return sizeOffset + sizeOfSize +",
"None: continue # extract message data = self.buffers[msgType][:length] # remove it from buffer",
"use of this file. \"\"\" Helper package for handling fragmentation of messages \"\"\"",
"returns its size, None otherwise. \"\"\" if len(data) < sizeOffset+sizeOfSize: return None else:",
"in order of urgency. Supports messages with given size (like Alerts) or with",
"to buffers\"\"\" if msgType not in self.priorities: raise ValueError(\"Message type not defined\") self.buffers[msgType]",
"defined\") self.buffers[msgType] += data def getMessage(self): \"\"\"Extract the highest priority complete message from",
"message of given type is complete \"\"\" def __init__(self): \"\"\"Set up empty defregmenter\"\"\"",
"empty defregmenter\"\"\" self.priorities = [] self.buffers = {} self.decoders = {} def addStaticSize(self,",
":ivar priorities: order in which messages from given types should be returned. :ivar",
"types should be returned. :ivar buffers: data buffers for message types :ivar decoders:",
"otherwise. \"\"\" if len(data) < sizeOffset+sizeOfSize: return None else: parser = Parser(data) #",
"\"\"\"Add a message type which has a dynamic size set in a header\"\"\"",
"highest priority complete message from buffer\"\"\" for msgType in self.priorities: length = self.decoders[msgType](self.buffers[msgType])",
"def getMessage(self): \"\"\"Extract the highest priority complete message from buffer\"\"\" for msgType in",
"\"\"\"Adds data to buffers\"\"\" if msgType not in self.priorities: raise ValueError(\"Message type not",
"Supports messages with given size (like Alerts) or with a length header in",
"a message type which all messages are of same length\"\"\" if msgType in",
"self.decoders[msgType] = sizeHandler def addData(self, msgType, data): \"\"\"Adds data to buffers\"\"\" if msgType",
"ValueError(\"Message type already defined\") if size < 1: raise ValueError(\"Message size must be",
"= Parser(data) # skip the header parser.getFixBytes(sizeOffset) payloadLength = parser.get(sizeOfSize) if parser.getRemainingLength() <",
"class Defragmenter(object): \"\"\" Class for demultiplexing TLS messages. Since the messages can be"
] |
[
"KIND, either express or implied. # See the License for the specific language",
"Unless required by applicable law or agreed to in writing, software # distributed",
"port: int, mlmd_connection: metadata.Metadata, execution: metadata_store_pb2.Execution, address: Optional[str] = None, creds: Optional[grpc.ServerCredentials] =",
"a gRPC server and add `self` on to it.\"\"\" result = grpc.server(futures.ThreadPoolExecutor()) execution_watcher_pb2_grpc.add_ExecutionWatcherServiceServicer_to_server(",
"Local network address to the server. address: Remote network address to the server,",
"request: execution_watcher_pb2.UpdateExecutionInfoRequest, context: grpc.ServicerContext ) -> execution_watcher_pb2.UpdateExecutionInfoResponse: \"\"\"Updates the `custom_properties` field of Execution",
"if request.execution_id != self._execution.id: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details( 'Execution with given execution_id not tracked by",
"None, creds: Optional[grpc.ServerCredentials] = None): \"\"\"Initializes the gRPC server. Args: port: Which port",
"@property def local_address(self) -> str: # Local network address to the server. return",
"Args: port: Which port the service will be using. mlmd_connection: ML metadata connection.",
"remote job info to MLMD.\"\"\" from concurrent import futures from typing import Optional",
"field of Execution object in MLMD.\"\"\" logging.info('Received request to update execution info: updates",
"this file except in compliance with the License. # You may obtain a",
"the execution is needed with self._mlmd_connection as m: m.store.put_executions((self._execution,)) return execution_watcher_pb2.UpdateExecutionInfoResponse() def _create_server(self):",
"LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0",
"\"\"\"This module provides a gRPC service for updating remote job info to MLMD.\"\"\"",
"language governing permissions and # limitations under the License. \"\"\"This module provides a",
"address to the server. return f'localhost:{self._port}' @property def address(self) -> str: return self._address",
"ANY KIND, either express or implied. # See the License for the specific",
"metadata_store_pb2.Execution, address: Optional[str] = None, creds: Optional[grpc.ServerCredentials] = None): \"\"\"Initializes the gRPC server.",
"or self.local_address def start(self): \"\"\"Starts the server.\"\"\" self._server.start() def stop(self): \"\"\"Stops the server.\"\"\"",
"the License. \"\"\"This module provides a gRPC service for updating remote job info",
"self._execution = execution def UpdateExecutionInfo( self, request: execution_watcher_pb2.UpdateExecutionInfoRequest, context: grpc.ServicerContext ) -> execution_watcher_pb2.UpdateExecutionInfoResponse:",
"in MLMD.\"\"\" logging.info('Received request to update execution info: updates %s, ' 'execution_id %s',",
"execution_watcher_pb2 from tfx.proto.orchestration import execution_watcher_pb2_grpc from ml_metadata.proto import metadata_store_pb2 def generate_service_stub( address: str,",
"to the server. return f'localhost:{self._port}' @property def address(self) -> str: return self._address or",
"class ExecutionWatcher( execution_watcher_pb2_grpc.ExecutionWatcherServiceServicer): \"\"\"A gRPC service server for updating remote job info to",
"execution.HasField('id'): raise ValueError( 'execution id must be set to be tracked by ExecutionWatcher.')",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"import Optional from absl import logging import grpc from tfx.orchestration import metadata from",
"mlmd_connection: ML metadata connection. execution: The MLMD Execution to keep track of. address:",
"not configured. \"\"\" def __init__(self, port: int, mlmd_connection: metadata.Metadata, execution: metadata_store_pb2.Execution, address: Optional[str]",
"it.\"\"\" result = grpc.server(futures.ThreadPoolExecutor()) execution_watcher_pb2_grpc.add_ExecutionWatcherServiceServicer_to_server( self, result) if self._creds is None: result.add_insecure_port(self.local_address) else:",
"the service will be using. mlmd_connection: ML metadata connection. execution: The MLMD Execution",
"if not configured. \"\"\" def __init__(self, port: int, mlmd_connection: metadata.Metadata, execution: metadata_store_pb2.Execution, address:",
") -> execution_watcher_pb2_grpc.ExecutionWatcherServiceStub: \"\"\"Generates a gRPC service stub for a given server address.\"\"\"",
"server for updating remote job info to MLMD. Attributes: local_address: Local network address",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"\"\"\"Initializes the gRPC server. Args: port: Which port the service will be using.",
"updates %s, ' 'execution_id %s', request.updates, request.execution_id) if request.execution_id != self._execution.id: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details(",
"formatted as an ipv4 or ipv6 address in the format `address:port`. If left",
"OF ANY KIND, either express or implied. # See the License for the",
"if self._creds is None: result.add_insecure_port(self.local_address) else: result.add_secure_port(self.local_address, self._creds) return result @property def local_address(self)",
"ExecutionWatcher( execution_watcher_pb2_grpc.ExecutionWatcherServiceServicer): \"\"\"A gRPC service server for updating remote job info to MLMD.",
"execution_watcher_pb2.UpdateExecutionInfoRequest, context: grpc.ServicerContext ) -> execution_watcher_pb2.UpdateExecutionInfoResponse: \"\"\"Updates the `custom_properties` field of Execution object",
"else: result.add_secure_port(self.local_address, self._creds) return result @property def local_address(self) -> str: # Local network",
"Attributes: local_address: Local network address to the server. address: Remote network address to",
"from tfx.proto.orchestration import execution_watcher_pb2 from tfx.proto.orchestration import execution_watcher_pb2_grpc from ml_metadata.proto import metadata_store_pb2 def",
"int, mlmd_connection: metadata.Metadata, execution: metadata_store_pb2.Execution, address: Optional[str] = None, creds: Optional[grpc.ServerCredentials] = None):",
"import execution_watcher_pb2 from tfx.proto.orchestration import execution_watcher_pb2_grpc from ml_metadata.proto import metadata_store_pb2 def generate_service_stub( address:",
"network address to the server. address: Remote network address to the server, same",
"grpc.insecure_channel(address) return execution_watcher_pb2_grpc.ExecutionWatcherServiceStub(channel) class ExecutionWatcher( execution_watcher_pb2_grpc.ExecutionWatcherServiceServicer): \"\"\"A gRPC service server for updating remote",
"import metadata_store_pb2 def generate_service_stub( address: str, creds: Optional[grpc.ChannelCredentials] = None, ) -> execution_watcher_pb2_grpc.ExecutionWatcherServiceStub:",
"for the specific language governing permissions and # limitations under the License. \"\"\"This",
"m: m.store.put_executions((self._execution,)) return execution_watcher_pb2.UpdateExecutionInfoResponse() def _create_server(self): \"\"\"Creates a gRPC server and add `self`",
"server address.\"\"\" channel = grpc.secure_channel( address, creds) if creds else grpc.insecure_channel(address) return execution_watcher_pb2_grpc.ExecutionWatcherServiceStub(channel)",
"Optional[str] = None, creds: Optional[grpc.ServerCredentials] = None): \"\"\"Initializes the gRPC server. Args: port:",
"execution_id not tracked by server: ' f'{request.execution_id}') return execution_watcher_pb2.UpdateExecutionInfoResponse() for key, value in",
"creds else grpc.insecure_channel(address) return execution_watcher_pb2_grpc.ExecutionWatcherServiceStub(channel) class ExecutionWatcher( execution_watcher_pb2_grpc.ExecutionWatcherServiceServicer): \"\"\"A gRPC service server for",
"= mlmd_connection self._server = self._create_server() if not execution.HasField('id'): raise ValueError( 'execution id must",
"All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the",
"MLMD.\"\"\" from concurrent import futures from typing import Optional from absl import logging",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"and add `self` on to it.\"\"\" result = grpc.server(futures.ThreadPoolExecutor()) execution_watcher_pb2_grpc.add_ExecutionWatcherServiceServicer_to_server( self, result) if",
"keep track of. address: Remote address used to contact the server. Should be",
"service stub for a given server address.\"\"\" channel = grpc.secure_channel( address, creds) if",
"m.store.put_executions((self._execution,)) return execution_watcher_pb2.UpdateExecutionInfoResponse() def _create_server(self): \"\"\"Creates a gRPC server and add `self` on",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"!= self._execution.id: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details( 'Execution with given execution_id not tracked by server: '",
"contact the server. Should be formatted as an ipv4 or ipv6 address in",
"request.updates.items(): self._execution.custom_properties[key].CopyFrom( value) # Only the execution is needed with self._mlmd_connection as m:",
"the specific language governing permissions and # limitations under the License. \"\"\"This module",
"address: Remote network address to the server, same as local_address if not configured.",
"as m: m.store.put_executions((self._execution,)) return execution_watcher_pb2.UpdateExecutionInfoResponse() def _create_server(self): \"\"\"Creates a gRPC server and add",
"execution_watcher_pb2_grpc.add_ExecutionWatcherServiceServicer_to_server( self, result) if self._creds is None: result.add_insecure_port(self.local_address) else: result.add_secure_port(self.local_address, self._creds) return result",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"execution_watcher_pb2.UpdateExecutionInfoResponse() for key, value in request.updates.items(): self._execution.custom_properties[key].CopyFrom( value) # Only the execution is",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"specific language governing permissions and # limitations under the License. \"\"\"This module provides",
"'Execution with given execution_id not tracked by server: ' f'{request.execution_id}') return execution_watcher_pb2.UpdateExecutionInfoResponse() for",
"= address self._creds = creds self._mlmd_connection = mlmd_connection self._server = self._create_server() if not",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"= grpc.secure_channel( address, creds) if creds else grpc.insecure_channel(address) return execution_watcher_pb2_grpc.ExecutionWatcherServiceStub(channel) class ExecutionWatcher( execution_watcher_pb2_grpc.ExecutionWatcherServiceServicer):",
"futures from typing import Optional from absl import logging import grpc from tfx.orchestration",
"creds: Optional[grpc.ServerCredentials] = None): \"\"\"Initializes the gRPC server. Args: port: Which port the",
"None, server will use an insecure port. \"\"\" super().__init__() self._port = port self._address",
"local_address(self) -> str: # Local network address to the server. return f'localhost:{self._port}' @property",
"metadata.Metadata, execution: metadata_store_pb2.Execution, address: Optional[str] = None, creds: Optional[grpc.ServerCredentials] = None): \"\"\"Initializes the",
"required by applicable law or agreed to in writing, software # distributed under",
"remote job info to MLMD. Attributes: local_address: Local network address to the server.",
"execution is needed with self._mlmd_connection as m: m.store.put_executions((self._execution,)) return execution_watcher_pb2.UpdateExecutionInfoResponse() def _create_server(self): \"\"\"Creates",
"metadata from tfx.proto.orchestration import execution_watcher_pb2 from tfx.proto.orchestration import execution_watcher_pb2_grpc from ml_metadata.proto import metadata_store_pb2",
"applicable law or agreed to in writing, software # distributed under the License",
"execution_watcher_pb2_grpc.ExecutionWatcherServiceStub: \"\"\"Generates a gRPC service stub for a given server address.\"\"\" channel =",
"info: updates %s, ' 'execution_id %s', request.updates, request.execution_id) if request.execution_id != self._execution.id: context.set_code(grpc.StatusCode.NOT_FOUND)",
"or agreed to in writing, software # distributed under the License is distributed",
"def _create_server(self): \"\"\"Creates a gRPC server and add `self` on to it.\"\"\" result",
"the format `address:port`. If left as None, server will use local address. creds:",
"needed with self._mlmd_connection as m: m.store.put_executions((self._execution,)) return execution_watcher_pb2.UpdateExecutionInfoResponse() def _create_server(self): \"\"\"Creates a gRPC",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"updating remote job info to MLMD. Attributes: local_address: Local network address to the",
"to contact the server. Should be formatted as an ipv4 or ipv6 address",
"with self._mlmd_connection as m: m.store.put_executions((self._execution,)) return execution_watcher_pb2.UpdateExecutionInfoResponse() def _create_server(self): \"\"\"Creates a gRPC server",
"as None, server will use local address. creds: gRPC server credentials. If left",
"None, ) -> execution_watcher_pb2_grpc.ExecutionWatcherServiceStub: \"\"\"Generates a gRPC service stub for a given server",
"port: Which port the service will be using. mlmd_connection: ML metadata connection. execution:",
"server: ' f'{request.execution_id}') return execution_watcher_pb2.UpdateExecutionInfoResponse() for key, value in request.updates.items(): self._execution.custom_properties[key].CopyFrom( value) #",
"or ipv6 address in the format `address:port`. If left as None, server will",
"str, creds: Optional[grpc.ChannelCredentials] = None, ) -> execution_watcher_pb2_grpc.ExecutionWatcherServiceStub: \"\"\"Generates a gRPC service stub",
"absl import logging import grpc from tfx.orchestration import metadata from tfx.proto.orchestration import execution_watcher_pb2",
"creds: gRPC server credentials. If left as None, server will use an insecure",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"server. return f'localhost:{self._port}' @property def address(self) -> str: return self._address or self.local_address def",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"and # limitations under the License. \"\"\"This module provides a gRPC service for",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"Remote address used to contact the server. Should be formatted as an ipv4",
"License. # You may obtain a copy of the License at # #",
"logging import grpc from tfx.orchestration import metadata from tfx.proto.orchestration import execution_watcher_pb2 from tfx.proto.orchestration",
"`self` on to it.\"\"\" result = grpc.server(futures.ThreadPoolExecutor()) execution_watcher_pb2_grpc.add_ExecutionWatcherServiceServicer_to_server( self, result) if self._creds is",
"compliance with the License. # You may obtain a copy of the License",
"as local_address if not configured. \"\"\" def __init__(self, port: int, mlmd_connection: metadata.Metadata, execution:",
"on to it.\"\"\" result = grpc.server(futures.ThreadPoolExecutor()) execution_watcher_pb2_grpc.add_ExecutionWatcherServiceServicer_to_server( self, result) if self._creds is None:",
"execution_watcher_pb2.UpdateExecutionInfoResponse: \"\"\"Updates the `custom_properties` field of Execution object in MLMD.\"\"\" logging.info('Received request to",
"return f'localhost:{self._port}' @property def address(self) -> str: return self._address or self.local_address def start(self):",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"from concurrent import futures from typing import Optional from absl import logging import",
"metadata_store_pb2 def generate_service_stub( address: str, creds: Optional[grpc.ChannelCredentials] = None, ) -> execution_watcher_pb2_grpc.ExecutionWatcherServiceStub: \"\"\"Generates",
"request to update execution info: updates %s, ' 'execution_id %s', request.updates, request.execution_id) if",
"gRPC server credentials. If left as None, server will use an insecure port.",
"to update execution info: updates %s, ' 'execution_id %s', request.updates, request.execution_id) if request.execution_id",
"self._execution.custom_properties[key].CopyFrom( value) # Only the execution is needed with self._mlmd_connection as m: m.store.put_executions((self._execution,))",
"2021 Google LLC. All Rights Reserved. # # Licensed under the Apache License,",
"limitations under the License. \"\"\"This module provides a gRPC service for updating remote",
"not use this file except in compliance with the License. # You may",
"Optional from absl import logging import grpc from tfx.orchestration import metadata from tfx.proto.orchestration",
"import metadata from tfx.proto.orchestration import execution_watcher_pb2 from tfx.proto.orchestration import execution_watcher_pb2_grpc from ml_metadata.proto import",
"self.local_address def start(self): \"\"\"Starts the server.\"\"\" self._server.start() def stop(self): \"\"\"Stops the server.\"\"\" self._server.stop(grace=None)",
"= self._create_server() if not execution.HasField('id'): raise ValueError( 'execution id must be set to",
"by ExecutionWatcher.') self._execution = execution def UpdateExecutionInfo( self, request: execution_watcher_pb2.UpdateExecutionInfoRequest, context: grpc.ServicerContext )",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"use local address. creds: gRPC server credentials. If left as None, server will",
"for updating remote job info to MLMD. Attributes: local_address: Local network address to",
"not tracked by server: ' f'{request.execution_id}') return execution_watcher_pb2.UpdateExecutionInfoResponse() for key, value in request.updates.items():",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"governing permissions and # limitations under the License. \"\"\"This module provides a gRPC",
"use an insecure port. \"\"\" super().__init__() self._port = port self._address = address self._creds",
"module provides a gRPC service for updating remote job info to MLMD.\"\"\" from",
"execution: The MLMD Execution to keep track of. address: Remote address used to",
"# you may not use this file except in compliance with the License.",
"permissions and # limitations under the License. \"\"\"This module provides a gRPC service",
"for a given server address.\"\"\" channel = grpc.secure_channel( address, creds) if creds else",
"-> str: # Local network address to the server. return f'localhost:{self._port}' @property def",
"agreed to in writing, software # distributed under the License is distributed on",
"mlmd_connection: metadata.Metadata, execution: metadata_store_pb2.Execution, address: Optional[str] = None, creds: Optional[grpc.ServerCredentials] = None): \"\"\"Initializes",
"Optional[grpc.ChannelCredentials] = None, ) -> execution_watcher_pb2_grpc.ExecutionWatcherServiceStub: \"\"\"Generates a gRPC service stub for a",
"MLMD. Attributes: local_address: Local network address to the server. address: Remote network address",
"to it.\"\"\" result = grpc.server(futures.ThreadPoolExecutor()) execution_watcher_pb2_grpc.add_ExecutionWatcherServiceServicer_to_server( self, result) if self._creds is None: result.add_insecure_port(self.local_address)",
"(the \"License\"); # you may not use this file except in compliance with",
"given server address.\"\"\" channel = grpc.secure_channel( address, creds) if creds else grpc.insecure_channel(address) return",
"the `custom_properties` field of Execution object in MLMD.\"\"\" logging.info('Received request to update execution",
"be formatted as an ipv4 or ipv6 address in the format `address:port`. If",
"UpdateExecutionInfo( self, request: execution_watcher_pb2.UpdateExecutionInfoRequest, context: grpc.ServicerContext ) -> execution_watcher_pb2.UpdateExecutionInfoResponse: \"\"\"Updates the `custom_properties` field",
"None): \"\"\"Initializes the gRPC server. Args: port: Which port the service will be",
"ml_metadata.proto import metadata_store_pb2 def generate_service_stub( address: str, creds: Optional[grpc.ChannelCredentials] = None, ) ->",
"# Unless required by applicable law or agreed to in writing, software #",
"self._server = self._create_server() if not execution.HasField('id'): raise ValueError( 'execution id must be set",
"by applicable law or agreed to in writing, software # distributed under the",
"= None): \"\"\"Initializes the gRPC server. Args: port: Which port the service will",
"address: Remote address used to contact the server. Should be formatted as an",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"return result @property def local_address(self) -> str: # Local network address to the",
"address.\"\"\" channel = grpc.secure_channel( address, creds) if creds else grpc.insecure_channel(address) return execution_watcher_pb2_grpc.ExecutionWatcherServiceStub(channel) class",
"execution_watcher_pb2_grpc from ml_metadata.proto import metadata_store_pb2 def generate_service_stub( address: str, creds: Optional[grpc.ChannelCredentials] = None,",
"as an ipv4 or ipv6 address in the format `address:port`. If left as",
"\"\"\" super().__init__() self._port = port self._address = address self._creds = creds self._mlmd_connection =",
"be tracked by ExecutionWatcher.') self._execution = execution def UpdateExecutionInfo( self, request: execution_watcher_pb2.UpdateExecutionInfoRequest, context:",
"The MLMD Execution to keep track of. address: Remote address used to contact",
"mlmd_connection self._server = self._create_server() if not execution.HasField('id'): raise ValueError( 'execution id must be",
"insecure port. \"\"\" super().__init__() self._port = port self._address = address self._creds = creds",
"file except in compliance with the License. # You may obtain a copy",
"if creds else grpc.insecure_channel(address) return execution_watcher_pb2_grpc.ExecutionWatcherServiceStub(channel) class ExecutionWatcher( execution_watcher_pb2_grpc.ExecutionWatcherServiceServicer): \"\"\"A gRPC service server",
"service server for updating remote job info to MLMD. Attributes: local_address: Local network",
"' 'execution_id %s', request.updates, request.execution_id) if request.execution_id != self._execution.id: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details( 'Execution with",
"# Local network address to the server. return f'localhost:{self._port}' @property def address(self) ->",
"creds self._mlmd_connection = mlmd_connection self._server = self._create_server() if not execution.HasField('id'): raise ValueError( 'execution",
"License for the specific language governing permissions and # limitations under the License.",
"metadata connection. execution: The MLMD Execution to keep track of. address: Remote address",
"'execution_id %s', request.updates, request.execution_id) if request.execution_id != self._execution.id: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details( 'Execution with given",
"stub for a given server address.\"\"\" channel = grpc.secure_channel( address, creds) if creds",
"to in writing, software # distributed under the License is distributed on an",
"for updating remote job info to MLMD.\"\"\" from concurrent import futures from typing",
"Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version",
"implied. # See the License for the specific language governing permissions and #",
"\"License\"); # you may not use this file except in compliance with the",
"used to contact the server. Should be formatted as an ipv4 or ipv6",
"Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"ValueError( 'execution id must be set to be tracked by ExecutionWatcher.') self._execution =",
"under the License. \"\"\"This module provides a gRPC service for updating remote job",
"format `address:port`. If left as None, server will use local address. creds: gRPC",
"network address to the server. return f'localhost:{self._port}' @property def address(self) -> str: return",
"a given server address.\"\"\" channel = grpc.secure_channel( address, creds) if creds else grpc.insecure_channel(address)",
"the server, same as local_address if not configured. \"\"\" def __init__(self, port: int,",
"`custom_properties` field of Execution object in MLMD.\"\"\" logging.info('Received request to update execution info:",
"or implied. # See the License for the specific language governing permissions and",
"tfx.proto.orchestration import execution_watcher_pb2_grpc from ml_metadata.proto import metadata_store_pb2 def generate_service_stub( address: str, creds: Optional[grpc.ChannelCredentials]",
"updating remote job info to MLMD.\"\"\" from concurrent import futures from typing import",
"connection. execution: The MLMD Execution to keep track of. address: Remote address used",
"the server. return f'localhost:{self._port}' @property def address(self) -> str: return self._address or self.local_address",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"the gRPC server. Args: port: Which port the service will be using. mlmd_connection:",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"server, same as local_address if not configured. \"\"\" def __init__(self, port: int, mlmd_connection:",
"tfx.orchestration import metadata from tfx.proto.orchestration import execution_watcher_pb2 from tfx.proto.orchestration import execution_watcher_pb2_grpc from ml_metadata.proto",
"str: return self._address or self.local_address def start(self): \"\"\"Starts the server.\"\"\" self._server.start() def stop(self):",
"tracked by ExecutionWatcher.') self._execution = execution def UpdateExecutionInfo( self, request: execution_watcher_pb2.UpdateExecutionInfoRequest, context: grpc.ServicerContext",
"local address. creds: gRPC server credentials. If left as None, server will use",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"def address(self) -> str: return self._address or self.local_address def start(self): \"\"\"Starts the server.\"\"\"",
"address in the format `address:port`. If left as None, server will use local",
"in writing, software # distributed under the License is distributed on an \"AS",
"License. \"\"\"This module provides a gRPC service for updating remote job info to",
"address to the server, same as local_address if not configured. \"\"\" def __init__(self,",
"Only the execution is needed with self._mlmd_connection as m: m.store.put_executions((self._execution,)) return execution_watcher_pb2.UpdateExecutionInfoResponse() def",
"result) if self._creds is None: result.add_insecure_port(self.local_address) else: result.add_secure_port(self.local_address, self._creds) return result @property def",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"local_address if not configured. \"\"\" def __init__(self, port: int, mlmd_connection: metadata.Metadata, execution: metadata_store_pb2.Execution,",
"using. mlmd_connection: ML metadata connection. execution: The MLMD Execution to keep track of.",
"\"\"\"Generates a gRPC service stub for a given server address.\"\"\" channel = grpc.secure_channel(",
"import logging import grpc from tfx.orchestration import metadata from tfx.proto.orchestration import execution_watcher_pb2 from",
"address: Optional[str] = None, creds: Optional[grpc.ServerCredentials] = None): \"\"\"Initializes the gRPC server. Args:",
"local_address: Local network address to the server. address: Remote network address to the",
"provides a gRPC service for updating remote job info to MLMD.\"\"\" from concurrent",
"__init__(self, port: int, mlmd_connection: metadata.Metadata, execution: metadata_store_pb2.Execution, address: Optional[str] = None, creds: Optional[grpc.ServerCredentials]",
"logging.info('Received request to update execution info: updates %s, ' 'execution_id %s', request.updates, request.execution_id)",
"If left as None, server will use an insecure port. \"\"\" super().__init__() self._port",
"str: # Local network address to the server. return f'localhost:{self._port}' @property def address(self)",
"self._creds is None: result.add_insecure_port(self.local_address) else: result.add_secure_port(self.local_address, self._creds) return result @property def local_address(self) ->",
"self._address or self.local_address def start(self): \"\"\"Starts the server.\"\"\" self._server.start() def stop(self): \"\"\"Stops the",
"service for updating remote job info to MLMD.\"\"\" from concurrent import futures from",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"a gRPC service stub for a given server address.\"\"\" channel = grpc.secure_channel( address,",
"you may not use this file except in compliance with the License. #",
"self._mlmd_connection = mlmd_connection self._server = self._create_server() if not execution.HasField('id'): raise ValueError( 'execution id",
"of Execution object in MLMD.\"\"\" logging.info('Received request to update execution info: updates %s,",
"= grpc.server(futures.ThreadPoolExecutor()) execution_watcher_pb2_grpc.add_ExecutionWatcherServiceServicer_to_server( self, result) if self._creds is None: result.add_insecure_port(self.local_address) else: result.add_secure_port(self.local_address, self._creds)",
"= None, ) -> execution_watcher_pb2_grpc.ExecutionWatcherServiceStub: \"\"\"Generates a gRPC service stub for a given",
"MLMD Execution to keep track of. address: Remote address used to contact the",
"typing import Optional from absl import logging import grpc from tfx.orchestration import metadata",
"server and add `self` on to it.\"\"\" result = grpc.server(futures.ThreadPoolExecutor()) execution_watcher_pb2_grpc.add_ExecutionWatcherServiceServicer_to_server( self, result)",
"network address to the server, same as local_address if not configured. \"\"\" def",
"use this file except in compliance with the License. # You may obtain",
"an insecure port. \"\"\" super().__init__() self._port = port self._address = address self._creds =",
"gRPC server and add `self` on to it.\"\"\" result = grpc.server(futures.ThreadPoolExecutor()) execution_watcher_pb2_grpc.add_ExecutionWatcherServiceServicer_to_server( self,",
"= execution def UpdateExecutionInfo( self, request: execution_watcher_pb2.UpdateExecutionInfoRequest, context: grpc.ServicerContext ) -> execution_watcher_pb2.UpdateExecutionInfoResponse: \"\"\"Updates",
"def UpdateExecutionInfo( self, request: execution_watcher_pb2.UpdateExecutionInfoRequest, context: grpc.ServicerContext ) -> execution_watcher_pb2.UpdateExecutionInfoResponse: \"\"\"Updates the `custom_properties`",
"same as local_address if not configured. \"\"\" def __init__(self, port: int, mlmd_connection: metadata.Metadata,",
"left as None, server will use local address. creds: gRPC server credentials. If",
"context.set_details( 'Execution with given execution_id not tracked by server: ' f'{request.execution_id}') return execution_watcher_pb2.UpdateExecutionInfoResponse()",
") -> execution_watcher_pb2.UpdateExecutionInfoResponse: \"\"\"Updates the `custom_properties` field of Execution object in MLMD.\"\"\" logging.info('Received",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"gRPC service for updating remote job info to MLMD.\"\"\" from concurrent import futures",
"ML metadata connection. execution: The MLMD Execution to keep track of. address: Remote",
"Execution object in MLMD.\"\"\" logging.info('Received request to update execution info: updates %s, '",
"of. address: Remote address used to contact the server. Should be formatted as",
"result.add_secure_port(self.local_address, self._creds) return result @property def local_address(self) -> str: # Local network address",
"self, result) if self._creds is None: result.add_insecure_port(self.local_address) else: result.add_secure_port(self.local_address, self._creds) return result @property",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"as None, server will use an insecure port. \"\"\" super().__init__() self._port = port",
"result @property def local_address(self) -> str: # Local network address to the server.",
"to the server, same as local_address if not configured. \"\"\" def __init__(self, port:",
"port the service will be using. mlmd_connection: ML metadata connection. execution: The MLMD",
"address. creds: gRPC server credentials. If left as None, server will use an",
"will use an insecure port. \"\"\" super().__init__() self._port = port self._address = address",
"from tfx.orchestration import metadata from tfx.proto.orchestration import execution_watcher_pb2 from tfx.proto.orchestration import execution_watcher_pb2_grpc from",
"super().__init__() self._port = port self._address = address self._creds = creds self._mlmd_connection = mlmd_connection",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"def __init__(self, port: int, mlmd_connection: metadata.Metadata, execution: metadata_store_pb2.Execution, address: Optional[str] = None, creds:",
"Execution to keep track of. address: Remote address used to contact the server.",
"self._port = port self._address = address self._creds = creds self._mlmd_connection = mlmd_connection self._server",
"MLMD.\"\"\" logging.info('Received request to update execution info: updates %s, ' 'execution_id %s', request.updates,",
"creds: Optional[grpc.ChannelCredentials] = None, ) -> execution_watcher_pb2_grpc.ExecutionWatcherServiceStub: \"\"\"Generates a gRPC service stub for",
"# # Unless required by applicable law or agreed to in writing, software",
"self._address = address self._creds = creds self._mlmd_connection = mlmd_connection self._server = self._create_server() if",
"express or implied. # See the License for the specific language governing permissions",
"self, request: execution_watcher_pb2.UpdateExecutionInfoRequest, context: grpc.ServicerContext ) -> execution_watcher_pb2.UpdateExecutionInfoResponse: \"\"\"Updates the `custom_properties` field of",
"f'localhost:{self._port}' @property def address(self) -> str: return self._address or self.local_address def start(self): \"\"\"Starts",
"either express or implied. # See the License for the specific language governing",
"def local_address(self) -> str: # Local network address to the server. return f'localhost:{self._port}'",
"self._creds) return result @property def local_address(self) -> str: # Local network address to",
"server credentials. If left as None, server will use an insecure port. \"\"\"",
"a gRPC service for updating remote job info to MLMD.\"\"\" from concurrent import",
"if not execution.HasField('id'): raise ValueError( 'execution id must be set to be tracked",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"execution def UpdateExecutionInfo( self, request: execution_watcher_pb2.UpdateExecutionInfoRequest, context: grpc.ServicerContext ) -> execution_watcher_pb2.UpdateExecutionInfoResponse: \"\"\"Updates the",
"= None, creds: Optional[grpc.ServerCredentials] = None): \"\"\"Initializes the gRPC server. Args: port: Which",
"<filename>tfx/orchestration/portable/execution_watcher.py # Copyright 2021 Google LLC. All Rights Reserved. # # Licensed under",
"address(self) -> str: return self._address or self.local_address def start(self): \"\"\"Starts the server.\"\"\" self._server.start()",
"generate_service_stub( address: str, creds: Optional[grpc.ChannelCredentials] = None, ) -> execution_watcher_pb2_grpc.ExecutionWatcherServiceStub: \"\"\"Generates a gRPC",
"' f'{request.execution_id}') return execution_watcher_pb2.UpdateExecutionInfoResponse() for key, value in request.updates.items(): self._execution.custom_properties[key].CopyFrom( value) # Only",
"None, server will use local address. creds: gRPC server credentials. If left as",
"-> execution_watcher_pb2.UpdateExecutionInfoResponse: \"\"\"Updates the `custom_properties` field of Execution object in MLMD.\"\"\" logging.info('Received request",
"given execution_id not tracked by server: ' f'{request.execution_id}') return execution_watcher_pb2.UpdateExecutionInfoResponse() for key, value",
"the License. # You may obtain a copy of the License at #",
"with given execution_id not tracked by server: ' f'{request.execution_id}') return execution_watcher_pb2.UpdateExecutionInfoResponse() for key,",
"server. address: Remote network address to the server, same as local_address if not",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"port. \"\"\" super().__init__() self._port = port self._address = address self._creds = creds self._mlmd_connection",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"server. Args: port: Which port the service will be using. mlmd_connection: ML metadata",
"\"\"\" def __init__(self, port: int, mlmd_connection: metadata.Metadata, execution: metadata_store_pb2.Execution, address: Optional[str] = None,",
"\"\"\"A gRPC service server for updating remote job info to MLMD. Attributes: local_address:",
"self._create_server() if not execution.HasField('id'): raise ValueError( 'execution id must be set to be",
"by server: ' f'{request.execution_id}') return execution_watcher_pb2.UpdateExecutionInfoResponse() for key, value in request.updates.items(): self._execution.custom_properties[key].CopyFrom( value)",
"return execution_watcher_pb2.UpdateExecutionInfoResponse() for key, value in request.updates.items(): self._execution.custom_properties[key].CopyFrom( value) # Only the execution",
"to be tracked by ExecutionWatcher.') self._execution = execution def UpdateExecutionInfo( self, request: execution_watcher_pb2.UpdateExecutionInfoRequest,",
"def generate_service_stub( address: str, creds: Optional[grpc.ChannelCredentials] = None, ) -> execution_watcher_pb2_grpc.ExecutionWatcherServiceStub: \"\"\"Generates a",
"will use local address. creds: gRPC server credentials. If left as None, server",
"None: result.add_insecure_port(self.local_address) else: result.add_secure_port(self.local_address, self._creds) return result @property def local_address(self) -> str: #",
"execution_watcher_pb2_grpc.ExecutionWatcherServiceStub(channel) class ExecutionWatcher( execution_watcher_pb2_grpc.ExecutionWatcherServiceServicer): \"\"\"A gRPC service server for updating remote job info",
"in the format `address:port`. If left as None, server will use local address.",
"address self._creds = creds self._mlmd_connection = mlmd_connection self._server = self._create_server() if not execution.HasField('id'):",
"address to the server. address: Remote network address to the server, same as",
"to MLMD.\"\"\" from concurrent import futures from typing import Optional from absl import",
"for key, value in request.updates.items(): self._execution.custom_properties[key].CopyFrom( value) # Only the execution is needed",
"the server. address: Remote network address to the server, same as local_address if",
"-> str: return self._address or self.local_address def start(self): \"\"\"Starts the server.\"\"\" self._server.start() def",
"with the License. # You may obtain a copy of the License at",
"gRPC service stub for a given server address.\"\"\" channel = grpc.secure_channel( address, creds)",
"grpc.ServicerContext ) -> execution_watcher_pb2.UpdateExecutionInfoResponse: \"\"\"Updates the `custom_properties` field of Execution object in MLMD.\"\"\"",
"request.execution_id) if request.execution_id != self._execution.id: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details( 'Execution with given execution_id not tracked",
"_create_server(self): \"\"\"Creates a gRPC server and add `self` on to it.\"\"\" result =",
"return execution_watcher_pb2_grpc.ExecutionWatcherServiceStub(channel) class ExecutionWatcher( execution_watcher_pb2_grpc.ExecutionWatcherServiceServicer): \"\"\"A gRPC service server for updating remote job",
"Optional[grpc.ServerCredentials] = None): \"\"\"Initializes the gRPC server. Args: port: Which port the service",
"'execution id must be set to be tracked by ExecutionWatcher.') self._execution = execution",
"info to MLMD. Attributes: local_address: Local network address to the server. address: Remote",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"grpc from tfx.orchestration import metadata from tfx.proto.orchestration import execution_watcher_pb2 from tfx.proto.orchestration import execution_watcher_pb2_grpc",
"-> execution_watcher_pb2_grpc.ExecutionWatcherServiceStub: \"\"\"Generates a gRPC service stub for a given server address.\"\"\" channel",
"is needed with self._mlmd_connection as m: m.store.put_executions((self._execution,)) return execution_watcher_pb2.UpdateExecutionInfoResponse() def _create_server(self): \"\"\"Creates a",
"execution_watcher_pb2_grpc.ExecutionWatcherServiceServicer): \"\"\"A gRPC service server for updating remote job info to MLMD. Attributes:",
"configured. \"\"\" def __init__(self, port: int, mlmd_connection: metadata.Metadata, execution: metadata_store_pb2.Execution, address: Optional[str] =",
"service will be using. mlmd_connection: ML metadata connection. execution: The MLMD Execution to",
"set to be tracked by ExecutionWatcher.') self._execution = execution def UpdateExecutionInfo( self, request:",
"law or agreed to in writing, software # distributed under the License is",
"result.add_insecure_port(self.local_address) else: result.add_secure_port(self.local_address, self._creds) return result @property def local_address(self) -> str: # Local",
"the License for the specific language governing permissions and # limitations under the",
"self._creds = creds self._mlmd_connection = mlmd_connection self._server = self._create_server() if not execution.HasField('id'): raise",
"return execution_watcher_pb2.UpdateExecutionInfoResponse() def _create_server(self): \"\"\"Creates a gRPC server and add `self` on to",
"an ipv4 or ipv6 address in the format `address:port`. If left as None,",
"not execution.HasField('id'): raise ValueError( 'execution id must be set to be tracked by",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"request.execution_id != self._execution.id: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details( 'Execution with given execution_id not tracked by server:",
"id must be set to be tracked by ExecutionWatcher.') self._execution = execution def",
"credentials. If left as None, server will use an insecure port. \"\"\" super().__init__()",
"from tfx.proto.orchestration import execution_watcher_pb2_grpc from ml_metadata.proto import metadata_store_pb2 def generate_service_stub( address: str, creds:",
"is None: result.add_insecure_port(self.local_address) else: result.add_secure_port(self.local_address, self._creds) return result @property def local_address(self) -> str:",
"Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"import futures from typing import Optional from absl import logging import grpc from",
"in compliance with the License. # You may obtain a copy of the",
"execution_watcher_pb2.UpdateExecutionInfoResponse() def _create_server(self): \"\"\"Creates a gRPC server and add `self` on to it.\"\"\"",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"= creds self._mlmd_connection = mlmd_connection self._server = self._create_server() if not execution.HasField('id'): raise ValueError(",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"return self._address or self.local_address def start(self): \"\"\"Starts the server.\"\"\" self._server.start() def stop(self): \"\"\"Stops",
"tfx.proto.orchestration import execution_watcher_pb2 from tfx.proto.orchestration import execution_watcher_pb2_grpc from ml_metadata.proto import metadata_store_pb2 def generate_service_stub(",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"address: str, creds: Optional[grpc.ChannelCredentials] = None, ) -> execution_watcher_pb2_grpc.ExecutionWatcherServiceStub: \"\"\"Generates a gRPC service",
"See the License for the specific language governing permissions and # limitations under",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"value in request.updates.items(): self._execution.custom_properties[key].CopyFrom( value) # Only the execution is needed with self._mlmd_connection",
"If left as None, server will use local address. creds: gRPC server credentials.",
"server. Should be formatted as an ipv4 or ipv6 address in the format",
"add `self` on to it.\"\"\" result = grpc.server(futures.ThreadPoolExecutor()) execution_watcher_pb2_grpc.add_ExecutionWatcherServiceServicer_to_server( self, result) if self._creds",
"update execution info: updates %s, ' 'execution_id %s', request.updates, request.execution_id) if request.execution_id !=",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"server will use an insecure port. \"\"\" super().__init__() self._port = port self._address =",
"Which port the service will be using. mlmd_connection: ML metadata connection. execution: The",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"@property def address(self) -> str: return self._address or self.local_address def start(self): \"\"\"Starts the",
"f'{request.execution_id}') return execution_watcher_pb2.UpdateExecutionInfoResponse() for key, value in request.updates.items(): self._execution.custom_properties[key].CopyFrom( value) # Only the",
"ipv4 or ipv6 address in the format `address:port`. If left as None, server",
"Local network address to the server. return f'localhost:{self._port}' @property def address(self) -> str:",
"context: grpc.ServicerContext ) -> execution_watcher_pb2.UpdateExecutionInfoResponse: \"\"\"Updates the `custom_properties` field of Execution object in",
"port self._address = address self._creds = creds self._mlmd_connection = mlmd_connection self._server = self._create_server()",
"to the server. address: Remote network address to the server, same as local_address",
"context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details( 'Execution with given execution_id not tracked by server: ' f'{request.execution_id}') return",
"be set to be tracked by ExecutionWatcher.') self._execution = execution def UpdateExecutionInfo( self,",
"execution info: updates %s, ' 'execution_id %s', request.updates, request.execution_id) if request.execution_id != self._execution.id:",
"request.updates, request.execution_id) if request.execution_id != self._execution.id: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details( 'Execution with given execution_id not",
"ipv6 address in the format `address:port`. If left as None, server will use",
"channel = grpc.secure_channel( address, creds) if creds else grpc.insecure_channel(address) return execution_watcher_pb2_grpc.ExecutionWatcherServiceStub(channel) class ExecutionWatcher(",
"in request.updates.items(): self._execution.custom_properties[key].CopyFrom( value) # Only the execution is needed with self._mlmd_connection as",
"job info to MLMD.\"\"\" from concurrent import futures from typing import Optional from",
"Should be formatted as an ipv4 or ipv6 address in the format `address:port`.",
"be using. mlmd_connection: ML metadata connection. execution: The MLMD Execution to keep track",
"ExecutionWatcher.') self._execution = execution def UpdateExecutionInfo( self, request: execution_watcher_pb2.UpdateExecutionInfoRequest, context: grpc.ServicerContext ) ->",
"value) # Only the execution is needed with self._mlmd_connection as m: m.store.put_executions((self._execution,)) return",
"\"\"\"Updates the `custom_properties` field of Execution object in MLMD.\"\"\" logging.info('Received request to update",
"gRPC service server for updating remote job info to MLMD. Attributes: local_address: Local",
"address, creds) if creds else grpc.insecure_channel(address) return execution_watcher_pb2_grpc.ExecutionWatcherServiceStub(channel) class ExecutionWatcher( execution_watcher_pb2_grpc.ExecutionWatcherServiceServicer): \"\"\"A gRPC",
"import grpc from tfx.orchestration import metadata from tfx.proto.orchestration import execution_watcher_pb2 from tfx.proto.orchestration import",
"self._mlmd_connection as m: m.store.put_executions((self._execution,)) return execution_watcher_pb2.UpdateExecutionInfoResponse() def _create_server(self): \"\"\"Creates a gRPC server and",
"`address:port`. If left as None, server will use local address. creds: gRPC server",
"info to MLMD.\"\"\" from concurrent import futures from typing import Optional from absl",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"except in compliance with the License. # You may obtain a copy of",
"to MLMD. Attributes: local_address: Local network address to the server. address: Remote network",
"address used to contact the server. Should be formatted as an ipv4 or",
"\"\"\"Creates a gRPC server and add `self` on to it.\"\"\" result = grpc.server(futures.ThreadPoolExecutor())",
"raise ValueError( 'execution id must be set to be tracked by ExecutionWatcher.') self._execution",
"key, value in request.updates.items(): self._execution.custom_properties[key].CopyFrom( value) # Only the execution is needed with",
"the server. Should be formatted as an ipv4 or ipv6 address in the",
"# Copyright 2021 Google LLC. All Rights Reserved. # # Licensed under the",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"from absl import logging import grpc from tfx.orchestration import metadata from tfx.proto.orchestration import",
"# Only the execution is needed with self._mlmd_connection as m: m.store.put_executions((self._execution,)) return execution_watcher_pb2.UpdateExecutionInfoResponse()",
"must be set to be tracked by ExecutionWatcher.') self._execution = execution def UpdateExecutionInfo(",
"else grpc.insecure_channel(address) return execution_watcher_pb2_grpc.ExecutionWatcherServiceStub(channel) class ExecutionWatcher( execution_watcher_pb2_grpc.ExecutionWatcherServiceServicer): \"\"\"A gRPC service server for updating",
"from ml_metadata.proto import metadata_store_pb2 def generate_service_stub( address: str, creds: Optional[grpc.ChannelCredentials] = None, )",
"Remote network address to the server, same as local_address if not configured. \"\"\"",
"job info to MLMD. Attributes: local_address: Local network address to the server. address:",
"execution: metadata_store_pb2.Execution, address: Optional[str] = None, creds: Optional[grpc.ServerCredentials] = None): \"\"\"Initializes the gRPC",
"server will use local address. creds: gRPC server credentials. If left as None,",
"from typing import Optional from absl import logging import grpc from tfx.orchestration import",
"object in MLMD.\"\"\" logging.info('Received request to update execution info: updates %s, ' 'execution_id",
"to keep track of. address: Remote address used to contact the server. Should",
"will be using. mlmd_connection: ML metadata connection. execution: The MLMD Execution to keep",
"concurrent import futures from typing import Optional from absl import logging import grpc",
"Copyright 2021 Google LLC. All Rights Reserved. # # Licensed under the Apache",
"= port self._address = address self._creds = creds self._mlmd_connection = mlmd_connection self._server =",
"result = grpc.server(futures.ThreadPoolExecutor()) execution_watcher_pb2_grpc.add_ExecutionWatcherServiceServicer_to_server( self, result) if self._creds is None: result.add_insecure_port(self.local_address) else: result.add_secure_port(self.local_address,",
"tracked by server: ' f'{request.execution_id}') return execution_watcher_pb2.UpdateExecutionInfoResponse() for key, value in request.updates.items(): self._execution.custom_properties[key].CopyFrom(",
"grpc.secure_channel( address, creds) if creds else grpc.insecure_channel(address) return execution_watcher_pb2_grpc.ExecutionWatcherServiceStub(channel) class ExecutionWatcher( execution_watcher_pb2_grpc.ExecutionWatcherServiceServicer): \"\"\"A",
"left as None, server will use an insecure port. \"\"\" super().__init__() self._port =",
"%s, ' 'execution_id %s', request.updates, request.execution_id) if request.execution_id != self._execution.id: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details( 'Execution",
"grpc.server(futures.ThreadPoolExecutor()) execution_watcher_pb2_grpc.add_ExecutionWatcherServiceServicer_to_server( self, result) if self._creds is None: result.add_insecure_port(self.local_address) else: result.add_secure_port(self.local_address, self._creds) return",
"import execution_watcher_pb2_grpc from ml_metadata.proto import metadata_store_pb2 def generate_service_stub( address: str, creds: Optional[grpc.ChannelCredentials] =",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"self._execution.id: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details( 'Execution with given execution_id not tracked by server: ' f'{request.execution_id}')",
"%s', request.updates, request.execution_id) if request.execution_id != self._execution.id: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details( 'Execution with given execution_id",
"gRPC server. Args: port: Which port the service will be using. mlmd_connection: ML",
"track of. address: Remote address used to contact the server. Should be formatted",
"creds) if creds else grpc.insecure_channel(address) return execution_watcher_pb2_grpc.ExecutionWatcherServiceStub(channel) class ExecutionWatcher( execution_watcher_pb2_grpc.ExecutionWatcherServiceServicer): \"\"\"A gRPC service",
"# limitations under the License. \"\"\"This module provides a gRPC service for updating"
] |
[
"get_options() ##{ 临时改超参数 opt.gpu = '1' opt.batch_size = 1 opt.max_epochs = 160 opt.method",
"opt def seed_torch(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if",
"train_attr_vecs, test_attr_vecs = load_data( data_filepath=opt.data_dir, ) modeldict, logdict = train_cpgan(graphs, train_adj_mats, train_attr_vecs, opt)",
"== '__main__': opt = get_options() ##{ 临时改超参数 opt.gpu = '1' opt.batch_size = 1",
"are using multi-GPU. # torch.backends.cudnn.benchmark = False # torch.backends.cudnn.deterministic = True if __name__",
"torch.cuda.manual_seed_all(seed) # if you are using multi-GPU. # torch.backends.cudnn.benchmark = False # torch.backends.cudnn.deterministic",
"} os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpu seed = int(time.time()*opt.random_seed) % (2**32) seed_torch(seed=seed) print('=========== OPTIONS ===========')",
"# torch.backends.cudnn.deterministic = True if __name__ == '__main__': opt = get_options() ##{ 临时改超参数",
"import numpy as np from CPGAN.options import * from CPGAN.train import * warnings.filterwarnings(\"ignore\")",
"= False # torch.backends.cudnn.deterministic = True if __name__ == '__main__': opt = get_options()",
"= '1' opt.batch_size = 1 opt.max_epochs = 160 opt.method = 'cpgan' opt.graph_type =",
"= 160 opt.method = 'cpgan' opt.graph_type = \"yeast\" opt.data_dir = \"./data\" ## 正式训练时收起",
"\"./data\" ## 正式训练时收起 } os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpu seed = int(time.time()*opt.random_seed) % (2**32) seed_torch(seed=seed)",
"opt.initialize() return opt def seed_torch(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed)",
"warnings.filterwarnings(\"ignore\") def get_options(): opt = Options() opt = opt.initialize() return opt def seed_torch(seed=1029):",
"160 opt.method = 'cpgan' opt.graph_type = \"yeast\" opt.data_dir = \"./data\" ## 正式训练时收起 }",
"opt.method = 'cpgan' opt.graph_type = \"yeast\" opt.data_dir = \"./data\" ## 正式训练时收起 } os.environ['CUDA_VISIBLE_DEVICES']",
"import * warnings.filterwarnings(\"ignore\") def get_options(): opt = Options() opt = opt.initialize() return opt",
"* import numpy as np from CPGAN.options import * from CPGAN.train import *",
"# if you are using multi-GPU. # torch.backends.cudnn.benchmark = False # torch.backends.cudnn.deterministic =",
"% (2**32) seed_torch(seed=seed) print('=========== OPTIONS ===========') pprint.pprint(vars(opt)) print(' ======== END OPTIONS ========\\n\\n') graphs",
"multi-GPU. # torch.backends.cudnn.benchmark = False # torch.backends.cudnn.deterministic = True if __name__ == '__main__':",
"Options() opt = opt.initialize() return opt def seed_torch(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed)",
"= opt.initialize() return opt def seed_torch(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed)",
"CPGAN.train import * warnings.filterwarnings(\"ignore\") def get_options(): opt = Options() opt = opt.initialize() return",
"as np from CPGAN.options import * from CPGAN.train import * warnings.filterwarnings(\"ignore\") def get_options():",
"CPGAN.options import * from CPGAN.train import * warnings.filterwarnings(\"ignore\") def get_options(): opt = Options()",
"get_options(): opt = Options() opt = opt.initialize() return opt def seed_torch(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED']",
"import * import numpy as np from CPGAN.options import * from CPGAN.train import",
"* warnings.filterwarnings(\"ignore\") def get_options(): opt = Options() opt = opt.initialize() return opt def",
"you are using multi-GPU. # torch.backends.cudnn.benchmark = False # torch.backends.cudnn.deterministic = True if",
"torch.backends.cudnn.benchmark = False # torch.backends.cudnn.deterministic = True if __name__ == '__main__': opt =",
"= train_adj_mats, test_adj_mats, train_attr_vecs, test_attr_vecs = load_data( data_filepath=opt.data_dir, ) modeldict, logdict = train_cpgan(graphs,",
"opt.gpu = '1' opt.batch_size = 1 opt.max_epochs = 160 opt.method = 'cpgan' opt.graph_type",
"pprint, os, random, torch from CPGAN.data_utils import * import numpy as np from",
"'1' opt.batch_size = 1 opt.max_epochs = 160 opt.method = 'cpgan' opt.graph_type = \"yeast\"",
"from CPGAN.train import * warnings.filterwarnings(\"ignore\") def get_options(): opt = Options() opt = opt.initialize()",
"int(time.time()*opt.random_seed) % (2**32) seed_torch(seed=seed) print('=========== OPTIONS ===========') pprint.pprint(vars(opt)) print(' ======== END OPTIONS ========\\n\\n')",
"1 opt.max_epochs = 160 opt.method = 'cpgan' opt.graph_type = \"yeast\" opt.data_dir = \"./data\"",
"test_adj_mats, train_attr_vecs, test_attr_vecs = load_data( data_filepath=opt.data_dir, ) modeldict, logdict = train_cpgan(graphs, train_adj_mats, train_attr_vecs,",
"opt = get_options() ##{ 临时改超参数 opt.gpu = '1' opt.batch_size = 1 opt.max_epochs =",
"__name__ == '__main__': opt = get_options() ##{ 临时改超参数 opt.gpu = '1' opt.batch_size =",
"= get_options() ##{ 临时改超参数 opt.gpu = '1' opt.batch_size = 1 opt.max_epochs = 160",
"graphs = train_adj_mats, test_adj_mats, train_attr_vecs, test_attr_vecs = load_data( data_filepath=opt.data_dir, ) modeldict, logdict =",
"= \"yeast\" opt.data_dir = \"./data\" ## 正式训练时收起 } os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpu seed =",
"import warnings import pprint, os, random, torch from CPGAN.data_utils import * import numpy",
"False # torch.backends.cudnn.deterministic = True if __name__ == '__main__': opt = get_options() ##{",
"正式训练时收起 } os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpu seed = int(time.time()*opt.random_seed) % (2**32) seed_torch(seed=seed) print('=========== OPTIONS",
"from CPGAN.data_utils import * import numpy as np from CPGAN.options import * from",
"opt.gpu seed = int(time.time()*opt.random_seed) % (2**32) seed_torch(seed=seed) print('=========== OPTIONS ===========') pprint.pprint(vars(opt)) print(' ========",
"numpy as np from CPGAN.options import * from CPGAN.train import * warnings.filterwarnings(\"ignore\") def",
"from CPGAN.options import * from CPGAN.train import * warnings.filterwarnings(\"ignore\") def get_options(): opt =",
"using multi-GPU. # torch.backends.cudnn.benchmark = False # torch.backends.cudnn.deterministic = True if __name__ ==",
"import * from CPGAN.train import * warnings.filterwarnings(\"ignore\") def get_options(): opt = Options() opt",
"'cpgan' opt.graph_type = \"yeast\" opt.data_dir = \"./data\" ## 正式训练时收起 } os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpu",
"np from CPGAN.options import * from CPGAN.train import * warnings.filterwarnings(\"ignore\") def get_options(): opt",
"torch.backends.cudnn.deterministic = True if __name__ == '__main__': opt = get_options() ##{ 临时改超参数 opt.gpu",
"seed_torch(seed=seed) print('=========== OPTIONS ===========') pprint.pprint(vars(opt)) print(' ======== END OPTIONS ========\\n\\n') graphs = train_adj_mats,",
"<filename>main.py import warnings import pprint, os, random, torch from CPGAN.data_utils import * import",
"opt.data_dir = \"./data\" ## 正式训练时收起 } os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpu seed = int(time.time()*opt.random_seed) %",
"True if __name__ == '__main__': opt = get_options() ##{ 临时改超参数 opt.gpu = '1'",
"##{ 临时改超参数 opt.gpu = '1' opt.batch_size = 1 opt.max_epochs = 160 opt.method =",
"opt.batch_size = 1 opt.max_epochs = 160 opt.method = 'cpgan' opt.graph_type = \"yeast\" opt.data_dir",
"= True if __name__ == '__main__': opt = get_options() ##{ 临时改超参数 opt.gpu =",
"======== END OPTIONS ========\\n\\n') graphs = train_adj_mats, test_adj_mats, train_attr_vecs, test_attr_vecs = load_data( data_filepath=opt.data_dir,",
"OPTIONS ===========') pprint.pprint(vars(opt)) print(' ======== END OPTIONS ========\\n\\n') graphs = train_adj_mats, test_adj_mats, train_attr_vecs,",
"= \"./data\" ## 正式训练时收起 } os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpu seed = int(time.time()*opt.random_seed) % (2**32)",
"= Options() opt = opt.initialize() return opt def seed_torch(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed)",
"str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if you are using multi-GPU. # torch.backends.cudnn.benchmark",
"os, random, torch from CPGAN.data_utils import * import numpy as np from CPGAN.options",
"\"yeast\" opt.data_dir = \"./data\" ## 正式训练时收起 } os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpu seed = int(time.time()*opt.random_seed)",
"= int(time.time()*opt.random_seed) % (2**32) seed_torch(seed=seed) print('=========== OPTIONS ===========') pprint.pprint(vars(opt)) print(' ======== END OPTIONS",
"opt.max_epochs = 160 opt.method = 'cpgan' opt.graph_type = \"yeast\" opt.data_dir = \"./data\" ##",
"opt.graph_type = \"yeast\" opt.data_dir = \"./data\" ## 正式训练时收起 } os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpu seed",
"train_adj_mats, test_adj_mats, train_attr_vecs, test_attr_vecs = load_data( data_filepath=opt.data_dir, ) modeldict, logdict = train_cpgan(graphs, train_adj_mats,",
"def get_options(): opt = Options() opt = opt.initialize() return opt def seed_torch(seed=1029): random.seed(seed)",
"opt = Options() opt = opt.initialize() return opt def seed_torch(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED'] =",
"torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if you are using multi-GPU. # torch.backends.cudnn.benchmark = False #",
"os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpu seed = int(time.time()*opt.random_seed) % (2**32) seed_torch(seed=seed) print('=========== OPTIONS ===========') pprint.pprint(vars(opt))",
"print(' ======== END OPTIONS ========\\n\\n') graphs = train_adj_mats, test_adj_mats, train_attr_vecs, test_attr_vecs = load_data(",
"(2**32) seed_torch(seed=seed) print('=========== OPTIONS ===========') pprint.pprint(vars(opt)) print(' ======== END OPTIONS ========\\n\\n') graphs =",
"import pprint, os, random, torch from CPGAN.data_utils import * import numpy as np",
"# torch.backends.cudnn.benchmark = False # torch.backends.cudnn.deterministic = True if __name__ == '__main__': opt",
"END OPTIONS ========\\n\\n') graphs = train_adj_mats, test_adj_mats, train_attr_vecs, test_attr_vecs = load_data( data_filepath=opt.data_dir, )",
"= 1 opt.max_epochs = 160 opt.method = 'cpgan' opt.graph_type = \"yeast\" opt.data_dir =",
"========\\n\\n') graphs = train_adj_mats, test_adj_mats, train_attr_vecs, test_attr_vecs = load_data( data_filepath=opt.data_dir, ) modeldict, logdict",
"warnings import pprint, os, random, torch from CPGAN.data_utils import * import numpy as",
"* from CPGAN.train import * warnings.filterwarnings(\"ignore\") def get_options(): opt = Options() opt =",
"opt = opt.initialize() return opt def seed_torch(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed)",
"random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if you are using",
"def seed_torch(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if you",
"if you are using multi-GPU. # torch.backends.cudnn.benchmark = False # torch.backends.cudnn.deterministic = True",
"'__main__': opt = get_options() ##{ 临时改超参数 opt.gpu = '1' opt.batch_size = 1 opt.max_epochs",
"print('=========== OPTIONS ===========') pprint.pprint(vars(opt)) print(' ======== END OPTIONS ========\\n\\n') graphs = train_adj_mats, test_adj_mats,",
"seed = int(time.time()*opt.random_seed) % (2**32) seed_torch(seed=seed) print('=========== OPTIONS ===========') pprint.pprint(vars(opt)) print(' ======== END",
"= 'cpgan' opt.graph_type = \"yeast\" opt.data_dir = \"./data\" ## 正式训练时收起 } os.environ['CUDA_VISIBLE_DEVICES'] =",
"torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if you are using multi-GPU. # torch.backends.cudnn.benchmark = False",
"seed_torch(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if you are",
"临时改超参数 opt.gpu = '1' opt.batch_size = 1 opt.max_epochs = 160 opt.method = 'cpgan'",
"return opt def seed_torch(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) #",
"===========') pprint.pprint(vars(opt)) print(' ======== END OPTIONS ========\\n\\n') graphs = train_adj_mats, test_adj_mats, train_attr_vecs, test_attr_vecs",
"pprint.pprint(vars(opt)) print(' ======== END OPTIONS ========\\n\\n') graphs = train_adj_mats, test_adj_mats, train_attr_vecs, test_attr_vecs =",
"= str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if you are using multi-GPU. #",
"torch from CPGAN.data_utils import * import numpy as np from CPGAN.options import *",
"CPGAN.data_utils import * import numpy as np from CPGAN.options import * from CPGAN.train",
"if __name__ == '__main__': opt = get_options() ##{ 临时改超参数 opt.gpu = '1' opt.batch_size",
"os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if you are using multi-GPU.",
"np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if you are using multi-GPU. # torch.backends.cudnn.benchmark =",
"= opt.gpu seed = int(time.time()*opt.random_seed) % (2**32) seed_torch(seed=seed) print('=========== OPTIONS ===========') pprint.pprint(vars(opt)) print('",
"## 正式训练时收起 } os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpu seed = int(time.time()*opt.random_seed) % (2**32) seed_torch(seed=seed) print('===========",
"OPTIONS ========\\n\\n') graphs = train_adj_mats, test_adj_mats, train_attr_vecs, test_attr_vecs = load_data( data_filepath=opt.data_dir, ) modeldict,",
"random, torch from CPGAN.data_utils import * import numpy as np from CPGAN.options import"
] |
[
"rospy.Publisher( '/mavros/setpoint_attitude/attitude', PoseStamped, queue_size=10 ) self._pubs['velocity'] = rospy.Publisher( '/mavros/setpoint_attitude/velocity', PoseStamped, queue_size=10 ) self._pubs['thrust']",
"self._pubs['velocity'] = rospy.Publisher( '/mavros/setpoint_attitude/velocity', PoseStamped, queue_size=10 ) self._pubs['thrust'] = rospy.Publisher( '/mavros/setpoint_attitude/thrust', Thrust, queue_size=10",
"tf.transformations import quaternion_from_euler from geometry_msgs.msg import Point, PoseStamped, Quaternion from mavros_msgs.msg import Thrust",
"geometry_msgs.msg import Point, PoseStamped, Quaternion from mavros_msgs.msg import Thrust class Sender(object): def __init__(self):",
"self._pubs = {} self._pubs['position'] = rospy.Publisher( '/mavros/setpoint_position/local', PoseStamped, queue_size=10 ) self._pubs['attitude'] = rospy.Publisher(",
"= {} self._pubs['position'] = rospy.Publisher( '/mavros/setpoint_position/local', PoseStamped, queue_size=10 ) self._pubs['attitude'] = rospy.Publisher( '/mavros/setpoint_attitude/attitude',",
"rospy from tf.transformations import quaternion_from_euler from geometry_msgs.msg import Point, PoseStamped, Quaternion from mavros_msgs.msg",
") self._pubs['attitude'] = rospy.Publisher( '/mavros/setpoint_attitude/attitude', PoseStamped, queue_size=10 ) self._pubs['velocity'] = rospy.Publisher( '/mavros/setpoint_attitude/velocity', PoseStamped,",
"rospy.Publisher( '/mavros/setpoint_attitude/thrust', Thrust, queue_size=10 ) self._pubs['mocap'] = rospy.Publisher( '/mavros/mocap/pose', PoseStamped, queue_size=10 ) def",
"pub in self._pubs.values(): pass#pub.unregister() def send_attitude(self, attitude): self._pubs['attitude'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_velocity(self, attitude): self._pubs['velocity'].publish(attitude.get_message())",
"def send_velocity(self, attitude): self._pubs['velocity'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_position(self, pose): self._pubs['position'].publish(pose.get_message()) def send_mocap(self, pose): self._pubs['mocap'].publish(pose.get_message())",
"class Sender(object): def __init__(self): self._pubs = {} self._pubs['position'] = rospy.Publisher( '/mavros/setpoint_position/local', PoseStamped, queue_size=10",
"rospy.Publisher( '/mavros/mocap/pose', PoseStamped, queue_size=10 ) def __del__(self): for pub in self._pubs.values(): pass#pub.unregister() def",
"pass#pub.unregister() def send_attitude(self, attitude): self._pubs['attitude'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_velocity(self, attitude): self._pubs['velocity'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_position(self,",
"self._pubs['attitude'] = rospy.Publisher( '/mavros/setpoint_attitude/attitude', PoseStamped, queue_size=10 ) self._pubs['velocity'] = rospy.Publisher( '/mavros/setpoint_attitude/velocity', PoseStamped, queue_size=10",
"Sender(object): def __init__(self): self._pubs = {} self._pubs['position'] = rospy.Publisher( '/mavros/setpoint_position/local', PoseStamped, queue_size=10 )",
"__init__(self): self._pubs = {} self._pubs['position'] = rospy.Publisher( '/mavros/setpoint_position/local', PoseStamped, queue_size=10 ) self._pubs['attitude'] =",
"{} self._pubs['position'] = rospy.Publisher( '/mavros/setpoint_position/local', PoseStamped, queue_size=10 ) self._pubs['attitude'] = rospy.Publisher( '/mavros/setpoint_attitude/attitude', PoseStamped,",
"Point, PoseStamped, Quaternion from mavros_msgs.msg import Thrust class Sender(object): def __init__(self): self._pubs =",
"from mavros_msgs.msg import Thrust class Sender(object): def __init__(self): self._pubs = {} self._pubs['position'] =",
"'/mavros/setpoint_attitude/attitude', PoseStamped, queue_size=10 ) self._pubs['velocity'] = rospy.Publisher( '/mavros/setpoint_attitude/velocity', PoseStamped, queue_size=10 ) self._pubs['thrust'] =",
"PoseStamped, queue_size=10 ) self._pubs['velocity'] = rospy.Publisher( '/mavros/setpoint_attitude/velocity', PoseStamped, queue_size=10 ) self._pubs['thrust'] = rospy.Publisher(",
"rospy.Publisher( '/mavros/setpoint_position/local', PoseStamped, queue_size=10 ) self._pubs['attitude'] = rospy.Publisher( '/mavros/setpoint_attitude/attitude', PoseStamped, queue_size=10 ) self._pubs['velocity']",
"'/mavros/setpoint_attitude/thrust', Thrust, queue_size=10 ) self._pubs['mocap'] = rospy.Publisher( '/mavros/mocap/pose', PoseStamped, queue_size=10 ) def __del__(self):",
"def send_attitude(self, attitude): self._pubs['attitude'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_velocity(self, attitude): self._pubs['velocity'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_position(self, pose):",
"self._pubs['attitude'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_velocity(self, attitude): self._pubs['velocity'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_position(self, pose): self._pubs['position'].publish(pose.get_message()) def send_mocap(self,",
"queue_size=10 ) self._pubs['velocity'] = rospy.Publisher( '/mavros/setpoint_attitude/velocity', PoseStamped, queue_size=10 ) self._pubs['thrust'] = rospy.Publisher( '/mavros/setpoint_attitude/thrust',",
") self._pubs['mocap'] = rospy.Publisher( '/mavros/mocap/pose', PoseStamped, queue_size=10 ) def __del__(self): for pub in",
"= rospy.Publisher( '/mavros/setpoint_attitude/thrust', Thrust, queue_size=10 ) self._pubs['mocap'] = rospy.Publisher( '/mavros/mocap/pose', PoseStamped, queue_size=10 )",
"def __init__(self): self._pubs = {} self._pubs['position'] = rospy.Publisher( '/mavros/setpoint_position/local', PoseStamped, queue_size=10 ) self._pubs['attitude']",
"= rospy.Publisher( '/mavros/setpoint_attitude/velocity', PoseStamped, queue_size=10 ) self._pubs['thrust'] = rospy.Publisher( '/mavros/setpoint_attitude/thrust', Thrust, queue_size=10 )",
"queue_size=10 ) self._pubs['mocap'] = rospy.Publisher( '/mavros/mocap/pose', PoseStamped, queue_size=10 ) def __del__(self): for pub",
"self._pubs['mocap'] = rospy.Publisher( '/mavros/mocap/pose', PoseStamped, queue_size=10 ) def __del__(self): for pub in self._pubs.values():",
"__del__(self): for pub in self._pubs.values(): pass#pub.unregister() def send_attitude(self, attitude): self._pubs['attitude'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_velocity(self,",
"send_attitude(self, attitude): self._pubs['attitude'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_velocity(self, attitude): self._pubs['velocity'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_position(self, pose): self._pubs['position'].publish(pose.get_message())",
"self._pubs['thrust'] = rospy.Publisher( '/mavros/setpoint_attitude/thrust', Thrust, queue_size=10 ) self._pubs['mocap'] = rospy.Publisher( '/mavros/mocap/pose', PoseStamped, queue_size=10",
"import Thrust class Sender(object): def __init__(self): self._pubs = {} self._pubs['position'] = rospy.Publisher( '/mavros/setpoint_position/local',",
"queue_size=10 ) self._pubs['thrust'] = rospy.Publisher( '/mavros/setpoint_attitude/thrust', Thrust, queue_size=10 ) self._pubs['mocap'] = rospy.Publisher( '/mavros/mocap/pose',",
"PoseStamped, queue_size=10 ) def __del__(self): for pub in self._pubs.values(): pass#pub.unregister() def send_attitude(self, attitude):",
"from geometry_msgs.msg import Point, PoseStamped, Quaternion from mavros_msgs.msg import Thrust class Sender(object): def",
"rospy.Publisher( '/mavros/setpoint_attitude/velocity', PoseStamped, queue_size=10 ) self._pubs['thrust'] = rospy.Publisher( '/mavros/setpoint_attitude/thrust', Thrust, queue_size=10 ) self._pubs['mocap']",
"= rospy.Publisher( '/mavros/setpoint_position/local', PoseStamped, queue_size=10 ) self._pubs['attitude'] = rospy.Publisher( '/mavros/setpoint_attitude/attitude', PoseStamped, queue_size=10 )",
"import rospy from tf.transformations import quaternion_from_euler from geometry_msgs.msg import Point, PoseStamped, Quaternion from",
"from tf.transformations import quaternion_from_euler from geometry_msgs.msg import Point, PoseStamped, Quaternion from mavros_msgs.msg import",
") self._pubs['velocity'] = rospy.Publisher( '/mavros/setpoint_attitude/velocity', PoseStamped, queue_size=10 ) self._pubs['thrust'] = rospy.Publisher( '/mavros/setpoint_attitude/thrust', Thrust,",
"in self._pubs.values(): pass#pub.unregister() def send_attitude(self, attitude): self._pubs['attitude'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_velocity(self, attitude): self._pubs['velocity'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust))",
"'/mavros/setpoint_attitude/velocity', PoseStamped, queue_size=10 ) self._pubs['thrust'] = rospy.Publisher( '/mavros/setpoint_attitude/thrust', Thrust, queue_size=10 ) self._pubs['mocap'] =",
") self._pubs['thrust'] = rospy.Publisher( '/mavros/setpoint_attitude/thrust', Thrust, queue_size=10 ) self._pubs['mocap'] = rospy.Publisher( '/mavros/mocap/pose', PoseStamped,",
"queue_size=10 ) def __del__(self): for pub in self._pubs.values(): pass#pub.unregister() def send_attitude(self, attitude): self._pubs['attitude'].publish(attitude.get_message())",
"Thrust class Sender(object): def __init__(self): self._pubs = {} self._pubs['position'] = rospy.Publisher( '/mavros/setpoint_position/local', PoseStamped,",
"= rospy.Publisher( '/mavros/mocap/pose', PoseStamped, queue_size=10 ) def __del__(self): for pub in self._pubs.values(): pass#pub.unregister()",
"for pub in self._pubs.values(): pass#pub.unregister() def send_attitude(self, attitude): self._pubs['attitude'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_velocity(self, attitude):",
"import Point, PoseStamped, Quaternion from mavros_msgs.msg import Thrust class Sender(object): def __init__(self): self._pubs",
"PoseStamped, queue_size=10 ) self._pubs['attitude'] = rospy.Publisher( '/mavros/setpoint_attitude/attitude', PoseStamped, queue_size=10 ) self._pubs['velocity'] = rospy.Publisher(",
"mavros_msgs.msg import Thrust class Sender(object): def __init__(self): self._pubs = {} self._pubs['position'] = rospy.Publisher(",
"self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_velocity(self, attitude): self._pubs['velocity'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_position(self, pose): self._pubs['position'].publish(pose.get_message()) def send_mocap(self, pose):",
"def __del__(self): for pub in self._pubs.values(): pass#pub.unregister() def send_attitude(self, attitude): self._pubs['attitude'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def",
"self._pubs.values(): pass#pub.unregister() def send_attitude(self, attitude): self._pubs['attitude'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_velocity(self, attitude): self._pubs['velocity'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def",
"quaternion_from_euler from geometry_msgs.msg import Point, PoseStamped, Quaternion from mavros_msgs.msg import Thrust class Sender(object):",
"'/mavros/setpoint_position/local', PoseStamped, queue_size=10 ) self._pubs['attitude'] = rospy.Publisher( '/mavros/setpoint_attitude/attitude', PoseStamped, queue_size=10 ) self._pubs['velocity'] =",
"Thrust, queue_size=10 ) self._pubs['mocap'] = rospy.Publisher( '/mavros/mocap/pose', PoseStamped, queue_size=10 ) def __del__(self): for",
"queue_size=10 ) self._pubs['attitude'] = rospy.Publisher( '/mavros/setpoint_attitude/attitude', PoseStamped, queue_size=10 ) self._pubs['velocity'] = rospy.Publisher( '/mavros/setpoint_attitude/velocity',",
"PoseStamped, Quaternion from mavros_msgs.msg import Thrust class Sender(object): def __init__(self): self._pubs = {}",
"<reponame>Adrien4193/drone_control<gh_stars>0 import rospy from tf.transformations import quaternion_from_euler from geometry_msgs.msg import Point, PoseStamped, Quaternion",
"attitude): self._pubs['attitude'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_velocity(self, attitude): self._pubs['velocity'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust)) def send_position(self, pose): self._pubs['position'].publish(pose.get_message()) def",
"import quaternion_from_euler from geometry_msgs.msg import Point, PoseStamped, Quaternion from mavros_msgs.msg import Thrust class",
") def __del__(self): for pub in self._pubs.values(): pass#pub.unregister() def send_attitude(self, attitude): self._pubs['attitude'].publish(attitude.get_message()) self._pubs['thrust'].publish(Thrust(thrust=attitude.thrust))",
"self._pubs['position'] = rospy.Publisher( '/mavros/setpoint_position/local', PoseStamped, queue_size=10 ) self._pubs['attitude'] = rospy.Publisher( '/mavros/setpoint_attitude/attitude', PoseStamped, queue_size=10",
"= rospy.Publisher( '/mavros/setpoint_attitude/attitude', PoseStamped, queue_size=10 ) self._pubs['velocity'] = rospy.Publisher( '/mavros/setpoint_attitude/velocity', PoseStamped, queue_size=10 )",
"Quaternion from mavros_msgs.msg import Thrust class Sender(object): def __init__(self): self._pubs = {} self._pubs['position']",
"'/mavros/mocap/pose', PoseStamped, queue_size=10 ) def __del__(self): for pub in self._pubs.values(): pass#pub.unregister() def send_attitude(self,",
"PoseStamped, queue_size=10 ) self._pubs['thrust'] = rospy.Publisher( '/mavros/setpoint_attitude/thrust', Thrust, queue_size=10 ) self._pubs['mocap'] = rospy.Publisher("
] |
[
"print(f'Wait for {seconds} seconds, Current time is {datetime.today().time()}') import random # 由于Windows下multiprocess会执行整个代码块,所以会引起循环创建进程的问题 #",
"13) print(my_birthday) # Q8 # 星期从零开始计数 print(my_birthday.weekday()) # 星期从一开始计数 print(my_birthday.isoweekday()) # Q9 from",
"import date now = date.today() now_string = now.isoformat() with open('today.txt', 'w') as file:",
"format)) # Q4 import os print(os.listdir('.')) # Q5 print(os.listdir('..')) # Q6 import multiprocessing",
"{datetime.today().time()}') import random # 由于Windows下multiprocess会执行整个代码块,所以会引起循环创建进程的问题 # 这需要下面的代码来避免 if __name__ == '__main__': for n",
"my_birthday = date(1993, 8, 13) print(my_birthday) # Q8 # 星期从零开始计数 print(my_birthday.weekday()) # 星期从一开始计数",
"with open('today.txt', 'w') as file: print(now, file=file) # Q2 today_string = None with",
"from datetime import date now = date.today() now_string = now.isoformat() with open('today.txt', 'w')",
"星期从零开始计数 print(my_birthday.weekday()) # 星期从一开始计数 print(my_birthday.isoweekday()) # Q9 from datetime import timedelta ten_thousand_day_after_my_birthday =",
"Q6 import multiprocessing def print_current_time(seconds): from time import sleep sleep(seconds) print(f'Wait for {seconds}",
"None with open('today.txt') as file: today_string = file.read() print(today_string) # Q3 from datetime",
"for n in range(3): seconds = random.random() process = multiprocessing.Process(target=print_current_time, args=(seconds,)) process.start() #",
"import datetime format = '%Y-%m-%d\\n' print(datetime.strptime(today_string, format)) # Q4 import os print(os.listdir('.')) #",
"from datetime import datetime format = '%Y-%m-%d\\n' print(datetime.strptime(today_string, format)) # Q4 import os",
"{seconds} seconds, Current time is {datetime.today().time()}') import random # 由于Windows下multiprocess会执行整个代码块,所以会引起循环创建进程的问题 # 这需要下面的代码来避免 if",
"import multiprocessing def print_current_time(seconds): from time import sleep sleep(seconds) print(f'Wait for {seconds} seconds,",
"datetime import date now = date.today() now_string = now.isoformat() with open('today.txt', 'w') as",
"process.start() # Q7 my_birthday = date(1993, 8, 13) print(my_birthday) # Q8 # 星期从零开始计数",
"# Q3 from datetime import datetime format = '%Y-%m-%d\\n' print(datetime.strptime(today_string, format)) # Q4",
"multiprocessing def print_current_time(seconds): from time import sleep sleep(seconds) print(f'Wait for {seconds} seconds, Current",
"= None with open('today.txt') as file: today_string = file.read() print(today_string) # Q3 from",
"# Q2 today_string = None with open('today.txt') as file: today_string = file.read() print(today_string)",
"as file: today_string = file.read() print(today_string) # Q3 from datetime import datetime format",
"# Q6 import multiprocessing def print_current_time(seconds): from time import sleep sleep(seconds) print(f'Wait for",
"8, 13) print(my_birthday) # Q8 # 星期从零开始计数 print(my_birthday.weekday()) # 星期从一开始计数 print(my_birthday.isoweekday()) # Q9",
"# 由于Windows下multiprocess会执行整个代码块,所以会引起循环创建进程的问题 # 这需要下面的代码来避免 if __name__ == '__main__': for n in range(3): seconds",
"= '%Y-%m-%d\\n' print(datetime.strptime(today_string, format)) # Q4 import os print(os.listdir('.')) # Q5 print(os.listdir('..')) #",
"time import sleep sleep(seconds) print(f'Wait for {seconds} seconds, Current time is {datetime.today().time()}') import",
"print(os.listdir('.')) # Q5 print(os.listdir('..')) # Q6 import multiprocessing def print_current_time(seconds): from time import",
"seconds, Current time is {datetime.today().time()}') import random # 由于Windows下multiprocess会执行整个代码块,所以会引起循环创建进程的问题 # 这需要下面的代码来避免 if __name__",
"这需要下面的代码来避免 if __name__ == '__main__': for n in range(3): seconds = random.random() process",
"# Q7 my_birthday = date(1993, 8, 13) print(my_birthday) # Q8 # 星期从零开始计数 print(my_birthday.weekday())",
"now_string = now.isoformat() with open('today.txt', 'w') as file: print(now, file=file) # Q2 today_string",
"import os print(os.listdir('.')) # Q5 print(os.listdir('..')) # Q6 import multiprocessing def print_current_time(seconds): from",
"# 这需要下面的代码来避免 if __name__ == '__main__': for n in range(3): seconds = random.random()",
"print(my_birthday) # Q8 # 星期从零开始计数 print(my_birthday.weekday()) # 星期从一开始计数 print(my_birthday.isoweekday()) # Q9 from datetime",
"random # 由于Windows下multiprocess会执行整个代码块,所以会引起循环创建进程的问题 # 这需要下面的代码来避免 if __name__ == '__main__': for n in range(3):",
"for {seconds} seconds, Current time is {datetime.today().time()}') import random # 由于Windows下multiprocess会执行整个代码块,所以会引起循环创建进程的问题 # 这需要下面的代码来避免",
"print(datetime.strptime(today_string, format)) # Q4 import os print(os.listdir('.')) # Q5 print(os.listdir('..')) # Q6 import",
"import random # 由于Windows下multiprocess会执行整个代码块,所以会引起循环创建进程的问题 # 这需要下面的代码来避免 if __name__ == '__main__': for n in",
"'w') as file: print(now, file=file) # Q2 today_string = None with open('today.txt') as",
"= file.read() print(today_string) # Q3 from datetime import datetime format = '%Y-%m-%d\\n' print(datetime.strptime(today_string,",
"Q4 import os print(os.listdir('.')) # Q5 print(os.listdir('..')) # Q6 import multiprocessing def print_current_time(seconds):",
"range(3): seconds = random.random() process = multiprocessing.Process(target=print_current_time, args=(seconds,)) process.start() # Q7 my_birthday =",
"def print_current_time(seconds): from time import sleep sleep(seconds) print(f'Wait for {seconds} seconds, Current time",
"Q1 from datetime import date now = date.today() now_string = now.isoformat() with open('today.txt',",
"'__main__': for n in range(3): seconds = random.random() process = multiprocessing.Process(target=print_current_time, args=(seconds,)) process.start()",
"= random.random() process = multiprocessing.Process(target=print_current_time, args=(seconds,)) process.start() # Q7 my_birthday = date(1993, 8,",
"print(os.listdir('..')) # Q6 import multiprocessing def print_current_time(seconds): from time import sleep sleep(seconds) print(f'Wait",
"if __name__ == '__main__': for n in range(3): seconds = random.random() process =",
"# Q1 from datetime import date now = date.today() now_string = now.isoformat() with",
"today_string = file.read() print(today_string) # Q3 from datetime import datetime format = '%Y-%m-%d\\n'",
"file=file) # Q2 today_string = None with open('today.txt') as file: today_string = file.read()",
"星期从一开始计数 print(my_birthday.isoweekday()) # Q9 from datetime import timedelta ten_thousand_day_after_my_birthday = my_birthday + timedelta(days=10000)",
"# 星期从一开始计数 print(my_birthday.isoweekday()) # Q9 from datetime import timedelta ten_thousand_day_after_my_birthday = my_birthday +",
"datetime format = '%Y-%m-%d\\n' print(datetime.strptime(today_string, format)) # Q4 import os print(os.listdir('.')) # Q5",
"# Q5 print(os.listdir('..')) # Q6 import multiprocessing def print_current_time(seconds): from time import sleep",
"sleep sleep(seconds) print(f'Wait for {seconds} seconds, Current time is {datetime.today().time()}') import random #",
"from time import sleep sleep(seconds) print(f'Wait for {seconds} seconds, Current time is {datetime.today().time()}')",
"date now = date.today() now_string = now.isoformat() with open('today.txt', 'w') as file: print(now,",
"now.isoformat() with open('today.txt', 'w') as file: print(now, file=file) # Q2 today_string = None",
"= now.isoformat() with open('today.txt', 'w') as file: print(now, file=file) # Q2 today_string =",
"as file: print(now, file=file) # Q2 today_string = None with open('today.txt') as file:",
"print(my_birthday.weekday()) # 星期从一开始计数 print(my_birthday.isoweekday()) # Q9 from datetime import timedelta ten_thousand_day_after_my_birthday = my_birthday",
"Current time is {datetime.today().time()}') import random # 由于Windows下multiprocess会执行整个代码块,所以会引起循环创建进程的问题 # 这需要下面的代码来避免 if __name__ ==",
"random.random() process = multiprocessing.Process(target=print_current_time, args=(seconds,)) process.start() # Q7 my_birthday = date(1993, 8, 13)",
"# 星期从零开始计数 print(my_birthday.weekday()) # 星期从一开始计数 print(my_birthday.isoweekday()) # Q9 from datetime import timedelta ten_thousand_day_after_my_birthday",
"== '__main__': for n in range(3): seconds = random.random() process = multiprocessing.Process(target=print_current_time, args=(seconds,))",
"'%Y-%m-%d\\n' print(datetime.strptime(today_string, format)) # Q4 import os print(os.listdir('.')) # Q5 print(os.listdir('..')) # Q6",
"print_current_time(seconds): from time import sleep sleep(seconds) print(f'Wait for {seconds} seconds, Current time is",
"open('today.txt', 'w') as file: print(now, file=file) # Q2 today_string = None with open('today.txt')",
"date.today() now_string = now.isoformat() with open('today.txt', 'w') as file: print(now, file=file) # Q2",
"= date(1993, 8, 13) print(my_birthday) # Q8 # 星期从零开始计数 print(my_birthday.weekday()) # 星期从一开始计数 print(my_birthday.isoweekday())",
"process = multiprocessing.Process(target=print_current_time, args=(seconds,)) process.start() # Q7 my_birthday = date(1993, 8, 13) print(my_birthday)",
"# Q8 # 星期从零开始计数 print(my_birthday.weekday()) # 星期从一开始计数 print(my_birthday.isoweekday()) # Q9 from datetime import",
"# Q4 import os print(os.listdir('.')) # Q5 print(os.listdir('..')) # Q6 import multiprocessing def",
"sleep(seconds) print(f'Wait for {seconds} seconds, Current time is {datetime.today().time()}') import random # 由于Windows下multiprocess会执行整个代码块,所以会引起循环创建进程的问题",
"with open('today.txt') as file: today_string = file.read() print(today_string) # Q3 from datetime import",
"is {datetime.today().time()}') import random # 由于Windows下multiprocess会执行整个代码块,所以会引起循环创建进程的问题 # 这需要下面的代码来避免 if __name__ == '__main__': for",
"print(my_birthday.isoweekday()) # Q9 from datetime import timedelta ten_thousand_day_after_my_birthday = my_birthday + timedelta(days=10000) print(ten_thousand_day_after_my_birthday)",
"= date.today() now_string = now.isoformat() with open('today.txt', 'w') as file: print(now, file=file) #",
"datetime import datetime format = '%Y-%m-%d\\n' print(datetime.strptime(today_string, format)) # Q4 import os print(os.listdir('.'))",
"file: today_string = file.read() print(today_string) # Q3 from datetime import datetime format =",
"Q5 print(os.listdir('..')) # Q6 import multiprocessing def print_current_time(seconds): from time import sleep sleep(seconds)",
"time is {datetime.today().time()}') import random # 由于Windows下multiprocess会执行整个代码块,所以会引起循环创建进程的问题 # 这需要下面的代码来避免 if __name__ == '__main__':",
"<reponame>DailyYu/python-study # Q1 from datetime import date now = date.today() now_string = now.isoformat()",
"os print(os.listdir('.')) # Q5 print(os.listdir('..')) # Q6 import multiprocessing def print_current_time(seconds): from time",
"file: print(now, file=file) # Q2 today_string = None with open('today.txt') as file: today_string",
"由于Windows下multiprocess会执行整个代码块,所以会引起循环创建进程的问题 # 这需要下面的代码来避免 if __name__ == '__main__': for n in range(3): seconds =",
"today_string = None with open('today.txt') as file: today_string = file.read() print(today_string) # Q3",
"file.read() print(today_string) # Q3 from datetime import datetime format = '%Y-%m-%d\\n' print(datetime.strptime(today_string, format))",
"Q3 from datetime import datetime format = '%Y-%m-%d\\n' print(datetime.strptime(today_string, format)) # Q4 import",
"= multiprocessing.Process(target=print_current_time, args=(seconds,)) process.start() # Q7 my_birthday = date(1993, 8, 13) print(my_birthday) #",
"args=(seconds,)) process.start() # Q7 my_birthday = date(1993, 8, 13) print(my_birthday) # Q8 #",
"print(today_string) # Q3 from datetime import datetime format = '%Y-%m-%d\\n' print(datetime.strptime(today_string, format)) #",
"in range(3): seconds = random.random() process = multiprocessing.Process(target=print_current_time, args=(seconds,)) process.start() # Q7 my_birthday",
"Q8 # 星期从零开始计数 print(my_birthday.weekday()) # 星期从一开始计数 print(my_birthday.isoweekday()) # Q9 from datetime import timedelta",
"__name__ == '__main__': for n in range(3): seconds = random.random() process = multiprocessing.Process(target=print_current_time,",
"Q7 my_birthday = date(1993, 8, 13) print(my_birthday) # Q8 # 星期从零开始计数 print(my_birthday.weekday()) #",
"seconds = random.random() process = multiprocessing.Process(target=print_current_time, args=(seconds,)) process.start() # Q7 my_birthday = date(1993,",
"import sleep sleep(seconds) print(f'Wait for {seconds} seconds, Current time is {datetime.today().time()}') import random",
"open('today.txt') as file: today_string = file.read() print(today_string) # Q3 from datetime import datetime",
"multiprocessing.Process(target=print_current_time, args=(seconds,)) process.start() # Q7 my_birthday = date(1993, 8, 13) print(my_birthday) # Q8",
"format = '%Y-%m-%d\\n' print(datetime.strptime(today_string, format)) # Q4 import os print(os.listdir('.')) # Q5 print(os.listdir('..'))",
"n in range(3): seconds = random.random() process = multiprocessing.Process(target=print_current_time, args=(seconds,)) process.start() # Q7",
"now = date.today() now_string = now.isoformat() with open('today.txt', 'w') as file: print(now, file=file)",
"date(1993, 8, 13) print(my_birthday) # Q8 # 星期从零开始计数 print(my_birthday.weekday()) # 星期从一开始计数 print(my_birthday.isoweekday()) #",
"Q2 today_string = None with open('today.txt') as file: today_string = file.read() print(today_string) #",
"print(now, file=file) # Q2 today_string = None with open('today.txt') as file: today_string ="
] |
[
"bbox_inches='tight') sess = tf.Session(config=tf.ConfigProto(device_count={'GPU': 0})) if __name__ == '__main__': # playing_with_losses() # tf_dataset_experiments()",
"depth_reconstructed_val[:, :, :, 0] # coord.request_stop() # coord.join(threads) # # layer = 2",
"= 320 # TARGET_HEIGHT = 120 # TARGET_WIDTH = 160 # DEPTH_DIM =",
"[0, 2, 0, 0, 0], [1, 1, 1, 0, 0], [0, 1, 0,",
"probs_tf = sess.run(tf.nn.softmax(logits_tf)) loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=labels_tf, logits=logits_tf)) new_loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=tf_labels_to_info_gain(labels, logits_tf), logits=logits_tf)) #",
"1, 1, 1, 1], # [0, 10, 0, 0, 0], # [1, 5,",
"# axarr[0, 0].set_title('masks_val') # axarr[0, 0].imshow(mask_val[0, :, :, layer]) # axarr[0, 1].set_title('mask_multiplied_val') #",
"tf.data.TFRecordDataset(['train-voxel-gta.csv', 'test-voxel-gta.csv']) train_imgs = tf.constant(['train-voxel-gta.csv']) filename_list = tf.data.Dataset.from_tensor_slices(train_imgs) filename_pairs = filename_list.flat_map(input_parser) data_pairs =",
"= sess.run(tf.reduce_mean(logits_tf)) # print('tf_mean\\n', tf_mean) # # print('mean\\n', np.mean(arr)) # print('sum_per_row\\n', np.sum(arr, axis=1))",
"= np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()]) # print('trainable vars: ', total_vars) # for",
"4], # [4, 4, 4, 8], # ]) # with tf.Graph().as_default(): # with",
"channels=3) # image = tf.cast(image, tf.float32) # # target # depth_png = tf.read_file(depth_filename)",
"- prob_bin_idx)**2) print('info gain', '\\n', info_gain) return info_gain def tf_labels_to_info_gain(labels, logits, alpha=0.2): last_axis",
"TARGET_WIDTH = 160 # DEPTH_DIM = 10 # # filename_queue = tf.train.string_input_producer(['train.csv'], shuffle=True)",
"np.mean(np.sum(arr, axis=1), axis=0)) # ds = DataSet(8) # ds.load_params('train.csv') # # d =",
"filename_list.flat_map(input_parser) data_pairs = filename_pairs.map(filenames_to_data) data_pairs = data_pairs.batch(batch_size) # # # input # image",
"0, 0], [0, 2, 0, 0, 0], [1, 1, 1, 0, 0], [0,",
"depth_discretized, invalid_depth], # batch_size=batch_size, # num_threads=4, # capacity=40) # # depth_reconstructed, weights, mask,",
"j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_ml.png\" % (output_dir, i,",
"d_max = 20 # num_bins = 10 # q_calc = (np.log(np.max(d)) - np.log(d_min))",
"range(500): # # if i % 500 == 0: # # print('hi', i)",
"range(DEPTH_DIM): # ra_depth = mask[:, :, j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") #",
"j) # depth_discr_pil.save(depth_discr_name) # # for j in range(DEPTH_DIM): # ra_depth = mask_lower[:,",
"1].imshow(depths_discretized_val[0, :, :, layer]) # axarr[0, 2].set_title('mask_multiplied_sum_val') # axarr[0, 2].imshow(mask_multiplied_sum_val[0, :, :]) #",
"# total_vars = np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()]) # print('trainable vars: ', total_vars)",
"axis=2) new_depth = new_depth.T new_depth *= int(255/depth_size) plt.figure(figsize=(10, 7)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/out-{}-depth-np.png'.format(j),",
"print('probs_idx', '\\n', prob_bin_idx) info_gain = np.exp(-alpha * (label_idx - prob_bin_idx)**2) print('info gain', '\\n',",
"= tf.py_func(dataset.DataSet.filename_to_target_voxelmap, [voxelmap_filename], tf.int32) voxelmap.set_shape([dataset.TARGET_WIDTH, dataset.TARGET_HEIGHT, dataset.DEPTH_DIM]) # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) depth_reconstructed =",
"/ depth_size) plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/2018-03-07--17-57-32--527.png', bbox_inches='tight') sess = tf.Session(config=tf.ConfigProto(device_count={'GPU': 0}))",
"loss_per_row def labels_to_info_gain(labels, logits, alpha=0.2): last_axis = len(logits.shape) - 1 label_idx = np.tile(np.argmax(labels,",
"logged_probs = np.log(probs) print('logged probs', '\\n', logged_probs) loss_per_row = - np.sum(labels_to_info_gain(labels, logits) *",
"voxelmap, depth_reconstructed def tf_new_data_api_experiments(): # global sess batch_size = 4 with sess.as_default(): tf.logging.set_verbosity(tf.logging.INFO)",
"dataset.DataSet.filename_to_input_image(filename) # # target # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) # depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) iterator",
"[\"annotation\"]]) # # input # jpg = tf.read_file(filename) # image = tf.image.decode_jpeg(jpg, channels=3)",
"TARGET_HEIGHT = 120 # TARGET_WIDTH = 160 # DEPTH_DIM = 10 # #",
"label_idx) # print('probs_idx', '\\n', prob_bin_idx) info_gain = np.exp(-alpha * (label_idx - prob_bin_idx)**2) print('info",
"[1, 1, 1, 1, 4], # [4, 1, 1, 1, 1], ]) probs",
"higher value to booleans in higher index depth_size = numpy_voxelmap.shape[2] new_depth = np.argmax(numpy_voxelmap,",
"depth_discr_pil.save(depth_discr_name) depth = depth_reconstructed[:, :, 0] if np.max(depth) != 0: ra_depth = (depth",
"0, 0, 1, 0], # [0, 0, 0, 0, 1], # [1, 0,",
"[1, 0, 0, 0, 0], ]) logits = np.array([ [0, 20, 0, 0,",
"calculation of depth image from voxelmap occupied_ndc_grid = voxels_values[j, :, :, :] occupied_ndc_grid",
"\"%s/%03d_reconstructed.png\" % (output_dir, i) depth_pil.save(depth_name) def playground_loss_function(labels, logits): # in rank 2, [elements,",
"print(d) # print(l) # # print('q_calc', q_calc) # # f, axarr = plt.subplots(2,",
"# coord.request_stop() # coord.join(threads) # # layer = 2 # f, axarr =",
"= 2 # f, axarr = plt.subplots(2, 3) # axarr[0, 0].set_title('masks_val') # axarr[0,",
"[0, 1, 0, 0, 0], # [3, 1, 1, 1, 1], # [0,",
"from Network import BATCH_SIZE from dataset import DataSet def output_predict(depths, images, depths_discretized, depths_reconstructed,",
"q = 0.5 # width of quantization bin # l = np.round((np.log(d) -",
"np.flip(numpy_voxelmap, axis=2) # now I have just boolean for each value # so",
"'\\n', e_x) print('sum_per_row', '\\n', sum_per_row) return e_x / sum_per_row def softmax_cross_entropy_loss(labels, logits): \"\"\"Same",
"data_pairs = filename_pairs.map(filenames_to_data) data_pairs = data_pairs.batch(batch_size) # # # input # image =",
"# # if i % 500 == 0: # # print('hi', i) #",
"# depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_ml.png\" % (output_dir, i, j)",
"depth_discr_name = \"%s/%03d_%03d_discr.png\" % (output_dir, i, j) depth_discr_pil.save(depth_discr_name) # for j in range(DEPTH_DIM):",
"tensorflow\"\"\" loss_per_row = - np.sum(labels * np.log(softmax(logits)), axis=1) return loss_per_row def labels_to_info_gain(labels, logits,",
"2 # f, axarr = plt.subplots(2, 3) # axarr[0, 0].set_title('masks_val') # axarr[0, 0].imshow(mask_val[0,",
"images_values, voxels_values, depths_values = sess.run([batch_images, batch_voxels, batch_depths]) for j in range(batch_size): plt.figure(figsize=(10, 6))",
"e_x = np.exp(x) sum_per_row = np.tile(e_x.sum(axis=1), (x.shape[1], 1)).T print('e_x', '\\n', e_x) print('sum_per_row', '\\n',",
"as sess: logits_tf = tf.constant(logits, dtype=tf.float32) labels_tf = tf.constant(labels, dtype=tf.float32) probs_tf = sess.run(tf.nn.softmax(logits_tf))",
"tf.expand_dims(tf.argmax(labels, axis=last_axis), 0) label_idx = tf.cast(label_idx, dtype=tf.int32) label_idx = tf.tile(label_idx, [labels.shape[last_axis], 1]) label_idx",
"plt.savefig('inspections/out-{}-depth-np.png'.format(j), bbox_inches='tight') def load_numpy_bin(): # name = 'inspections/2018-03-07--17-57-32--527.bin' name = 'inspections/2018-03-07--17-57-32--527.npy' # numpy_voxelmap",
"- np.log(d_min)) # axarr[1, 1].plot((np.log(d) - np.log(d_min)) / q_calc) # plt.show() # with",
"1]) difference = (label_idx - prob_bin_idx)**2 difference = tf.cast(difference, dtype=tf.float32) info_gain = tf.exp(-alpha",
"j] * 255.0 depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_discr_name = \"%s/%03d_%03d_discr.png\" % (output_dir, i,",
"= dataset.DataSet.discretize_depth(depth) # # invalid_depth = tf.sign(depth) # # batch_size = 8 #",
"i % 500 == 0: # # print('hi', i) # # IMAGE_HEIGHT =",
"sep=';') numpy_voxelmap = np.load(name) print(numpy_voxelmap.shape) # numpy_voxelmap = numpy_voxelmap.reshape([240, 160, 100]) numpy_voxelmap =",
"# [1, 1, 4, 1, 1], # [1, 1, 1, 4, 1], #",
"# ds.load_params('train.csv') # # d = list(range(1, 100)) # d_min = np.min(d) #",
"tf.expand_dims(tf.range(logits.shape[last_axis], dtype=tf.int32), last_axis) prob_bin_idx = tf.transpose(prob_bin_idx) prob_bin_idx = tf.tile(prob_bin_idx, [labels.shape[0], 1]) difference =",
"# print('probs', '\\n', probs) # print('probs diff', '\\n', probs - probs_tf) print('loss', '\\n',",
"# network.prepare() # total_vars = np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()]) # print('trainable vars:",
"0, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 0,",
"# # filename_queue = tf.train.string_input_producer(['train.csv'], shuffle=True) # reader = tf.TextLineReader() # _, serialized_example",
"if __name__ == '__main__': # playing_with_losses() # tf_dataset_experiments() # load_numpy_bin() tf_new_data_api_experiments() # arr",
"tf.train.Coordinator() # threads = tf.train.start_queue_runners(sess=sess, coord=coord) # # images_val, depths_val, depths_discretized_val, invalid_depths_val, depth_reconstructed_val,",
"# print('q_calc', q_calc) # # f, axarr = plt.subplots(2, 2) # axarr[0, 0].plot(d)",
"train_imgs = tf.constant(['train-voxel-gta.csv']) filename_list = tf.data.Dataset.from_tensor_slices(train_imgs) filename_pairs = filename_list.flat_map(input_parser) data_pairs = filename_pairs.map(filenames_to_data) data_pairs",
"1, 1, 4, 1], # [1, 1, 1, 1, 4], # [4, 1,",
"= len(logits.shape) - 1 label_idx = tf.expand_dims(tf.argmax(labels, axis=last_axis), 0) label_idx = tf.cast(label_idx, dtype=tf.int32)",
"255.0 depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_discr_name = \"%s/%03d_%03d_discr.png\" % (output_dir, i, j) depth_discr_pil.save(depth_discr_name)",
":] occupied_ndc_grid = np.flip(occupied_ndc_grid, axis=2) depth_size = occupied_ndc_grid.shape[2] new_depth = np.argmax(occupied_ndc_grid, axis=2) new_depth",
"= tf.constant(logits, dtype=tf.float32) labels_tf = tf.constant(labels, dtype=tf.float32) probs_tf = sess.run(tf.nn.softmax(logits_tf)) loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=labels_tf,",
"tf.py_func(dataset.DataSet.filename_to_target_voxelmap, [voxelmap_filename], tf.int32) voxelmap.set_shape([dataset.TARGET_WIDTH, dataset.TARGET_HEIGHT, dataset.DEPTH_DIM]) # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap)",
"if np.max(depth) != 0: ra_depth = (depth / np.max(depth)) * 255.0 else: ra_depth",
"\"%s/%03d_org.png\" % (output_dir, i) pilimg.save(image_name) depth = depth.transpose(2, 0, 1) if np.max(depth) !=",
"in range(batch_size): plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(images_values[j, :, :, :].astype(dtype=np.uint8)) plt.savefig('inspections/out-{}-rgb.png'.format(j), bbox_inches='tight') plt.figure(figsize=(10, 6))",
"i) depth_pil.save(depth_name) for j in range(dataset.DEPTH_DIM): ra_depth = depth_discretized[:, :, j] * 255.0",
"'\\n', logged_probs) loss_per_row = - np.sum(labels_to_info_gain(labels, logits) * logged_probs, axis=1) return loss_per_row def",
"= np.array([ [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0,",
"return loss_per_row def playing_with_losses(): labels = np.array([ [0, 1, 0, 0, 0], [0,",
"info_gain = tf.exp(-alpha * difference) return info_gain def informed_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as",
"logits=logits_tf)) new_loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=tf_labels_to_info_gain(labels, logits_tf), logits=logits_tf)) # print('labels', '\\n', labels) # print('logits', '\\n',",
"dataset.TARGET_HEIGHT, dataset.DEPTH_DIM]) # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) return rgb_image, voxelmap, depth_reconstructed",
"# axarr[0, 1].plot(np.log(d)) # axarr[1, 0].plot(np.log(d) - np.log(d_min)) # axarr[1, 1].plot((np.log(d) - np.log(d_min))",
"for i, _ in enumerate(images): image, depth, depth_discretized, depth_reconstructed = images[i], depths[i], depths_discretized[i],",
"'\\n', loss_tf) print('loss diff', '\\n', loss - loss_tf) print('new_loss', '\\n', new_loss) print('new_loss_tf', '\\n',",
"np.fromfile(name, sep=';') numpy_voxelmap = np.load(name) print(numpy_voxelmap.shape) # numpy_voxelmap = numpy_voxelmap.reshape([240, 160, 100]) numpy_voxelmap",
"# filename, depth_filename = tf.decode_csv(serialized_example, [[\"path\"], [\"annotation\"]]) # # input # jpg =",
"depth, depth_discretized, depth_reconstructed = images[i], depths[i], depths_discretized[i], \\ depths_reconstructed[i] pilimg = Image.fromarray(np.uint8(image)) image_name",
"= dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) # depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) iterator = data_pairs.make_one_shot_iterator() batch_images, batch_voxels, batch_depths =",
"[elements, classes] # tf.nn.weighted_cross_entropy_with_logits(labels, logits, weights) losses = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) return losses def",
"axarr[1, 0].imshow(depths_val[0, :, :, 0]) # axarr[1, 1].set_title('depths_discretized_val') # axarr[1, 1].imshow(depths_discretized_val[0, :, :,",
"DEPTH_DIM = 10 # # filename_queue = tf.train.string_input_producer(['train.csv'], shuffle=True) # reader = tf.TextLineReader()",
"0, 0], [0, 10, 0, 0, 0], [0, 2, 0, 0, 0], [1,",
"playing_with_losses() # tf_dataset_experiments() # load_numpy_bin() tf_new_data_api_experiments() # arr = np.array([ # [1, 1,",
"numpy_voxelmap.shape[2] new_depth = np.argmax(numpy_voxelmap, axis=2) new_depth = new_depth.T new_depth *= int(255 / depth_size)",
"dataset.DataSet.filename_to_input_image(rgb_filename) voxelmap = tf.py_func(dataset.DataSet.filename_to_target_voxelmap, [voxelmap_filename], tf.int32) voxelmap.set_shape([dataset.TARGET_WIDTH, dataset.TARGET_HEIGHT, dataset.DEPTH_DIM]) # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename)",
"axis=1), axis=0)) # ds = DataSet(8) # ds.load_params('train.csv') # # d = list(range(1,",
"0], [0, 10, 0, 0, 0], [0, 2, 0, 0, 0], [1, 1,",
"batch_size = 4 with sess.as_default(): tf.logging.set_verbosity(tf.logging.INFO) # dataset = tf.data.TFRecordDataset(['train-voxel-gta.csv', 'test-voxel-gta.csv']) train_imgs =",
"# axarr[1, 1].imshow(depths_discretized_val[0, :, :, layer]) # axarr[0, 2].set_title('mask_multiplied_sum_val') # axarr[0, 2].imshow(mask_multiplied_sum_val[0, :,",
"mask_multiplied_sum = Network.Network.bins_to_depth(depths_discretized) # # print('weights: ', weights) # # coord = tf.train.Coordinator()",
"numpy_voxelmap = np.flip(numpy_voxelmap, axis=2) # now I have just boolean for each value",
"# plt.show() # network = Network.Network() # network.prepare() # total_vars = np.sum([np.prod(v.get_shape().as_list()) for",
"softmax_cross_entropy_loss(labels=labels, logits=logits) new_loss = informed_cross_entropy_loss(labels=labels, logits=logits) with tf.Graph().as_default(): with tf.Session() as sess: logits_tf",
"axarr[0, 1].set_title('sample 2') # axarr[0, 1].plot(probs[1, :]) # axarr[1, 0].set_title('sample 3') # axarr[1,",
"'\\n', probs) logged_probs = np.log(probs) print('logged probs', '\\n', logged_probs) loss_per_row = - np.sum(labels_to_info_gain(labels,",
"= dataset.DataSet.tf_voxelmap_to_depth(voxelmap) return rgb_image, voxelmap, depth_reconstructed def tf_new_data_api_experiments(): # global sess batch_size =",
"if i % 500 == 0: # # print('hi', i) # # IMAGE_HEIGHT",
"tf_mean = sess.run(tf.reduce_mean(logits_tf)) # print('tf_mean\\n', tf_mean) # # print('mean\\n', np.mean(arr)) # print('sum_per_row\\n', np.sum(arr,",
"invalid_depth], # batch_size=batch_size, # num_threads=4, # capacity=40) # # depth_reconstructed, weights, mask, mask_multiplied,",
"in range(DEPTH_DIM): # ra_depth = mask[:, :, j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\")",
"axarr = plt.subplots(2, 3) # axarr[0, 0].set_title('masks_val') # axarr[0, 0].imshow(mask_val[0, :, :, layer])",
"def output_predict(depths, images, depths_discretized, depths_reconstructed, output_dir): print(\"output predict into %s\" % output_dir) if",
"range(dataset.DEPTH_DIM): ra_depth = depth_discretized[:, :, j] * 255.0 depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_discr_name",
"depth_reconstructed, mask, mask_multiplied, mask_multiplied_sum]) # sess.run(images) # # output_predict(depths_val, images_val, depths_discretized_val, # depth_reconstructed_val,",
"Network import BATCH_SIZE from dataset import DataSet def output_predict(depths, images, depths_discretized, depths_reconstructed, output_dir):",
"ds.load_params('train.csv') # # d = list(range(1, 100)) # d_min = np.min(d) # d_max",
"\"\"\"Same behaviour as tf.nn.softmax in tensorflow\"\"\" e_x = np.exp(x) sum_per_row = np.tile(e_x.sum(axis=1), (x.shape[1],",
"tf.gfile.MakeDirs(output_dir) for i, _ in enumerate(images): image, depth, depth_discretized, depth_reconstructed = images[i], depths[i],",
"to assign higher value to booleans in higher index depth_size = numpy_voxelmap.shape[2] new_depth",
"weights, mask, mask_multiplied, mask_multiplied_sum = Network.Network.bins_to_depth(depths_discretized) # # print('weights: ', weights) # #",
"0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1,",
"DataSet(8) # ds.load_params('train.csv') # # d = list(range(1, 100)) # d_min = np.min(d)",
"total_vars) # for output bins = 200: 73 696 786 # for output",
"logits = np.array([ [0, 20, 0, 0, 0], [0, 10, 0, 0, 0],",
"of depth image from voxelmap occupied_ndc_grid = voxels_values[j, :, :, :] occupied_ndc_grid =",
"print('q_calc', q_calc) # # f, axarr = plt.subplots(2, 2) # axarr[0, 0].plot(d) #",
"dataset.DataSet.tf_voxelmap_to_depth(voxelmap) iterator = data_pairs.make_one_shot_iterator() batch_images, batch_voxels, batch_depths = iterator.get_next() for i in range(1):",
"alpha=0.2): last_axis = len(logits.shape) - 1 label_idx = np.tile(np.argmax(labels, axis=last_axis), (labels.shape[last_axis], 1)).T prob_bin_idx",
"tf.nn.weighted_cross_entropy_with_logits(labels, logits, weights) losses = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) return losses def prob_to_logit(probs): return np.log(probs",
"prob_bin_idx)**2) print('info gain', '\\n', info_gain) return info_gain def tf_labels_to_info_gain(labels, logits, alpha=0.2): last_axis =",
"tf.data.Dataset.from_tensor_slices(train_imgs) filename_pairs = filename_list.flat_map(input_parser) data_pairs = filename_pairs.map(filenames_to_data) data_pairs = data_pairs.batch(batch_size) # # #",
"print('sum_per_row', '\\n', sum_per_row) return e_x / sum_per_row def softmax_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as",
"depth * 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_name = \"%s/%03d_reconstructed.png\" % (output_dir, i)",
"= numpy_voxelmap.shape[2] new_depth = np.argmax(numpy_voxelmap, axis=2) new_depth = new_depth.T new_depth *= int(255 /",
"1], # [0, 0, 1, 0, 0], # [1, 1, 4, 1, 1],",
"= tf.cast(label_idx, dtype=tf.int32) label_idx = tf.tile(label_idx, [labels.shape[last_axis], 1]) label_idx = tf.transpose(label_idx) prob_bin_idx =",
"1, 4], # [4, 1, 1, 1, 1], ]) probs = softmax(logits) loss",
"0].set_title('depths_val') # axarr[1, 0].imshow(depths_val[0, :, :, 0]) # axarr[1, 1].set_title('depths_discretized_val') # axarr[1, 1].imshow(depths_discretized_val[0,",
"# layer = 2 # f, axarr = plt.subplots(2, 3) # axarr[0, 0].set_title('masks_val')",
"[1, 5, 1, 1, 1], # [0, 0, 1, 0, 0], # [1,",
"from dataset import DataSet def output_predict(depths, images, depths_discretized, depths_reconstructed, output_dir): print(\"output predict into",
"= np.tile(np.argmax(labels, axis=last_axis), (labels.shape[last_axis], 1)).T prob_bin_idx = np.tile(range(logits.shape[last_axis]), (labels.shape[0], 1)) # print('label_idx', '\\n',",
"in tensorflow\"\"\" e_x = np.exp(x) sum_per_row = np.tile(e_x.sum(axis=1), (x.shape[1], 1)).T print('e_x', '\\n', e_x)",
"as sess: # x = tf.constant(d) # # # for i in range(500):",
"\\ depths_reconstructed[i] pilimg = Image.fromarray(np.uint8(image)) image_name = \"%s/%03d_org.png\" % (output_dir, i) pilimg.save(image_name) depth",
"last_axis = len(logits.shape) - 1 label_idx = np.tile(np.argmax(labels, axis=last_axis), (labels.shape[last_axis], 1)).T prob_bin_idx =",
"depth = depth.transpose(2, 0, 1) if np.max(depth) != 0: ra_depth = (depth /",
"dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) return rgb_image, voxelmap, depth_reconstructed def tf_new_data_api_experiments(): # global sess",
"PIL import Image import Network import dataset from Network import BATCH_SIZE from dataset",
"quantization bin # l = np.round((np.log(d) - np.log(d_min)) / q_calc) # # print(d)",
"voxelmap occupied_ndc_grid = voxels_values[j, :, :, :] occupied_ndc_grid = np.flip(occupied_ndc_grid, axis=2) depth_size =",
"mask_multiplied, mask_multiplied_sum]) # sess.run(images) # # output_predict(depths_val, images_val, depths_discretized_val, # depth_reconstructed_val, 'kunda') #",
"Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_name = \"%s/%03d_reconstructed.png\" % (output_dir, i) depth_pil.save(depth_name) def playground_loss_function(labels, logits): #",
"= 4 with sess.as_default(): tf.logging.set_verbosity(tf.logging.INFO) # dataset = tf.data.TFRecordDataset(['train-voxel-gta.csv', 'test-voxel-gta.csv']) train_imgs = tf.constant(['train-voxel-gta.csv'])",
"depth_name = \"%s/%03d.png\" % (output_dir, i) depth_pil.save(depth_name) for j in range(dataset.DEPTH_DIM): ra_depth =",
"bin # l = np.round((np.log(d) - np.log(d_min)) / q_calc) # # print(d) #",
"loss diff', '\\n', new_loss - new_loss_tf) # f, axarr = plt.subplots(2, 3) #",
"losses def prob_to_logit(probs): return np.log(probs / (1 - probs)) def softmax(x): \"\"\"Same behaviour",
"axarr[1, 1].set_title('sample 4') # axarr[1, 1].plot(probs[3, :]) plt.plot(probs[0, :], color='r') plt.plot(probs[1, :], color='g')",
"*= int(255/depth_size) plt.figure(figsize=(10, 7)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/out-{}-depth-np.png'.format(j), bbox_inches='tight') def load_numpy_bin(): # name",
"0: # # print('hi', i) # # IMAGE_HEIGHT = 240 # IMAGE_WIDTH =",
"# [0, 0, 1, 0, 0], # [1, 1, 4, 1, 1], #",
"# axarr[0, 0].plot(d) # axarr[0, 1].plot(np.log(d)) # axarr[1, 0].plot(np.log(d) - np.log(d_min)) # axarr[1,",
"tf.transpose(prob_bin_idx) prob_bin_idx = tf.tile(prob_bin_idx, [labels.shape[0], 1]) difference = (label_idx - prob_bin_idx)**2 difference =",
"= softmax(logits) print('probs', '\\n', probs) logged_probs = np.log(probs) print('logged probs', '\\n', logged_probs) loss_per_row",
"1].set_title('sample 4') # axarr[1, 1].plot(probs[3, :]) plt.plot(probs[0, :], color='r') plt.plot(probs[1, :], color='g') plt.plot(probs[2,",
"with sess.as_default(): tf.logging.set_verbosity(tf.logging.INFO) # dataset = tf.data.TFRecordDataset(['train-voxel-gta.csv', 'test-voxel-gta.csv']) train_imgs = tf.constant(['train-voxel-gta.csv']) filename_list =",
"\"\"\"Same behaviour as tf.nn.softmax_cross_entropy_with_logits in tensorflow\"\"\" loss_per_row = - np.sum(labels * np.log(softmax(logits)), axis=1)",
"0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0,",
"# [3, 1, 1, 1, 1], # [0, 10, 0, 0, 0], #",
"image from voxelmap occupied_ndc_grid = voxels_values[j, :, :, :] occupied_ndc_grid = np.flip(occupied_ndc_grid, axis=2)",
"= \"%s/%03d_%03d_discr_m.png\" % (output_dir, i, j) # depth_discr_pil.save(depth_discr_name) # # for j in",
"reader.read(filename_queue) # filename, depth_filename = tf.decode_csv(serialized_example, [[\"path\"], [\"annotation\"]]) # # input # jpg",
"from PIL import Image import Network import dataset from Network import BATCH_SIZE from",
"# [image, depth, depth_discretized, invalid_depth], # batch_size=batch_size, # num_threads=4, # capacity=40) # #",
"= tf.data.TextLineDataset(filename).map(lambda line: tf.decode_csv(line, [[\"path\"], [\"annotation\"]])) return channel_data def filenames_to_data(rgb_filename, voxelmap_filename): tf.logging.warning(('rgb_filename', rgb_filename))",
"np.round((np.log(d) - np.log(d_min)) / q_calc) # # print(d) # print(l) # # print('q_calc',",
"= \"%s/%03d_%03d_discr_ml.png\" % (output_dir, i, j) # depth_discr_pil.save(depth_discr_name) depth = depth_reconstructed[:, :, 0]",
"# capacity=40) # # depth_reconstructed, weights, mask, mask_multiplied, mask_multiplied_sum = Network.Network.bins_to_depth(depths_discretized) # #",
"output bins = 200: 73 696 786 # for output bins = 100:",
"vars: ', total_vars) # for output bins = 200: 73 696 786 #",
"# depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) iterator = data_pairs.make_one_shot_iterator() batch_images, batch_voxels, batch_depths = iterator.get_next() for",
"np.log(d_min)) / (num_bins - 1) # # q = 0.5 # width of",
"tf.cast(depth, tf.int64) # # resize # image = tf.image.resize_images(image, (IMAGE_HEIGHT, IMAGE_WIDTH)) # depth",
"depth_size = numpy_voxelmap.shape[2] new_depth = np.argmax(numpy_voxelmap, axis=2) new_depth = new_depth.T new_depth *= int(255",
"np.max(depth)) * 255.0 else: ra_depth = depth * 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth[0]), mode=\"L\")",
"# # for i in range(500): # # if i % 500 ==",
"1].set_title('depths_discretized_val') # axarr[1, 1].imshow(depths_discretized_val[0, :, :, layer]) # axarr[0, 2].set_title('mask_multiplied_sum_val') # axarr[0, 2].imshow(mask_multiplied_sum_val[0,",
"probs = softmax(logits) print('probs', '\\n', probs) logged_probs = np.log(probs) print('logged probs', '\\n', logged_probs)",
"probs - probs_tf) print('loss', '\\n', loss) print('loss_tf', '\\n', loss_tf) print('loss diff', '\\n', loss",
"with tf.Session() as sess: # logits_tf = tf.constant(arr, dtype=tf.float32) # tf_mean = sess.run(tf.reduce_mean(logits_tf))",
"0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], # [0,",
"x = tf.constant(d) # # # for i in range(500): # # if",
"% (output_dir, i, j) # depth_discr_pil.save(depth_discr_name) # # for j in range(DEPTH_DIM): #",
"= data_pairs.batch(batch_size) # # # input # image = dataset.DataSet.filename_to_input_image(filename) # # target",
"# tf.nn.weighted_cross_entropy_with_logits(labels, logits, weights) losses = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) return losses def prob_to_logit(probs): return",
"d_min = np.min(d) # d_max = 20 # num_bins = 10 # q_calc",
"np.log(d_min)) / q_calc) # # print(d) # print(l) # # print('q_calc', q_calc) #",
"with tf.Graph().as_default(): # with tf.Session() as sess: # x = tf.constant(d) # #",
"# network = Network.Network() # network.prepare() # total_vars = np.sum([np.prod(v.get_shape().as_list()) for v in",
"np.exp(x) sum_per_row = np.tile(e_x.sum(axis=1), (x.shape[1], 1)).T print('e_x', '\\n', e_x) print('sum_per_row', '\\n', sum_per_row) return",
"plt.show() # network = Network.Network() # network.prepare() # total_vars = np.sum([np.prod(v.get_shape().as_list()) for v",
"# input # jpg = tf.read_file(filename) # image = tf.image.decode_jpeg(jpg, channels=3) # image",
"enumerate(images): image, depth, depth_discretized, depth_reconstructed = images[i], depths[i], depths_discretized[i], \\ depths_reconstructed[i] pilimg =",
"1], [0, 1, 0, 0, 0], # [3, 1, 1, 1, 1], #",
"depth_png = tf.read_file(depth_filename) # depth = tf.image.decode_png(depth_png, channels=1) # depth = tf.cast(depth, tf.float32)",
"= \"%s/%03d_%03d_discr.png\" % (output_dir, i, j) depth_discr_pil.save(depth_discr_name) # for j in range(DEPTH_DIM): #",
"0, 0, 0], [0, 2, 0, 0, 0], [1, 1, 1, 0, 0],",
"[0, 1, 0, 0, 0], [0, 1, 0, 0, 0], # [0, 1,",
"3) # axarr[0, 0].set_title('sample 1') # axarr[0, 0].plot(probs[0, :]) # axarr[0, 1].set_title('sample 2')",
":], color='g') plt.plot(probs[2, :], color='b') plt.plot(probs[3, :], color='y') plt.show() def input_parser(filename): assert tf.get_default_session()",
"# num_bins = 10 # q_calc = (np.log(np.max(d)) - np.log(d_min)) / (num_bins -",
"# images, depths, depths_discretized, invalid_depths = tf.train.batch( # [image, depth, depth_discretized, invalid_depth], #",
":]) # plt.show() # network = Network.Network() # network.prepare() # total_vars = np.sum([np.prod(v.get_shape().as_list())",
"data_pairs.make_one_shot_iterator() batch_images, batch_voxels, batch_depths = iterator.get_next() for i in range(1): images_values, voxels_values, depths_values",
"2], # [2, 2, 2, 4], # [4, 4, 4, 8], # ])",
"depth_pil.save(depth_name) for j in range(dataset.DEPTH_DIM): ra_depth = depth_discretized[:, :, j] * 255.0 depth_discr_pil",
"= tf.cast(depth, tf.int64) # # resize # image = tf.image.resize_images(image, (IMAGE_HEIGHT, IMAGE_WIDTH)) #",
"sum_per_row = np.tile(e_x.sum(axis=1), (x.shape[1], 1)).T print('e_x', '\\n', e_x) print('sum_per_row', '\\n', sum_per_row) return e_x",
"(output_dir, i) depth_pil.save(depth_name) def playground_loss_function(labels, logits): # in rank 2, [elements, classes] #",
"target # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) # depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) iterator = data_pairs.make_one_shot_iterator() batch_images,",
"import tensorflow as tf import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot",
"= iterator.get_next() for i in range(1): images_values, voxels_values, depths_values = sess.run([batch_images, batch_voxels, batch_depths])",
"0].plot(probs[0, :]) # axarr[0, 1].set_title('sample 2') # axarr[0, 1].plot(probs[1, :]) # axarr[1, 0].set_title('sample",
"depth_reconstructed_val, 'kunda') # # depth_reconstructed_val = depth_reconstructed_val[:, :, :, 0] # coord.request_stop() #",
"tf.image.decode_png(depth_png, channels=1) # depth = tf.cast(depth, tf.float32) # depth = depth / 255.0",
"# IMAGE_HEIGHT = 240 # IMAGE_WIDTH = 320 # TARGET_HEIGHT = 120 #",
"images, depths_discretized, depths_reconstructed, output_dir): print(\"output predict into %s\" % output_dir) if not tf.gfile.Exists(output_dir):",
"print('label_idx', '\\n', label_idx) # print('probs_idx', '\\n', prob_bin_idx) info_gain = np.exp(-alpha * (label_idx -",
":]) # axarr[1, 1].set_title('sample 4') # axarr[1, 1].plot(probs[3, :]) plt.plot(probs[0, :], color='r') plt.plot(probs[1,",
"# # target # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) # depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) iterator =",
"channel_data = tf.data.TextLineDataset(filename).map(lambda line: tf.decode_csv(line, [[\"path\"], [\"annotation\"]])) return channel_data def filenames_to_data(rgb_filename, voxelmap_filename): tf.logging.warning(('rgb_filename',",
"plt.subplots(2, 3) # axarr[0, 0].set_title('masks_val') # axarr[0, 0].imshow(mask_val[0, :, :, layer]) # axarr[0,",
"= plt.subplots(2, 3) # axarr[0, 0].set_title('sample 1') # axarr[0, 0].plot(probs[0, :]) # axarr[0,",
"= tf.cast(difference, dtype=tf.float32) info_gain = tf.exp(-alpha * difference) return info_gain def informed_cross_entropy_loss(labels, logits):",
"# print(l) # # print('q_calc', q_calc) # # f, axarr = plt.subplots(2, 2)",
"axarr[1, 1].plot(probs[3, :]) plt.plot(probs[0, :], color='r') plt.plot(probs[1, :], color='g') plt.plot(probs[2, :], color='b') plt.plot(probs[3,",
"0, 0], [0, 1, 0, 0, 0], # [0, 1, 0, 0, 0],",
"= tf.cast(image, tf.float32) # # target # depth_png = tf.read_file(depth_filename) # depth =",
"1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0,",
"* (label_idx - prob_bin_idx)**2) print('info gain', '\\n', info_gain) return info_gain def tf_labels_to_info_gain(labels, logits,",
"2].imshow(depth_reconstructed_val[0, :, :]) # plt.show() # network = Network.Network() # network.prepare() # total_vars",
"# # coord = tf.train.Coordinator() # threads = tf.train.start_queue_runners(sess=sess, coord=coord) # # images_val,",
"Network import dataset from Network import BATCH_SIZE from dataset import DataSet def output_predict(depths,",
"print(\"output predict into %s\" % output_dir) if not tf.gfile.Exists(output_dir): tf.gfile.MakeDirs(output_dir) for i, _",
"np.load(name) print(numpy_voxelmap.shape) # numpy_voxelmap = numpy_voxelmap.reshape([240, 160, 100]) numpy_voxelmap = np.flip(numpy_voxelmap, axis=2) #",
"= (np.log(np.max(d)) - np.log(d_min)) / (num_bins - 1) # # q = 0.5",
"= tf.constant(['train-voxel-gta.csv']) filename_list = tf.data.Dataset.from_tensor_slices(train_imgs) filename_pairs = filename_list.flat_map(input_parser) data_pairs = filename_pairs.map(filenames_to_data) data_pairs =",
"def informed_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as tf.nn.weighted_cross_entropy_with_logits in tensorflow\"\"\" probs = softmax(logits) print('probs',",
"boolean for each value # so I create mask to assign higher value",
"tf.logging.set_verbosity(tf.logging.INFO) # dataset = tf.data.TFRecordDataset(['train-voxel-gta.csv', 'test-voxel-gta.csv']) train_imgs = tf.constant(['train-voxel-gta.csv']) filename_list = tf.data.Dataset.from_tensor_slices(train_imgs) filename_pairs",
"pure numpy calculation of depth image from voxelmap occupied_ndc_grid = voxels_values[j, :, :,",
"0, 1, 0, 0], # [1, 1, 4, 1, 1], # [1, 1,",
"tf.nn.weighted_cross_entropy_with_logits in tensorflow\"\"\" probs = softmax(logits) print('probs', '\\n', probs) logged_probs = np.log(probs) print('logged",
"# axarr[1, 1].plot(probs[3, :]) plt.plot(probs[0, :], color='r') plt.plot(probs[1, :], color='g') plt.plot(probs[2, :], color='b')",
"tf.image.resize_images(image, (IMAGE_HEIGHT, IMAGE_WIDTH)) # depth = tf.image.resize_images(depth, (TARGET_HEIGHT, TARGET_WIDTH)) # # depth_discretized =",
"name = 'inspections/2018-03-07--17-57-32--527.bin' name = 'inspections/2018-03-07--17-57-32--527.npy' # numpy_voxelmap = np.fromfile(name, sep=';') numpy_voxelmap =",
"tensorflow\"\"\" probs = softmax(logits) print('probs', '\\n', probs) logged_probs = np.log(probs) print('logged probs', '\\n',",
"so I create mask to assign higher value to booleans in higher index",
"new_loss_tf) print('new loss diff', '\\n', new_loss - new_loss_tf) # f, axarr = plt.subplots(2,",
"[3, 1, 1, 1, 1], # [0, 10, 0, 0, 0], # [1,",
"_, serialized_example = reader.read(filename_queue) # filename, depth_filename = tf.decode_csv(serialized_example, [[\"path\"], [\"annotation\"]]) # #",
"logits_tf), logits=logits_tf)) # print('labels', '\\n', labels) # print('logits', '\\n', logits) # print('probs', '\\n',",
":], color='b') plt.plot(probs[3, :], color='y') plt.show() def input_parser(filename): assert tf.get_default_session() is sess tf.logging.warning(('filename',",
"[1, 1, 1, 2], # [2, 2, 2, 4], # [4, 4, 4,",
"0, 1], [0, 1, 0, 0, 0], # [3, 1, 1, 1, 1],",
"'\\n', new_loss_tf) print('new loss diff', '\\n', new_loss - new_loss_tf) # f, axarr =",
"j) # depth_discr_pil.save(depth_discr_name) depth = depth_reconstructed[:, :, 0] if np.max(depth) != 0: ra_depth",
"# global sess batch_size = 4 with sess.as_default(): tf.logging.set_verbosity(tf.logging.INFO) # dataset = tf.data.TFRecordDataset(['train-voxel-gta.csv',",
"difference = (label_idx - prob_bin_idx)**2 difference = tf.cast(difference, dtype=tf.float32) info_gain = tf.exp(-alpha *",
"= reader.read(filename_queue) # filename, depth_filename = tf.decode_csv(serialized_example, [[\"path\"], [\"annotation\"]]) # # input #",
"tf.trainable_variables()]) # print('trainable vars: ', total_vars) # for output bins = 200: 73",
":, :] occupied_ndc_grid = np.flip(occupied_ndc_grid, axis=2) depth_size = occupied_ndc_grid.shape[2] new_depth = np.argmax(occupied_ndc_grid, axis=2)",
"filename_pairs.map(filenames_to_data) data_pairs = data_pairs.batch(batch_size) # # # input # image = dataset.DataSet.filename_to_input_image(filename) #",
"tf.decode_csv(line, [[\"path\"], [\"annotation\"]])) return channel_data def filenames_to_data(rgb_filename, voxelmap_filename): tf.logging.warning(('rgb_filename', rgb_filename)) rgb_image = dataset.DataSet.filename_to_input_image(rgb_filename)",
"1)) # print('label_idx', '\\n', label_idx) # print('probs_idx', '\\n', prob_bin_idx) info_gain = np.exp(-alpha *",
"0].imshow(mask_val[0, :, :, layer]) # axarr[0, 1].set_title('mask_multiplied_val') # axarr[0, 1].imshow(mask_multiplied_val[0, :, :, layer])",
"= new_depth.T new_depth *= int(255 / depth_size) plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/2018-03-07--17-57-32--527.png',",
"# axarr[0, 1].imshow(mask_multiplied_val[0, :, :, layer]) # axarr[1, 0].set_title('depths_val') # axarr[1, 0].imshow(depths_val[0, :,",
"tf.train.start_queue_runners(sess=sess, coord=coord) # # images_val, depths_val, depths_discretized_val, invalid_depths_val, depth_reconstructed_val, mask_val, mask_multiplied_val, mask_multiplied_sum_val =",
"print('probs', '\\n', probs) # print('probs diff', '\\n', probs - probs_tf) print('loss', '\\n', loss)",
"dtype=tf.int32) label_idx = tf.tile(label_idx, [labels.shape[last_axis], 1]) label_idx = tf.transpose(label_idx) prob_bin_idx = tf.expand_dims(tf.range(logits.shape[last_axis], dtype=tf.int32),",
"(output_dir, i, j) # depth_discr_pil.save(depth_discr_name) depth = depth_reconstructed[:, :, 0] if np.max(depth) !=",
"iterator.get_next() for i in range(1): images_values, voxels_values, depths_values = sess.run([batch_images, batch_voxels, batch_depths]) for",
"tf.Graph().as_default(): # with tf.Session() as sess: # x = tf.constant(d) # # #",
"\"%s/%03d.png\" % (output_dir, i) depth_pil.save(depth_name) for j in range(dataset.DEPTH_DIM): ra_depth = depth_discretized[:, :,",
"0, 0, 0], [1, 1, 1, 0, 0], [0, 1, 0, 0, 1],",
"tf.Session() as sess: # logits_tf = tf.constant(arr, dtype=tf.float32) # tf_mean = sess.run(tf.reduce_mean(logits_tf)) #",
"tf.constant(d) # # # for i in range(500): # # if i %",
"= tf.tile(label_idx, [labels.shape[last_axis], 1]) label_idx = tf.transpose(label_idx) prob_bin_idx = tf.expand_dims(tf.range(logits.shape[last_axis], dtype=tf.int32), last_axis) prob_bin_idx",
":, :].astype(dtype=np.uint8)) plt.savefig('inspections/out-{}-rgb.png'.format(j), bbox_inches='tight') plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(depths_values[j, :, :].T, cmap='gray') plt.savefig('inspections/out-{}-depth.png'.format(j), bbox_inches='tight')",
"Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_discr_name = \"%s/%03d_%03d_discr.png\" % (output_dir, i, j) depth_discr_pil.save(depth_discr_name) # for j",
"plt.savefig('inspections/out-{}-rgb.png'.format(j), bbox_inches='tight') plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(depths_values[j, :, :].T, cmap='gray') plt.savefig('inspections/out-{}-depth.png'.format(j), bbox_inches='tight') # pure",
"1, 1], # [1, 1, 1, 4, 1], # [1, 1, 1, 1,",
"invalid_depths, depth_reconstructed, mask, mask_multiplied, mask_multiplied_sum]) # sess.run(images) # # output_predict(depths_val, images_val, depths_discretized_val, #",
"output_dir) if not tf.gfile.Exists(output_dir): tf.gfile.MakeDirs(output_dir) for i, _ in enumerate(images): image, depth, depth_discretized,",
"(TARGET_HEIGHT, TARGET_WIDTH)) # # depth_discretized = dataset.DataSet.discretize_depth(depth) # # invalid_depth = tf.sign(depth) #",
"tf_new_data_api_experiments(): # global sess batch_size = 4 with sess.as_default(): tf.logging.set_verbosity(tf.logging.INFO) # dataset =",
"depth = tf.cast(depth, tf.float32) # depth = depth / 255.0 # # depth",
"for j in range(DEPTH_DIM): # ra_depth = mask_lower[:, :, j] # depth_discr_pil =",
"axarr[0, 2].set_title('mask_multiplied_sum_val') # axarr[0, 2].imshow(mask_multiplied_sum_val[0, :, :]) # axarr[1, 2].set_title('depth_reconstructed_val') # axarr[1, 2].imshow(depth_reconstructed_val[0,",
"# threads = tf.train.start_queue_runners(sess=sess, coord=coord) # # images_val, depths_val, depths_discretized_val, invalid_depths_val, depth_reconstructed_val, mask_val,",
"new_depth.T new_depth *= int(255 / depth_size) plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/2018-03-07--17-57-32--527.png', bbox_inches='tight')",
"batch_size=batch_size, # num_threads=4, # capacity=40) # # depth_reconstructed, weights, mask, mask_multiplied, mask_multiplied_sum =",
"info_gain def informed_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as tf.nn.weighted_cross_entropy_with_logits in tensorflow\"\"\" probs = softmax(logits)",
"logits=logits) new_loss = informed_cross_entropy_loss(labels=labels, logits=logits) with tf.Graph().as_default(): with tf.Session() as sess: logits_tf =",
"= mask_lower[:, :, j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_ml.png\"",
"dataset.DEPTH_DIM]) # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) return rgb_image, voxelmap, depth_reconstructed def",
"pilimg.save(image_name) depth = depth.transpose(2, 0, 1) if np.max(depth) != 0: ra_depth = (depth",
"# target # depth_png = tf.read_file(depth_filename) # depth = tf.image.decode_png(depth_png, channels=1) # depth",
"dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) # depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) iterator = data_pairs.make_one_shot_iterator() batch_images, batch_voxels, batch_depths = iterator.get_next()",
"'\\n', sum_per_row) return e_x / sum_per_row def softmax_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as tf.nn.softmax_cross_entropy_with_logits",
"softmax(x): \"\"\"Same behaviour as tf.nn.softmax in tensorflow\"\"\" e_x = np.exp(x) sum_per_row = np.tile(e_x.sum(axis=1),",
"tf.constant(['train-voxel-gta.csv']) filename_list = tf.data.Dataset.from_tensor_slices(train_imgs) filename_pairs = filename_list.flat_map(input_parser) data_pairs = filename_pairs.map(filenames_to_data) data_pairs = data_pairs.batch(batch_size)",
"j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_m.png\" % (output_dir, i,",
"probs = softmax(logits) loss = softmax_cross_entropy_loss(labels=labels, logits=logits) new_loss = informed_cross_entropy_loss(labels=labels, logits=logits) with tf.Graph().as_default():",
"behaviour as tf.nn.softmax in tensorflow\"\"\" e_x = np.exp(x) sum_per_row = np.tile(e_x.sum(axis=1), (x.shape[1], 1)).T",
"= np.array([ # [1, 1, 1, 2], # [2, 2, 2, 4], #",
"loss_per_row def playing_with_losses(): labels = np.array([ [0, 1, 0, 0, 0], [0, 1,",
"0, 0, 1], [0, 1, 0, 0, 0], # [3, 1, 1, 1,",
"images[i], depths[i], depths_discretized[i], \\ depths_reconstructed[i] pilimg = Image.fromarray(np.uint8(image)) image_name = \"%s/%03d_org.png\" % (output_dir,",
"[image, depth, depth_discretized, invalid_depth], # batch_size=batch_size, # num_threads=4, # capacity=40) # # depth_reconstructed,",
":, :, :] occupied_ndc_grid = np.flip(occupied_ndc_grid, axis=2) depth_size = occupied_ndc_grid.shape[2] new_depth = np.argmax(occupied_ndc_grid,",
"import BATCH_SIZE from dataset import DataSet def output_predict(depths, images, depths_discretized, depths_reconstructed, output_dir): print(\"output",
"1, 0, 0, 0], [0, 1, 0, 0, 0], # [0, 1, 0,",
"1]) label_idx = tf.transpose(label_idx) prob_bin_idx = tf.expand_dims(tf.range(logits.shape[last_axis], dtype=tf.int32), last_axis) prob_bin_idx = tf.transpose(prob_bin_idx) prob_bin_idx",
"# # input # image = dataset.DataSet.filename_to_input_image(filename) # # target # voxelmap =",
"# ra_depth = mask[:, :, j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name",
"import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from PIL",
"'test-voxel-gta.csv']) train_imgs = tf.constant(['train-voxel-gta.csv']) filename_list = tf.data.Dataset.from_tensor_slices(train_imgs) filename_pairs = filename_list.flat_map(input_parser) data_pairs = filename_pairs.map(filenames_to_data)",
"ds = DataSet(8) # ds.load_params('train.csv') # # d = list(range(1, 100)) # d_min",
"axarr = plt.subplots(2, 3) # axarr[0, 0].set_title('sample 1') # axarr[0, 0].plot(probs[0, :]) #",
"plt.show() def input_parser(filename): assert tf.get_default_session() is sess tf.logging.warning(('filename', filename)) channel_data = tf.data.TextLineDataset(filename).map(lambda line:",
"# [2, 2, 2, 4], # [4, 4, 4, 8], # ]) #",
"dataset = tf.data.TFRecordDataset(['train-voxel-gta.csv', 'test-voxel-gta.csv']) train_imgs = tf.constant(['train-voxel-gta.csv']) filename_list = tf.data.Dataset.from_tensor_slices(train_imgs) filename_pairs = filename_list.flat_map(input_parser)",
"color='r') plt.plot(probs[1, :], color='g') plt.plot(probs[2, :], color='b') plt.plot(probs[3, :], color='y') plt.show() def input_parser(filename):",
"sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=tf_labels_to_info_gain(labels, logits_tf), logits=logits_tf)) # print('labels', '\\n', labels) # print('logits', '\\n', logits) # print('probs',",
"4, 4, 8], # ]) # with tf.Graph().as_default(): # with tf.Session() as sess:",
"depths_discretized, depths_reconstructed, output_dir): print(\"output predict into %s\" % output_dir) if not tf.gfile.Exists(output_dir): tf.gfile.MakeDirs(output_dir)",
"sum_per_row) return e_x / sum_per_row def softmax_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as tf.nn.softmax_cross_entropy_with_logits in",
"[1, 1, 4, 1, 1], # [1, 1, 1, 4, 1], # [1,",
"# # depth_reconstructed, weights, mask, mask_multiplied, mask_multiplied_sum = Network.Network.bins_to_depth(depths_discretized) # # print('weights: ',",
"= 10 # # filename_queue = tf.train.string_input_producer(['train.csv'], shuffle=True) # reader = tf.TextLineReader() #",
"range(1): images_values, voxels_values, depths_values = sess.run([batch_images, batch_voxels, batch_depths]) for j in range(batch_size): plt.figure(figsize=(10,",
"load_numpy_bin() tf_new_data_api_experiments() # arr = np.array([ # [1, 1, 1, 2], # [2,",
"= tf.train.Coordinator() # threads = tf.train.start_queue_runners(sess=sess, coord=coord) # # images_val, depths_val, depths_discretized_val, invalid_depths_val,",
":]) # axarr[0, 1].set_title('sample 2') # axarr[0, 1].plot(probs[1, :]) # axarr[1, 0].set_title('sample 3')",
"'\\n', prob_bin_idx) info_gain = np.exp(-alpha * (label_idx - prob_bin_idx)**2) print('info gain', '\\n', info_gain)",
"0], [0, 1, 0, 0, 1], [0, 1, 0, 0, 0], # [3,",
"network = Network.Network() # network.prepare() # total_vars = np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()])",
"tf.nn.softmax_cross_entropy_with_logits in tensorflow\"\"\" loss_per_row = - np.sum(labels * np.log(softmax(logits)), axis=1) return loss_per_row def",
"with tf.Graph().as_default(): # with tf.Session() as sess: # logits_tf = tf.constant(arr, dtype=tf.float32) #",
"depth.transpose(2, 0, 1) if np.max(depth) != 0: ra_depth = (depth / np.max(depth)) *",
"print('e_x', '\\n', e_x) print('sum_per_row', '\\n', sum_per_row) return e_x / sum_per_row def softmax_cross_entropy_loss(labels, logits):",
"# image = dataset.DataSet.filename_to_input_image(filename) # # target # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) # depth_reconstructed",
"voxelmap.set_shape([dataset.TARGET_WIDTH, dataset.TARGET_HEIGHT, dataset.DEPTH_DIM]) # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) return rgb_image, voxelmap,",
"1 label_idx = tf.expand_dims(tf.argmax(labels, axis=last_axis), 0) label_idx = tf.cast(label_idx, dtype=tf.int32) label_idx = tf.tile(label_idx,",
"1, 0, 0], # [0, 0, 0, 1, 0], # [0, 0, 0,",
"1], ]) probs = softmax(logits) loss = softmax_cross_entropy_loss(labels=labels, logits=logits) new_loss = informed_cross_entropy_loss(labels=labels, logits=logits)",
"else: ra_depth = depth * 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth[0]), mode=\"L\") depth_name = \"%s/%03d.png\"",
"tf import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from",
"int(255 / depth_size) plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/2018-03-07--17-57-32--527.png', bbox_inches='tight') sess = tf.Session(config=tf.ConfigProto(device_count={'GPU':",
"# numpy_voxelmap = numpy_voxelmap.reshape([240, 160, 100]) numpy_voxelmap = np.flip(numpy_voxelmap, axis=2) # now I",
":], color='y') plt.show() def input_parser(filename): assert tf.get_default_session() is sess tf.logging.warning(('filename', filename)) channel_data =",
"np.array([ [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1,",
"0].plot(probs[2, :]) # axarr[1, 1].set_title('sample 4') # axarr[1, 1].plot(probs[3, :]) plt.plot(probs[0, :], color='r')",
"index depth_size = numpy_voxelmap.shape[2] new_depth = np.argmax(numpy_voxelmap, axis=2) new_depth = new_depth.T new_depth *=",
"# [4, 1, 1, 1, 1], ]) probs = softmax(logits) loss = softmax_cross_entropy_loss(labels=labels,",
"= tf.image.resize_images(depth, (TARGET_HEIGHT, TARGET_WIDTH)) # # depth_discretized = dataset.DataSet.discretize_depth(depth) # # invalid_depth =",
"# # depth_discretized = dataset.DataSet.discretize_depth(depth) # # invalid_depth = tf.sign(depth) # # batch_size",
"mode=\"L\") depth_discr_name = \"%s/%03d_%03d_discr.png\" % (output_dir, i, j) depth_discr_pil.save(depth_discr_name) # for j in",
"tf.decode_csv(serialized_example, [[\"path\"], [\"annotation\"]]) # # input # jpg = tf.read_file(filename) # image =",
"# for output bins = 200: 73 696 786 # for output bins",
"plt.plot(probs[0, :], color='r') plt.plot(probs[1, :], color='g') plt.plot(probs[2, :], color='b') plt.plot(probs[3, :], color='y') plt.show()",
"0, 1, 0], # [0, 0, 0, 0, 1], # [1, 0, 0,",
"axarr[1, 2].set_title('depth_reconstructed_val') # axarr[1, 2].imshow(depth_reconstructed_val[0, :, :]) # plt.show() # network = Network.Network()",
"0].set_title('masks_val') # axarr[0, 0].imshow(mask_val[0, :, :, layer]) # axarr[0, 1].set_title('mask_multiplied_val') # axarr[0, 1].imshow(mask_multiplied_val[0,",
"# # print('q_calc', q_calc) # # f, axarr = plt.subplots(2, 2) # axarr[0,",
"= tf.expand_dims(tf.range(logits.shape[last_axis], dtype=tf.int32), last_axis) prob_bin_idx = tf.transpose(prob_bin_idx) prob_bin_idx = tf.tile(prob_bin_idx, [labels.shape[0], 1]) difference",
"[2, 2, 2, 4], # [4, 4, 4, 8], # ]) # with",
"dtype=tf.int32), last_axis) prob_bin_idx = tf.transpose(prob_bin_idx) prob_bin_idx = tf.tile(prob_bin_idx, [labels.shape[0], 1]) difference = (label_idx",
"[1, 1, 1, 0, 0], [0, 1, 0, 0, 1], [0, 1, 0,",
"# with tf.Graph().as_default(): # with tf.Session() as sess: # logits_tf = tf.constant(arr, dtype=tf.float32)",
"logits_tf = tf.constant(logits, dtype=tf.float32) labels_tf = tf.constant(labels, dtype=tf.float32) probs_tf = sess.run(tf.nn.softmax(logits_tf)) loss_tf =",
"# depth = tf.image.resize_images(depth, (TARGET_HEIGHT, TARGET_WIDTH)) # # depth_discretized = dataset.DataSet.discretize_depth(depth) # #",
"= len(logits.shape) - 1 label_idx = np.tile(np.argmax(labels, axis=last_axis), (labels.shape[last_axis], 1)).T prob_bin_idx = np.tile(range(logits.shape[last_axis]),",
"= np.flip(occupied_ndc_grid, axis=2) depth_size = occupied_ndc_grid.shape[2] new_depth = np.argmax(occupied_ndc_grid, axis=2) new_depth = new_depth.T",
"160, 100]) numpy_voxelmap = np.flip(numpy_voxelmap, axis=2) # now I have just boolean for",
"print('loss_tf', '\\n', loss_tf) print('loss diff', '\\n', loss - loss_tf) print('new_loss', '\\n', new_loss) print('new_loss_tf',",
"depths_val, depths_discretized_val, invalid_depths_val, depth_reconstructed_val, mask_val, mask_multiplied_val, mask_multiplied_sum_val = sess.run( # [images, depths, depths_discretized,",
"import Network import dataset from Network import BATCH_SIZE from dataset import DataSet def",
"= 'inspections/2018-03-07--17-57-32--527.bin' name = 'inspections/2018-03-07--17-57-32--527.npy' # numpy_voxelmap = np.fromfile(name, sep=';') numpy_voxelmap = np.load(name)",
"3) # axarr[0, 0].set_title('masks_val') # axarr[0, 0].imshow(mask_val[0, :, :, layer]) # axarr[0, 1].set_title('mask_multiplied_val')",
"tf.read_file(filename) # image = tf.image.decode_jpeg(jpg, channels=3) # image = tf.cast(image, tf.float32) # #",
"*= int(255 / depth_size) plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/2018-03-07--17-57-32--527.png', bbox_inches='tight') sess =",
"1, 2], # [2, 2, 2, 4], # [4, 4, 4, 8], #",
"# [1, 5, 1, 1, 1], # [0, 0, 1, 0, 0], #",
"= sess.run(tf.nn.softmax(logits_tf)) loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=labels_tf, logits=logits_tf)) new_loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=tf_labels_to_info_gain(labels, logits_tf), logits=logits_tf)) # print('labels',",
"f, axarr = plt.subplots(2, 3) # axarr[0, 0].set_title('masks_val') # axarr[0, 0].imshow(mask_val[0, :, :,",
"i) # # IMAGE_HEIGHT = 240 # IMAGE_WIDTH = 320 # TARGET_HEIGHT =",
"0, 1, 0, 0], # [0, 0, 0, 1, 0], # [0, 0,",
"def load_numpy_bin(): # name = 'inspections/2018-03-07--17-57-32--527.bin' name = 'inspections/2018-03-07--17-57-32--527.npy' # numpy_voxelmap = np.fromfile(name,",
"= tf.transpose(label_idx) prob_bin_idx = tf.expand_dims(tf.range(logits.shape[last_axis], dtype=tf.int32), last_axis) prob_bin_idx = tf.transpose(prob_bin_idx) prob_bin_idx = tf.tile(prob_bin_idx,",
":, j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_ml.png\" % (output_dir,",
"= DataSet(8) # ds.load_params('train.csv') # # d = list(range(1, 100)) # d_min =",
"playground_loss_function(labels, logits): # in rank 2, [elements, classes] # tf.nn.weighted_cross_entropy_with_logits(labels, logits, weights) losses",
"image, depth, depth_discretized, depth_reconstructed = images[i], depths[i], depths_discretized[i], \\ depths_reconstructed[i] pilimg = Image.fromarray(np.uint8(image))",
"j in range(DEPTH_DIM): # ra_depth = mask_lower[:, :, j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth),",
"i, j) # depth_discr_pil.save(depth_discr_name) depth = depth_reconstructed[:, :, 0] if np.max(depth) != 0:",
"* 255.0 else: ra_depth = depth * 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_name",
"label_idx = tf.expand_dims(tf.argmax(labels, axis=last_axis), 0) label_idx = tf.cast(label_idx, dtype=tf.int32) label_idx = tf.tile(label_idx, [labels.shape[last_axis],",
"= tf.data.TFRecordDataset(['train-voxel-gta.csv', 'test-voxel-gta.csv']) train_imgs = tf.constant(['train-voxel-gta.csv']) filename_list = tf.data.Dataset.from_tensor_slices(train_imgs) filename_pairs = filename_list.flat_map(input_parser) data_pairs",
"info_gain def tf_labels_to_info_gain(labels, logits, alpha=0.2): last_axis = len(logits.shape) - 1 label_idx = tf.expand_dims(tf.argmax(labels,",
"6)) plt.axis('off') plt.imshow(images_values[j, :, :, :].astype(dtype=np.uint8)) plt.savefig('inspections/out-{}-rgb.png'.format(j), bbox_inches='tight') plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(depths_values[j, :,",
"axis=last_axis), 0) label_idx = tf.cast(label_idx, dtype=tf.int32) label_idx = tf.tile(label_idx, [labels.shape[last_axis], 1]) label_idx =",
"numpy_voxelmap = np.fromfile(name, sep=';') numpy_voxelmap = np.load(name) print(numpy_voxelmap.shape) # numpy_voxelmap = numpy_voxelmap.reshape([240, 160,",
"1, 1, 1, 1], ]) probs = softmax(logits) loss = softmax_cross_entropy_loss(labels=labels, logits=logits) new_loss",
"= sess.run([batch_images, batch_voxels, batch_depths]) for j in range(batch_size): plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(images_values[j, :,",
"% (output_dir, i, j) depth_discr_pil.save(depth_discr_name) # for j in range(DEPTH_DIM): # ra_depth =",
"depths, depths_discretized, invalid_depths = tf.train.batch( # [image, depth, depth_discretized, invalid_depth], # batch_size=batch_size, #",
"[0, 0, 0, 1, 0], # [0, 0, 0, 0, 1], # [1,",
"filename_pairs = filename_list.flat_map(input_parser) data_pairs = filename_pairs.map(filenames_to_data) data_pairs = data_pairs.batch(batch_size) # # # input",
"# axarr[0, 1].set_title('sample 2') # axarr[0, 1].plot(probs[1, :]) # axarr[1, 0].set_title('sample 3') #",
"= 8 # # generate batch # images, depths, depths_discretized, invalid_depths = tf.train.batch(",
"image = tf.image.decode_jpeg(jpg, channels=3) # image = tf.cast(image, tf.float32) # # target #",
"0], # [3, 1, 1, 1, 1], # [0, 10, 0, 0, 0],",
"1].set_title('sample 2') # axarr[0, 1].plot(probs[1, :]) # axarr[1, 0].set_title('sample 3') # axarr[1, 0].plot(probs[2,",
"I create mask to assign higher value to booleans in higher index depth_size",
"print(l) # # print('q_calc', q_calc) # # f, axarr = plt.subplots(2, 2) #",
"(labels.shape[last_axis], 1)).T prob_bin_idx = np.tile(range(logits.shape[last_axis]), (labels.shape[0], 1)) # print('label_idx', '\\n', label_idx) # print('probs_idx',",
"= 20 # num_bins = 10 # q_calc = (np.log(np.max(d)) - np.log(d_min)) /",
"# # q = 0.5 # width of quantization bin # l =",
"'\\n', info_gain) return info_gain def tf_labels_to_info_gain(labels, logits, alpha=0.2): last_axis = len(logits.shape) - 1",
"print('logits', '\\n', logits) # print('probs', '\\n', probs) # print('probs diff', '\\n', probs -",
"# depth_discr_name = \"%s/%03d_%03d_discr_m.png\" % (output_dir, i, j) # depth_discr_pil.save(depth_discr_name) # # for",
"# image = tf.cast(image, tf.float32) # # target # depth_png = tf.read_file(depth_filename) #",
"= tf.read_file(filename) # image = tf.image.decode_jpeg(jpg, channels=3) # image = tf.cast(image, tf.float32) #",
"= depth / 255.0 # # depth = tf.cast(depth, tf.int64) # # resize",
":], color='r') plt.plot(probs[1, :], color='g') plt.plot(probs[2, :], color='b') plt.plot(probs[3, :], color='y') plt.show() def",
"= 10 # q_calc = (np.log(np.max(d)) - np.log(d_min)) / (num_bins - 1) #",
"1, 4, 1], # [1, 1, 1, 1, 4], # [4, 1, 1,",
"plt from PIL import Image import Network import dataset from Network import BATCH_SIZE",
"= tf.TextLineReader() # _, serialized_example = reader.read(filename_queue) # filename, depth_filename = tf.decode_csv(serialized_example, [[\"path\"],",
"batch_size = 8 # # generate batch # images, depths, depths_discretized, invalid_depths =",
"prob_bin_idx = tf.tile(prob_bin_idx, [labels.shape[0], 1]) difference = (label_idx - prob_bin_idx)**2 difference = tf.cast(difference,",
"np.sum(labels * np.log(softmax(logits)), axis=1) return loss_per_row def labels_to_info_gain(labels, logits, alpha=0.2): last_axis = len(logits.shape)",
"logged_probs) loss_per_row = - np.sum(labels_to_info_gain(labels, logits) * logged_probs, axis=1) return loss_per_row def playing_with_losses():",
"# # layer = 2 # f, axarr = plt.subplots(2, 3) # axarr[0,",
":, layer]) # axarr[0, 1].set_title('mask_multiplied_val') # axarr[0, 1].imshow(mask_multiplied_val[0, :, :, layer]) # axarr[1,",
"- new_loss_tf) # f, axarr = plt.subplots(2, 3) # axarr[0, 0].set_title('sample 1') #",
"= tf.constant(d) # # # for i in range(500): # # if i",
"invalid_depths_val, depth_reconstructed_val, mask_val, mask_multiplied_val, mask_multiplied_sum_val = sess.run( # [images, depths, depths_discretized, invalid_depths, depth_reconstructed,",
"batch_depths]) for j in range(batch_size): plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(images_values[j, :, :, :].astype(dtype=np.uint8)) plt.savefig('inspections/out-{}-rgb.png'.format(j),",
"def input_parser(filename): assert tf.get_default_session() is sess tf.logging.warning(('filename', filename)) channel_data = tf.data.TextLineDataset(filename).map(lambda line: tf.decode_csv(line,",
"# print('weights: ', weights) # # coord = tf.train.Coordinator() # threads = tf.train.start_queue_runners(sess=sess,",
"# with tf.Session() as sess: # logits_tf = tf.constant(arr, dtype=tf.float32) # tf_mean =",
"rgb_image = dataset.DataSet.filename_to_input_image(rgb_filename) voxelmap = tf.py_func(dataset.DataSet.filename_to_target_voxelmap, [voxelmap_filename], tf.int32) voxelmap.set_shape([dataset.TARGET_WIDTH, dataset.TARGET_HEIGHT, dataset.DEPTH_DIM]) # voxelmap",
"as tf.nn.softmax in tensorflow\"\"\" e_x = np.exp(x) sum_per_row = np.tile(e_x.sum(axis=1), (x.shape[1], 1)).T print('e_x',",
"loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=labels_tf, logits=logits_tf)) new_loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=tf_labels_to_info_gain(labels, logits_tf), logits=logits_tf)) # print('labels', '\\n', labels)",
"# print('mean_of_sum\\n', np.mean(np.sum(arr, axis=1), axis=0)) # ds = DataSet(8) # ds.load_params('train.csv') # #",
"losses = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) return losses def prob_to_logit(probs): return np.log(probs / (1 -",
"cmap='gray') plt.savefig('inspections/out-{}-depth-np.png'.format(j), bbox_inches='tight') def load_numpy_bin(): # name = 'inspections/2018-03-07--17-57-32--527.bin' name = 'inspections/2018-03-07--17-57-32--527.npy' #",
"weights) # # coord = tf.train.Coordinator() # threads = tf.train.start_queue_runners(sess=sess, coord=coord) # #",
"f, axarr = plt.subplots(2, 2) # axarr[0, 0].plot(d) # axarr[0, 1].plot(np.log(d)) # axarr[1,",
"label_idx = np.tile(np.argmax(labels, axis=last_axis), (labels.shape[last_axis], 1)).T prob_bin_idx = np.tile(range(logits.shape[last_axis]), (labels.shape[0], 1)) # print('label_idx',",
"= dataset.DataSet.tf_voxelmap_to_depth(voxelmap) iterator = data_pairs.make_one_shot_iterator() batch_images, batch_voxels, batch_depths = iterator.get_next() for i in",
"2].set_title('mask_multiplied_sum_val') # axarr[0, 2].imshow(mask_multiplied_sum_val[0, :, :]) # axarr[1, 2].set_title('depth_reconstructed_val') # axarr[1, 2].imshow(depth_reconstructed_val[0, :,",
"tf.train.string_input_producer(['train.csv'], shuffle=True) # reader = tf.TextLineReader() # _, serialized_example = reader.read(filename_queue) # filename,",
"% (output_dir, i, j) # depth_discr_pil.save(depth_discr_name) depth = depth_reconstructed[:, :, 0] if np.max(depth)",
"return info_gain def informed_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as tf.nn.weighted_cross_entropy_with_logits in tensorflow\"\"\" probs =",
"cmap='gray') plt.savefig('inspections/out-{}-depth.png'.format(j), bbox_inches='tight') # pure numpy calculation of depth image from voxelmap occupied_ndc_grid",
"sess.run(tf.reduce_mean(logits_tf)) # print('tf_mean\\n', tf_mean) # # print('mean\\n', np.mean(arr)) # print('sum_per_row\\n', np.sum(arr, axis=1)) #",
"new_depth = np.argmax(numpy_voxelmap, axis=2) new_depth = new_depth.T new_depth *= int(255 / depth_size) plt.figure(figsize=(10,",
"[0, 10, 0, 0, 0], [0, 2, 0, 0, 0], [1, 1, 1,",
"6)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/2018-03-07--17-57-32--527.png', bbox_inches='tight') sess = tf.Session(config=tf.ConfigProto(device_count={'GPU': 0})) if __name__ ==",
"'kunda') # # depth_reconstructed_val = depth_reconstructed_val[:, :, :, 0] # coord.request_stop() # coord.join(threads)",
"320 # TARGET_HEIGHT = 120 # TARGET_WIDTH = 160 # DEPTH_DIM = 10",
"ra_depth = (depth / np.max(depth)) * 255.0 else: ra_depth = depth * 255.0",
"print('new_loss', '\\n', new_loss) print('new_loss_tf', '\\n', new_loss_tf) print('new loss diff', '\\n', new_loss - new_loss_tf)",
"# axarr[1, 0].plot(probs[2, :]) # axarr[1, 1].set_title('sample 4') # axarr[1, 1].plot(probs[3, :]) plt.plot(probs[0,",
"3') # axarr[1, 0].plot(probs[2, :]) # axarr[1, 1].set_title('sample 4') # axarr[1, 1].plot(probs[3, :])",
"range(batch_size): plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(images_values[j, :, :, :].astype(dtype=np.uint8)) plt.savefig('inspections/out-{}-rgb.png'.format(j), bbox_inches='tight') plt.figure(figsize=(10, 6)) plt.axis('off')",
"# l = np.round((np.log(d) - np.log(d_min)) / q_calc) # # print(d) # print(l)",
":, :, 0] # coord.request_stop() # coord.join(threads) # # layer = 2 #",
"'\\n', logits) # print('probs', '\\n', probs) # print('probs diff', '\\n', probs - probs_tf)",
"depth = depth_reconstructed[:, :, 0] if np.max(depth) != 0: ra_depth = (depth /",
"depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) return rgb_image, voxelmap, depth_reconstructed def tf_new_data_api_experiments(): # global sess batch_size",
"print('hi', i) # # IMAGE_HEIGHT = 240 # IMAGE_WIDTH = 320 # TARGET_HEIGHT",
"generate batch # images, depths, depths_discretized, invalid_depths = tf.train.batch( # [image, depth, depth_discretized,",
"sess: # logits_tf = tf.constant(arr, dtype=tf.float32) # tf_mean = sess.run(tf.reduce_mean(logits_tf)) # print('tf_mean\\n', tf_mean)",
"axarr[1, 1].plot((np.log(d) - np.log(d_min)) / q_calc) # plt.show() # with tf.Graph().as_default(): # with",
":, layer]) # axarr[1, 0].set_title('depths_val') # axarr[1, 0].imshow(depths_val[0, :, :, 0]) # axarr[1,",
"depth_size = occupied_ndc_grid.shape[2] new_depth = np.argmax(occupied_ndc_grid, axis=2) new_depth = new_depth.T new_depth *= int(255/depth_size)",
"tf.train.batch( # [image, depth, depth_discretized, invalid_depth], # batch_size=batch_size, # num_threads=4, # capacity=40) #",
"numpy calculation of depth image from voxelmap occupied_ndc_grid = voxels_values[j, :, :, :]",
"= np.exp(-alpha * (label_idx - prob_bin_idx)**2) print('info gain', '\\n', info_gain) return info_gain def",
"d = list(range(1, 100)) # d_min = np.min(d) # d_max = 20 #",
"1, 0, 0, 0], # [0, 1, 0, 0, 0], # [0, 0,",
"np.array([ [0, 20, 0, 0, 0], [0, 10, 0, 0, 0], [0, 2,",
"probs', '\\n', logged_probs) loss_per_row = - np.sum(labels_to_info_gain(labels, logits) * logged_probs, axis=1) return loss_per_row",
"= images[i], depths[i], depths_discretized[i], \\ depths_reconstructed[i] pilimg = Image.fromarray(np.uint8(image)) image_name = \"%s/%03d_org.png\" %",
"0], # [1, 5, 1, 1, 1], # [0, 0, 1, 0, 0],",
"# # input # jpg = tf.read_file(filename) # image = tf.image.decode_jpeg(jpg, channels=3) #",
"= Network.Network.bins_to_depth(depths_discretized) # # print('weights: ', weights) # # coord = tf.train.Coordinator() #",
"q_calc = (np.log(np.max(d)) - np.log(d_min)) / (num_bins - 1) # # q =",
"# print('logits', '\\n', logits) # print('probs', '\\n', probs) # print('probs diff', '\\n', probs",
"np.max(depth)) * 255.0 else: ra_depth = depth * 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\")",
"mask_multiplied, mask_multiplied_sum = Network.Network.bins_to_depth(depths_discretized) # # print('weights: ', weights) # # coord =",
"= depth * 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth[0]), mode=\"L\") depth_name = \"%s/%03d.png\" % (output_dir,",
"tf.cast(difference, dtype=tf.float32) info_gain = tf.exp(-alpha * difference) return info_gain def informed_cross_entropy_loss(labels, logits): \"\"\"Same",
"np.max(depth) != 0: ra_depth = (depth / np.max(depth)) * 255.0 else: ra_depth =",
"'inspections/2018-03-07--17-57-32--527.bin' name = 'inspections/2018-03-07--17-57-32--527.npy' # numpy_voxelmap = np.fromfile(name, sep=';') numpy_voxelmap = np.load(name) print(numpy_voxelmap.shape)",
"np.flip(occupied_ndc_grid, axis=2) depth_size = occupied_ndc_grid.shape[2] new_depth = np.argmax(occupied_ndc_grid, axis=2) new_depth = new_depth.T new_depth",
"# reader = tf.TextLineReader() # _, serialized_example = reader.read(filename_queue) # filename, depth_filename =",
"axarr[1, 1].imshow(depths_discretized_val[0, :, :, layer]) # axarr[0, 2].set_title('mask_multiplied_sum_val') # axarr[0, 2].imshow(mask_multiplied_sum_val[0, :, :])",
"dtype=tf.float32) labels_tf = tf.constant(labels, dtype=tf.float32) probs_tf = sess.run(tf.nn.softmax(logits_tf)) loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=labels_tf, logits=logits_tf)) new_loss_tf",
"plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/out-{}-depth-np.png'.format(j), bbox_inches='tight') def load_numpy_bin(): # name = 'inspections/2018-03-07--17-57-32--527.bin' name = 'inspections/2018-03-07--17-57-32--527.npy'",
"axarr[0, 0].imshow(mask_val[0, :, :, layer]) # axarr[0, 1].set_title('mask_multiplied_val') # axarr[0, 1].imshow(mask_multiplied_val[0, :, :,",
"1, 1, 1], ]) probs = softmax(logits) loss = softmax_cross_entropy_loss(labels=labels, logits=logits) new_loss =",
"# print('probs_idx', '\\n', prob_bin_idx) info_gain = np.exp(-alpha * (label_idx - prob_bin_idx)**2) print('info gain',",
"= tf.decode_csv(serialized_example, [[\"path\"], [\"annotation\"]]) # # input # jpg = tf.read_file(filename) # image",
"= depth * 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_name = \"%s/%03d_reconstructed.png\" % (output_dir,",
"'\\n', new_loss - new_loss_tf) # f, axarr = plt.subplots(2, 3) # axarr[0, 0].set_title('sample",
"tf.Session(config=tf.ConfigProto(device_count={'GPU': 0})) if __name__ == '__main__': # playing_with_losses() # tf_dataset_experiments() # load_numpy_bin() tf_new_data_api_experiments()",
"# num_threads=4, # capacity=40) # # depth_reconstructed, weights, mask, mask_multiplied, mask_multiplied_sum = Network.Network.bins_to_depth(depths_discretized)",
"in tf.trainable_variables()]) # print('trainable vars: ', total_vars) # for output bins = 200:",
"occupied_ndc_grid.shape[2] new_depth = np.argmax(occupied_ndc_grid, axis=2) new_depth = new_depth.T new_depth *= int(255/depth_size) plt.figure(figsize=(10, 7))",
"layer]) # axarr[0, 2].set_title('mask_multiplied_sum_val') # axarr[0, 2].imshow(mask_multiplied_sum_val[0, :, :]) # axarr[1, 2].set_title('depth_reconstructed_val') #",
"BATCH_SIZE from dataset import DataSet def output_predict(depths, images, depths_discretized, depths_reconstructed, output_dir): print(\"output predict",
"image_name = \"%s/%03d_org.png\" % (output_dir, i) pilimg.save(image_name) depth = depth.transpose(2, 0, 1) if",
"sess tf.logging.warning(('filename', filename)) channel_data = tf.data.TextLineDataset(filename).map(lambda line: tf.decode_csv(line, [[\"path\"], [\"annotation\"]])) return channel_data def",
"0, 0, 0], [0, 10, 0, 0, 0], [0, 2, 0, 0, 0],",
"tf_mean) # # print('mean\\n', np.mean(arr)) # print('sum_per_row\\n', np.sum(arr, axis=1)) # print('mean_of_sum\\n', np.mean(np.sum(arr, axis=1),",
"* np.log(softmax(logits)), axis=1) return loss_per_row def labels_to_info_gain(labels, logits, alpha=0.2): last_axis = len(logits.shape) -",
"__name__ == '__main__': # playing_with_losses() # tf_dataset_experiments() # load_numpy_bin() tf_new_data_api_experiments() # arr =",
"# batch_size=batch_size, # num_threads=4, # capacity=40) # # depth_reconstructed, weights, mask, mask_multiplied, mask_multiplied_sum",
"output_predict(depths, images, depths_discretized, depths_reconstructed, output_dir): print(\"output predict into %s\" % output_dir) if not",
"0], # [0, 1, 0, 0, 0], # [0, 0, 1, 0, 0],",
"voxelmap_filename): tf.logging.warning(('rgb_filename', rgb_filename)) rgb_image = dataset.DataSet.filename_to_input_image(rgb_filename) voxelmap = tf.py_func(dataset.DataSet.filename_to_target_voxelmap, [voxelmap_filename], tf.int32) voxelmap.set_shape([dataset.TARGET_WIDTH, dataset.TARGET_HEIGHT,",
"in tensorflow\"\"\" probs = softmax(logits) print('probs', '\\n', probs) logged_probs = np.log(probs) print('logged probs',",
"f, axarr = plt.subplots(2, 3) # axarr[0, 0].set_title('sample 1') # axarr[0, 0].plot(probs[0, :])",
"logits, alpha=0.2): last_axis = len(logits.shape) - 1 label_idx = tf.expand_dims(tf.argmax(labels, axis=last_axis), 0) label_idx",
"# dataset = tf.data.TFRecordDataset(['train-voxel-gta.csv', 'test-voxel-gta.csv']) train_imgs = tf.constant(['train-voxel-gta.csv']) filename_list = tf.data.Dataset.from_tensor_slices(train_imgs) filename_pairs =",
"image = dataset.DataSet.filename_to_input_image(filename) # # target # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) # depth_reconstructed =",
"color='g') plt.plot(probs[2, :], color='b') plt.plot(probs[3, :], color='y') plt.show() def input_parser(filename): assert tf.get_default_session() is",
"= tf.image.resize_images(image, (IMAGE_HEIGHT, IMAGE_WIDTH)) # depth = tf.image.resize_images(depth, (TARGET_HEIGHT, TARGET_WIDTH)) # # depth_discretized",
"depths_discretized_val, # depth_reconstructed_val, 'kunda') # # depth_reconstructed_val = depth_reconstructed_val[:, :, :, 0] #",
"= np.argmax(occupied_ndc_grid, axis=2) new_depth = new_depth.T new_depth *= int(255/depth_size) plt.figure(figsize=(10, 7)) plt.axis('off') plt.imshow(new_depth,",
"depth * 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth[0]), mode=\"L\") depth_name = \"%s/%03d.png\" % (output_dir, i)",
"capacity=40) # # depth_reconstructed, weights, mask, mask_multiplied, mask_multiplied_sum = Network.Network.bins_to_depth(depths_discretized) # # print('weights:",
"[0, 0, 1, 0, 0], # [1, 1, 4, 1, 1], # [1,",
":]) plt.plot(probs[0, :], color='r') plt.plot(probs[1, :], color='g') plt.plot(probs[2, :], color='b') plt.plot(probs[3, :], color='y')",
"0, 0, 0, 0], ]) logits = np.array([ [0, 20, 0, 0, 0],",
"data_pairs = data_pairs.batch(batch_size) # # # input # image = dataset.DataSet.filename_to_input_image(filename) # #",
"# [1, 1, 1, 1, 4], # [4, 1, 1, 1, 1], ])",
"np.log(probs) print('logged probs', '\\n', logged_probs) loss_per_row = - np.sum(labels_to_info_gain(labels, logits) * logged_probs, axis=1)",
"depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_discr_name = \"%s/%03d_%03d_discr.png\" % (output_dir, i, j) depth_discr_pil.save(depth_discr_name) #",
"= tf.exp(-alpha * difference) return info_gain def informed_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as tf.nn.weighted_cross_entropy_with_logits",
"softmax(logits) loss = softmax_cross_entropy_loss(labels=labels, logits=logits) new_loss = informed_cross_entropy_loss(labels=labels, logits=logits) with tf.Graph().as_default(): with tf.Session()",
"as plt from PIL import Image import Network import dataset from Network import",
"% 500 == 0: # # print('hi', i) # # IMAGE_HEIGHT = 240",
"depth = tf.cast(depth, tf.int64) # # resize # image = tf.image.resize_images(image, (IMAGE_HEIGHT, IMAGE_WIDTH))",
"1) # # q = 0.5 # width of quantization bin # l",
"'\\n', loss - loss_tf) print('new_loss', '\\n', new_loss) print('new_loss_tf', '\\n', new_loss_tf) print('new loss diff',",
"depth_reconstructed_val = depth_reconstructed_val[:, :, :, 0] # coord.request_stop() # coord.join(threads) # # layer",
"behaviour as tf.nn.weighted_cross_entropy_with_logits in tensorflow\"\"\" probs = softmax(logits) print('probs', '\\n', probs) logged_probs =",
"1, 4, 1, 1], # [1, 1, 1, 4, 1], # [1, 1,",
":, 0] # coord.request_stop() # coord.join(threads) # # layer = 2 # f,",
"0], [0, 1, 0, 0, 0], # [0, 1, 0, 0, 0], #",
"depths_discretized_val, invalid_depths_val, depth_reconstructed_val, mask_val, mask_multiplied_val, mask_multiplied_sum_val = sess.run( # [images, depths, depths_discretized, invalid_depths,",
"np.argmax(occupied_ndc_grid, axis=2) new_depth = new_depth.T new_depth *= int(255/depth_size) plt.figure(figsize=(10, 7)) plt.axis('off') plt.imshow(new_depth, cmap='gray')",
"# # f, axarr = plt.subplots(2, 2) # axarr[0, 0].plot(d) # axarr[0, 1].plot(np.log(d))",
"2) # axarr[0, 0].plot(d) # axarr[0, 1].plot(np.log(d)) # axarr[1, 0].plot(np.log(d) - np.log(d_min)) #",
"as sess: # logits_tf = tf.constant(arr, dtype=tf.float32) # tf_mean = sess.run(tf.reduce_mean(logits_tf)) # print('tf_mean\\n',",
"[0, 20, 0, 0, 0], [0, 10, 0, 0, 0], [0, 2, 0,",
"sess.as_default(): tf.logging.set_verbosity(tf.logging.INFO) # dataset = tf.data.TFRecordDataset(['train-voxel-gta.csv', 'test-voxel-gta.csv']) train_imgs = tf.constant(['train-voxel-gta.csv']) filename_list = tf.data.Dataset.from_tensor_slices(train_imgs)",
"/ sum_per_row def softmax_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as tf.nn.softmax_cross_entropy_with_logits in tensorflow\"\"\" loss_per_row =",
"voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) return rgb_image, voxelmap, depth_reconstructed def tf_new_data_api_experiments(): #",
"dataset from Network import BATCH_SIZE from dataset import DataSet def output_predict(depths, images, depths_discretized,",
"depths_discretized, invalid_depths = tf.train.batch( # [image, depth, depth_discretized, invalid_depth], # batch_size=batch_size, # num_threads=4,",
"- np.sum(labels_to_info_gain(labels, logits) * logged_probs, axis=1) return loss_per_row def playing_with_losses(): labels = np.array([",
"depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_ml.png\" % (output_dir, i, j) #",
"v in tf.trainable_variables()]) # print('trainable vars: ', total_vars) # for output bins =",
"# d_min = np.min(d) # d_max = 20 # num_bins = 10 #",
"= (label_idx - prob_bin_idx)**2 difference = tf.cast(difference, dtype=tf.float32) info_gain = tf.exp(-alpha * difference)",
"axis=1)) # print('mean_of_sum\\n', np.mean(np.sum(arr, axis=1), axis=0)) # ds = DataSet(8) # ds.load_params('train.csv') #",
"print('weights: ', weights) # # coord = tf.train.Coordinator() # threads = tf.train.start_queue_runners(sess=sess, coord=coord)",
"1, 1, 0, 0], [0, 1, 0, 0, 1], [0, 1, 0, 0,",
"# axarr[1, 0].set_title('depths_val') # axarr[1, 0].imshow(depths_val[0, :, :, 0]) # axarr[1, 1].set_title('depths_discretized_val') #",
"4, 1], # [1, 1, 1, 1, 4], # [4, 1, 1, 1,",
"batch_depths = iterator.get_next() for i in range(1): images_values, voxels_values, depths_values = sess.run([batch_images, batch_voxels,",
"images_val, depths_discretized_val, # depth_reconstructed_val, 'kunda') # # depth_reconstructed_val = depth_reconstructed_val[:, :, :, 0]",
"sess batch_size = 4 with sess.as_default(): tf.logging.set_verbosity(tf.logging.INFO) # dataset = tf.data.TFRecordDataset(['train-voxel-gta.csv', 'test-voxel-gta.csv']) train_imgs",
"= tf.cast(depth, tf.float32) # depth = depth / 255.0 # # depth =",
"new_depth *= int(255/depth_size) plt.figure(figsize=(10, 7)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/out-{}-depth-np.png'.format(j), bbox_inches='tight') def load_numpy_bin(): #",
"= sess.run( # [images, depths, depths_discretized, invalid_depths, depth_reconstructed, mask, mask_multiplied, mask_multiplied_sum]) # sess.run(images)",
"# depth_discr_pil.save(depth_discr_name) # # for j in range(DEPTH_DIM): # ra_depth = mask_lower[:, :,",
"# axarr[0, 1].set_title('mask_multiplied_val') # axarr[0, 1].imshow(mask_multiplied_val[0, :, :, layer]) # axarr[1, 0].set_title('depths_val') #",
"/ (1 - probs)) def softmax(x): \"\"\"Same behaviour as tf.nn.softmax in tensorflow\"\"\" e_x",
"plt.imshow(depths_values[j, :, :].T, cmap='gray') plt.savefig('inspections/out-{}-depth.png'.format(j), bbox_inches='tight') # pure numpy calculation of depth image",
"# output_predict(depths_val, images_val, depths_discretized_val, # depth_reconstructed_val, 'kunda') # # depth_reconstructed_val = depth_reconstructed_val[:, :,",
"return rgb_image, voxelmap, depth_reconstructed def tf_new_data_api_experiments(): # global sess batch_size = 4 with",
"occupied_ndc_grid = np.flip(occupied_ndc_grid, axis=2) depth_size = occupied_ndc_grid.shape[2] new_depth = np.argmax(occupied_ndc_grid, axis=2) new_depth =",
"depth_name = \"%s/%03d_reconstructed.png\" % (output_dir, i) depth_pil.save(depth_name) def playground_loss_function(labels, logits): # in rank",
"[labels.shape[last_axis], 1]) label_idx = tf.transpose(label_idx) prob_bin_idx = tf.expand_dims(tf.range(logits.shape[last_axis], dtype=tf.int32), last_axis) prob_bin_idx = tf.transpose(prob_bin_idx)",
"labels_tf = tf.constant(labels, dtype=tf.float32) probs_tf = sess.run(tf.nn.softmax(logits_tf)) loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=labels_tf, logits=logits_tf)) new_loss_tf =",
"# axarr[1, 0].set_title('sample 3') # axarr[1, 0].plot(probs[2, :]) # axarr[1, 1].set_title('sample 4') #",
"batch_voxels, batch_depths = iterator.get_next() for i in range(1): images_values, voxels_values, depths_values = sess.run([batch_images,",
"', weights) # # coord = tf.train.Coordinator() # threads = tf.train.start_queue_runners(sess=sess, coord=coord) #",
"# axarr[1, 1].plot((np.log(d) - np.log(d_min)) / q_calc) # plt.show() # with tf.Graph().as_default(): #",
"range(DEPTH_DIM): # ra_depth = mask_lower[:, :, j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") #",
"weights) losses = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) return losses def prob_to_logit(probs): return np.log(probs / (1",
"# tf_dataset_experiments() # load_numpy_bin() tf_new_data_api_experiments() # arr = np.array([ # [1, 1, 1,",
"depth_reconstructed, weights, mask, mask_multiplied, mask_multiplied_sum = Network.Network.bins_to_depth(depths_discretized) # # print('weights: ', weights) #",
"# depth_discretized = dataset.DataSet.discretize_depth(depth) # # invalid_depth = tf.sign(depth) # # batch_size =",
"print('trainable vars: ', total_vars) # for output bins = 200: 73 696 786",
"# axarr[0, 2].set_title('mask_multiplied_sum_val') # axarr[0, 2].imshow(mask_multiplied_sum_val[0, :, :]) # axarr[1, 2].set_title('depth_reconstructed_val') # axarr[1,",
"= tf.image.decode_png(depth_png, channels=1) # depth = tf.cast(depth, tf.float32) # depth = depth /",
"sess.run(images) # # output_predict(depths_val, images_val, depths_discretized_val, # depth_reconstructed_val, 'kunda') # # depth_reconstructed_val =",
"10, 0, 0, 0], # [1, 5, 1, 1, 1], # [0, 0,",
"100)) # d_min = np.min(d) # d_max = 20 # num_bins = 10",
"', total_vars) # for output bins = 200: 73 696 786 # for",
"0, 0], # [0, 0, 0, 1, 0], # [0, 0, 0, 0,",
"1, 1, 1, 4], # [4, 1, 1, 1, 1], ]) probs =",
"1, 0], # [0, 0, 0, 0, 1], # [1, 0, 0, 0,",
"IMAGE_WIDTH = 320 # TARGET_HEIGHT = 120 # TARGET_WIDTH = 160 # DEPTH_DIM",
"filenames_to_data(rgb_filename, voxelmap_filename): tf.logging.warning(('rgb_filename', rgb_filename)) rgb_image = dataset.DataSet.filename_to_input_image(rgb_filename) voxelmap = tf.py_func(dataset.DataSet.filename_to_target_voxelmap, [voxelmap_filename], tf.int32) voxelmap.set_shape([dataset.TARGET_WIDTH,",
"# depth = depth / 255.0 # # depth = tf.cast(depth, tf.int64) #",
"voxelmap = tf.py_func(dataset.DataSet.filename_to_target_voxelmap, [voxelmap_filename], tf.int32) voxelmap.set_shape([dataset.TARGET_WIDTH, dataset.TARGET_HEIGHT, dataset.DEPTH_DIM]) # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) depth_reconstructed",
"import Image import Network import dataset from Network import BATCH_SIZE from dataset import",
"print('loss diff', '\\n', loss - loss_tf) print('new_loss', '\\n', new_loss) print('new_loss_tf', '\\n', new_loss_tf) print('new",
"# so I create mask to assign higher value to booleans in higher",
"100]) numpy_voxelmap = np.flip(numpy_voxelmap, axis=2) # now I have just boolean for each",
"tf.tile(label_idx, [labels.shape[last_axis], 1]) label_idx = tf.transpose(label_idx) prob_bin_idx = tf.expand_dims(tf.range(logits.shape[last_axis], dtype=tf.int32), last_axis) prob_bin_idx =",
"color='y') plt.show() def input_parser(filename): assert tf.get_default_session() is sess tf.logging.warning(('filename', filename)) channel_data = tf.data.TextLineDataset(filename).map(lambda",
"num_bins = 10 # q_calc = (np.log(np.max(d)) - np.log(d_min)) / (num_bins - 1)",
"# [0, 0, 0, 1, 0], # [0, 0, 0, 0, 1], #",
"booleans in higher index depth_size = numpy_voxelmap.shape[2] new_depth = np.argmax(numpy_voxelmap, axis=2) new_depth =",
"np.log(d_min)) / q_calc) # plt.show() # with tf.Graph().as_default(): # with tf.Session() as sess:",
"depth_discr_pil.save(depth_discr_name) # # for j in range(DEPTH_DIM): # ra_depth = mask_lower[:, :, j]",
"2, [elements, classes] # tf.nn.weighted_cross_entropy_with_logits(labels, logits, weights) losses = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) return losses",
"= Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_name = \"%s/%03d_reconstructed.png\" % (output_dir, i) depth_pil.save(depth_name) def playground_loss_function(labels, logits):",
"Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_m.png\" % (output_dir, i, j) # depth_discr_pil.save(depth_discr_name) #",
"= data_pairs.make_one_shot_iterator() batch_images, batch_voxels, batch_depths = iterator.get_next() for i in range(1): images_values, voxels_values,",
":].astype(dtype=np.uint8)) plt.savefig('inspections/out-{}-rgb.png'.format(j), bbox_inches='tight') plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(depths_values[j, :, :].T, cmap='gray') plt.savefig('inspections/out-{}-depth.png'.format(j), bbox_inches='tight') #",
"tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) return losses def prob_to_logit(probs): return np.log(probs / (1 - probs)) def",
"return np.log(probs / (1 - probs)) def softmax(x): \"\"\"Same behaviour as tf.nn.softmax in",
"voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) # depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) iterator = data_pairs.make_one_shot_iterator() batch_images, batch_voxels, batch_depths",
"0, 0], # [1, 1, 4, 1, 1], # [1, 1, 1, 4,",
"= \"%s/%03d_org.png\" % (output_dir, i) pilimg.save(image_name) depth = depth.transpose(2, 0, 1) if np.max(depth)",
"# axarr[0, 0].imshow(mask_val[0, :, :, layer]) # axarr[0, 1].set_title('mask_multiplied_val') # axarr[0, 1].imshow(mask_multiplied_val[0, :,",
"axarr[1, 0].set_title('sample 3') # axarr[1, 0].plot(probs[2, :]) # axarr[1, 1].set_title('sample 4') # axarr[1,",
"= Network.Network() # network.prepare() # total_vars = np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()]) #",
"matplotlib.pyplot as plt from PIL import Image import Network import dataset from Network",
"- probs)) def softmax(x): \"\"\"Same behaviour as tf.nn.softmax in tensorflow\"\"\" e_x = np.exp(x)",
"mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_m.png\" % (output_dir, i, j) # depth_discr_pil.save(depth_discr_name) # #",
"mask_multiplied_sum_val = sess.run( # [images, depths, depths_discretized, invalid_depths, depth_reconstructed, mask, mask_multiplied, mask_multiplied_sum]) #",
"# [0, 1, 0, 0, 0], # [0, 0, 1, 0, 0], #",
"create mask to assign higher value to booleans in higher index depth_size =",
"threads = tf.train.start_queue_runners(sess=sess, coord=coord) # # images_val, depths_val, depths_discretized_val, invalid_depths_val, depth_reconstructed_val, mask_val, mask_multiplied_val,",
"plt.savefig('inspections/out-{}-depth.png'.format(j), bbox_inches='tight') # pure numpy calculation of depth image from voxelmap occupied_ndc_grid =",
"# axarr[0, 1].plot(probs[1, :]) # axarr[1, 0].set_title('sample 3') # axarr[1, 0].plot(probs[2, :]) #",
"# # # input # image = dataset.DataSet.filename_to_input_image(filename) # # target # voxelmap",
"mask_multiplied_val, mask_multiplied_sum_val = sess.run( # [images, depths, depths_discretized, invalid_depths, depth_reconstructed, mask, mask_multiplied, mask_multiplied_sum])",
"Network.Network.bins_to_depth(depths_discretized) # # print('weights: ', weights) # # coord = tf.train.Coordinator() # threads",
"mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_ml.png\" % (output_dir, i, j) # depth_discr_pil.save(depth_discr_name) depth =",
"e_x / sum_per_row def softmax_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as tf.nn.softmax_cross_entropy_with_logits in tensorflow\"\"\" loss_per_row",
"# depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_m.png\" % (output_dir, i, j)",
"2, 2, 4], # [4, 4, 4, 8], # ]) # with tf.Graph().as_default():",
"'\\n', probs - probs_tf) print('loss', '\\n', loss) print('loss_tf', '\\n', loss_tf) print('loss diff', '\\n',",
"axis=0)) # ds = DataSet(8) # ds.load_params('train.csv') # # d = list(range(1, 100))",
"np.tile(e_x.sum(axis=1), (x.shape[1], 1)).T print('e_x', '\\n', e_x) print('sum_per_row', '\\n', sum_per_row) return e_x / sum_per_row",
"axarr = plt.subplots(2, 2) # axarr[0, 0].plot(d) # axarr[0, 1].plot(np.log(d)) # axarr[1, 0].plot(np.log(d)",
"1, 0, 0, 0], # [0, 0, 1, 0, 0], # [0, 0,",
"new_depth = new_depth.T new_depth *= int(255 / depth_size) plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(new_depth, cmap='gray')",
"axarr[0, 1].plot(probs[1, :]) # axarr[1, 0].set_title('sample 3') # axarr[1, 0].plot(probs[2, :]) # axarr[1,",
"# q = 0.5 # width of quantization bin # l = np.round((np.log(d)",
"axarr[1, 0].set_title('depths_val') # axarr[1, 0].imshow(depths_val[0, :, :, 0]) # axarr[1, 1].set_title('depths_discretized_val') # axarr[1,",
"1], # [0, 10, 0, 0, 0], # [1, 5, 1, 1, 1],",
"loss_per_row = - np.sum(labels_to_info_gain(labels, logits) * logged_probs, axis=1) return loss_per_row def playing_with_losses(): labels",
"1, 0, 0], # [1, 1, 4, 1, 1], # [1, 1, 1,",
"# numpy_voxelmap = np.fromfile(name, sep=';') numpy_voxelmap = np.load(name) print(numpy_voxelmap.shape) # numpy_voxelmap = numpy_voxelmap.reshape([240,",
"new_loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=tf_labels_to_info_gain(labels, logits_tf), logits=logits_tf)) # print('labels', '\\n', labels) # print('logits', '\\n', logits)",
"def playground_loss_function(labels, logits): # in rank 2, [elements, classes] # tf.nn.weighted_cross_entropy_with_logits(labels, logits, weights)",
"# axarr[1, 2].imshow(depth_reconstructed_val[0, :, :]) # plt.show() # network = Network.Network() # network.prepare()",
"tf.exp(-alpha * difference) return info_gain def informed_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as tf.nn.weighted_cross_entropy_with_logits in",
"1].plot(probs[1, :]) # axarr[1, 0].set_title('sample 3') # axarr[1, 0].plot(probs[2, :]) # axarr[1, 1].set_title('sample",
"1].plot((np.log(d) - np.log(d_min)) / q_calc) # plt.show() # with tf.Graph().as_default(): # with tf.Session()",
"# arr = np.array([ # [1, 1, 1, 2], # [2, 2, 2,",
"% output_dir) if not tf.gfile.Exists(output_dir): tf.gfile.MakeDirs(output_dir) for i, _ in enumerate(images): image, depth,",
"# ]) # with tf.Graph().as_default(): # with tf.Session() as sess: # logits_tf =",
"int(255/depth_size) plt.figure(figsize=(10, 7)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/out-{}-depth-np.png'.format(j), bbox_inches='tight') def load_numpy_bin(): # name =",
"# _, serialized_example = reader.read(filename_queue) # filename, depth_filename = tf.decode_csv(serialized_example, [[\"path\"], [\"annotation\"]]) #",
"[0, 0, 1, 0, 0], # [0, 0, 0, 1, 0], # [0,",
"output_predict(depths_val, images_val, depths_discretized_val, # depth_reconstructed_val, 'kunda') # # depth_reconstructed_val = depth_reconstructed_val[:, :, :,",
"np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()]) # print('trainable vars: ', total_vars) # for output",
"# depth_reconstructed_val, 'kunda') # # depth_reconstructed_val = depth_reconstructed_val[:, :, :, 0] # coord.request_stop()",
"resize # image = tf.image.resize_images(image, (IMAGE_HEIGHT, IMAGE_WIDTH)) # depth = tf.image.resize_images(depth, (TARGET_HEIGHT, TARGET_WIDTH))",
"= tf.train.start_queue_runners(sess=sess, coord=coord) # # images_val, depths_val, depths_discretized_val, invalid_depths_val, depth_reconstructed_val, mask_val, mask_multiplied_val, mask_multiplied_sum_val",
"120 # TARGET_WIDTH = 160 # DEPTH_DIM = 10 # # filename_queue =",
"* 255.0 else: ra_depth = depth * 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth[0]), mode=\"L\") depth_name",
"# print('trainable vars: ', total_vars) # for output bins = 200: 73 696",
"= new_depth.T new_depth *= int(255/depth_size) plt.figure(figsize=(10, 7)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/out-{}-depth-np.png'.format(j), bbox_inches='tight') def",
"'__main__': # playing_with_losses() # tf_dataset_experiments() # load_numpy_bin() tf_new_data_api_experiments() # arr = np.array([ #",
"for output bins = 200: 73 696 786 # for output bins =",
"IMAGE_HEIGHT = 240 # IMAGE_WIDTH = 320 # TARGET_HEIGHT = 120 # TARGET_WIDTH",
"np.min(d) # d_max = 20 # num_bins = 10 # q_calc = (np.log(np.max(d))",
":, :, 0]) # axarr[1, 1].set_title('depths_discretized_val') # axarr[1, 1].imshow(depths_discretized_val[0, :, :, layer]) #",
"occupied_ndc_grid = voxels_values[j, :, :, :] occupied_ndc_grid = np.flip(occupied_ndc_grid, axis=2) depth_size = occupied_ndc_grid.shape[2]",
"[images, depths, depths_discretized, invalid_depths, depth_reconstructed, mask, mask_multiplied, mask_multiplied_sum]) # sess.run(images) # # output_predict(depths_val,",
"logits) * logged_probs, axis=1) return loss_per_row def playing_with_losses(): labels = np.array([ [0, 1,",
"np.argmax(numpy_voxelmap, axis=2) new_depth = new_depth.T new_depth *= int(255 / depth_size) plt.figure(figsize=(10, 6)) plt.axis('off')",
"batch_voxels, batch_depths]) for j in range(batch_size): plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(images_values[j, :, :, :].astype(dtype=np.uint8))",
"np.log(d_min)) # axarr[1, 1].plot((np.log(d) - np.log(d_min)) / q_calc) # plt.show() # with tf.Graph().as_default():",
"shuffle=True) # reader = tf.TextLineReader() # _, serialized_example = reader.read(filename_queue) # filename, depth_filename",
"= (depth / np.max(depth)) * 255.0 else: ra_depth = depth * 255.0 depth_pil",
"= Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_m.png\" % (output_dir, i, j) # depth_discr_pil.save(depth_discr_name)",
"TARGET_WIDTH)) # # depth_discretized = dataset.DataSet.discretize_depth(depth) # # invalid_depth = tf.sign(depth) # #",
"= 160 # DEPTH_DIM = 10 # # filename_queue = tf.train.string_input_producer(['train.csv'], shuffle=True) #",
"[0, 10, 0, 0, 0], # [1, 5, 1, 1, 1], # [0,",
"print('mean\\n', np.mean(arr)) # print('sum_per_row\\n', np.sum(arr, axis=1)) # print('mean_of_sum\\n', np.mean(np.sum(arr, axis=1), axis=0)) # ds",
"= tf.constant(labels, dtype=tf.float32) probs_tf = sess.run(tf.nn.softmax(logits_tf)) loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=labels_tf, logits=logits_tf)) new_loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=tf_labels_to_info_gain(labels,",
"not tf.gfile.Exists(output_dir): tf.gfile.MakeDirs(output_dir) for i, _ in enumerate(images): image, depth, depth_discretized, depth_reconstructed =",
"probs_tf) print('loss', '\\n', loss) print('loss_tf', '\\n', loss_tf) print('loss diff', '\\n', loss - loss_tf)",
"1)).T prob_bin_idx = np.tile(range(logits.shape[last_axis]), (labels.shape[0], 1)) # print('label_idx', '\\n', label_idx) # print('probs_idx', '\\n',",
"input_parser(filename): assert tf.get_default_session() is sess tf.logging.warning(('filename', filename)) channel_data = tf.data.TextLineDataset(filename).map(lambda line: tf.decode_csv(line, [[\"path\"],",
":, :, layer]) # axarr[0, 2].set_title('mask_multiplied_sum_val') # axarr[0, 2].imshow(mask_multiplied_sum_val[0, :, :]) # axarr[1,",
"/ 255.0 # # depth = tf.cast(depth, tf.int64) # # resize # image",
"rgb_image, voxelmap, depth_reconstructed def tf_new_data_api_experiments(): # global sess batch_size = 4 with sess.as_default():",
"# # images_val, depths_val, depths_discretized_val, invalid_depths_val, depth_reconstructed_val, mask_val, mask_multiplied_val, mask_multiplied_sum_val = sess.run( #",
"plt.imshow(images_values[j, :, :, :].astype(dtype=np.uint8)) plt.savefig('inspections/out-{}-rgb.png'.format(j), bbox_inches='tight') plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(depths_values[j, :, :].T, cmap='gray')",
"- loss_tf) print('new_loss', '\\n', new_loss) print('new_loss_tf', '\\n', new_loss_tf) print('new loss diff', '\\n', new_loss",
"%s\" % output_dir) if not tf.gfile.Exists(output_dir): tf.gfile.MakeDirs(output_dir) for i, _ in enumerate(images): image,",
"import matplotlib.pyplot as plt from PIL import Image import Network import dataset from",
"invalid_depth = tf.sign(depth) # # batch_size = 8 # # generate batch #",
"label_idx = tf.tile(label_idx, [labels.shape[last_axis], 1]) label_idx = tf.transpose(label_idx) prob_bin_idx = tf.expand_dims(tf.range(logits.shape[last_axis], dtype=tf.int32), last_axis)",
"* 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth[0]), mode=\"L\") depth_name = \"%s/%03d.png\" % (output_dir, i) depth_pil.save(depth_name)",
"softmax(logits) print('probs', '\\n', probs) logged_probs = np.log(probs) print('logged probs', '\\n', logged_probs) loss_per_row =",
"channel_data def filenames_to_data(rgb_filename, voxelmap_filename): tf.logging.warning(('rgb_filename', rgb_filename)) rgb_image = dataset.DataSet.filename_to_input_image(rgb_filename) voxelmap = tf.py_func(dataset.DataSet.filename_to_target_voxelmap, [voxelmap_filename],",
"informed_cross_entropy_loss(labels=labels, logits=logits) with tf.Graph().as_default(): with tf.Session() as sess: logits_tf = tf.constant(logits, dtype=tf.float32) labels_tf",
"np.mean(arr)) # print('sum_per_row\\n', np.sum(arr, axis=1)) # print('mean_of_sum\\n', np.mean(np.sum(arr, axis=1), axis=0)) # ds =",
"channels=1) # depth = tf.cast(depth, tf.float32) # depth = depth / 255.0 #",
"0], ]) logits = np.array([ [0, 20, 0, 0, 0], [0, 10, 0,",
"1], # [1, 1, 1, 1, 4], # [4, 1, 1, 1, 1],",
"list(range(1, 100)) # d_min = np.min(d) # d_max = 20 # num_bins =",
"/ (num_bins - 1) # # q = 0.5 # width of quantization",
"# depth_reconstructed_val = depth_reconstructed_val[:, :, :, 0] # coord.request_stop() # coord.join(threads) # #",
"depth_pil = Image.fromarray(np.uint8(ra_depth[0]), mode=\"L\") depth_name = \"%s/%03d.png\" % (output_dir, i) depth_pil.save(depth_name) for j",
"diff', '\\n', loss - loss_tf) print('new_loss', '\\n', new_loss) print('new_loss_tf', '\\n', new_loss_tf) print('new loss",
"l = np.round((np.log(d) - np.log(d_min)) / q_calc) # # print(d) # print(l) #",
"with tf.Graph().as_default(): with tf.Session() as sess: logits_tf = tf.constant(logits, dtype=tf.float32) labels_tf = tf.constant(labels,",
"# axarr[1, 2].set_title('depth_reconstructed_val') # axarr[1, 2].imshow(depth_reconstructed_val[0, :, :]) # plt.show() # network =",
"# print('tf_mean\\n', tf_mean) # # print('mean\\n', np.mean(arr)) # print('sum_per_row\\n', np.sum(arr, axis=1)) # print('mean_of_sum\\n',",
"# print('sum_per_row\\n', np.sum(arr, axis=1)) # print('mean_of_sum\\n', np.mean(np.sum(arr, axis=1), axis=0)) # ds = DataSet(8)",
"= tf.data.Dataset.from_tensor_slices(train_imgs) filename_pairs = filename_list.flat_map(input_parser) data_pairs = filename_pairs.map(filenames_to_data) data_pairs = data_pairs.batch(batch_size) # #",
"0, 0, 0], # [1, 5, 1, 1, 1], # [0, 0, 1,",
"= sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=tf_labels_to_info_gain(labels, logits_tf), logits=logits_tf)) # print('labels', '\\n', labels) # print('logits', '\\n', logits) #",
"logits=logits_tf)) # print('labels', '\\n', labels) # print('logits', '\\n', logits) # print('probs', '\\n', probs)",
"print('sum_per_row\\n', np.sum(arr, axis=1)) # print('mean_of_sum\\n', np.mean(np.sum(arr, axis=1), axis=0)) # ds = DataSet(8) #",
"output_dir): print(\"output predict into %s\" % output_dir) if not tf.gfile.Exists(output_dir): tf.gfile.MakeDirs(output_dir) for i,",
"# pure numpy calculation of depth image from voxelmap occupied_ndc_grid = voxels_values[j, :,",
"1].set_title('mask_multiplied_val') # axarr[0, 1].imshow(mask_multiplied_val[0, :, :, layer]) # axarr[1, 0].set_title('depths_val') # axarr[1, 0].imshow(depths_val[0,",
"# axarr[0, 0].plot(probs[0, :]) # axarr[0, 1].set_title('sample 2') # axarr[0, 1].plot(probs[1, :]) #",
"# ds = DataSet(8) # ds.load_params('train.csv') # # d = list(range(1, 100)) #",
"prob_bin_idx)**2 difference = tf.cast(difference, dtype=tf.float32) info_gain = tf.exp(-alpha * difference) return info_gain def",
"(IMAGE_HEIGHT, IMAGE_WIDTH)) # depth = tf.image.resize_images(depth, (TARGET_HEIGHT, TARGET_WIDTH)) # # depth_discretized = dataset.DataSet.discretize_depth(depth)",
"= 'inspections/2018-03-07--17-57-32--527.npy' # numpy_voxelmap = np.fromfile(name, sep=';') numpy_voxelmap = np.load(name) print(numpy_voxelmap.shape) # numpy_voxelmap",
"tf.logging.warning(('filename', filename)) channel_data = tf.data.TextLineDataset(filename).map(lambda line: tf.decode_csv(line, [[\"path\"], [\"annotation\"]])) return channel_data def filenames_to_data(rgb_filename,",
"# [1, 1, 1, 2], # [2, 2, 2, 4], # [4, 4,",
"0].plot(d) # axarr[0, 1].plot(np.log(d)) # axarr[1, 0].plot(np.log(d) - np.log(d_min)) # axarr[1, 1].plot((np.log(d) -",
"bbox_inches='tight') def load_numpy_bin(): # name = 'inspections/2018-03-07--17-57-32--527.bin' name = 'inspections/2018-03-07--17-57-32--527.npy' # numpy_voxelmap =",
"DataSet def output_predict(depths, images, depths_discretized, depths_reconstructed, output_dir): print(\"output predict into %s\" % output_dir)",
"1, 1], # [0, 0, 1, 0, 0], # [1, 1, 4, 1,",
"softmax_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as tf.nn.softmax_cross_entropy_with_logits in tensorflow\"\"\" loss_per_row = - np.sum(labels *",
"% (output_dir, i) depth_pil.save(depth_name) for j in range(dataset.DEPTH_DIM): ra_depth = depth_discretized[:, :, j]",
"tf.Session() as sess: logits_tf = tf.constant(logits, dtype=tf.float32) labels_tf = tf.constant(labels, dtype=tf.float32) probs_tf =",
"2') # axarr[0, 1].plot(probs[1, :]) # axarr[1, 0].set_title('sample 3') # axarr[1, 0].plot(probs[2, :])",
"# axarr[1, 1].set_title('depths_discretized_val') # axarr[1, 1].imshow(depths_discretized_val[0, :, :, layer]) # axarr[0, 2].set_title('mask_multiplied_sum_val') #",
"0], # [0, 0, 1, 0, 0], # [0, 0, 0, 1, 0],",
"now I have just boolean for each value # so I create mask",
"1, 0, 0], [0, 1, 0, 0, 1], [0, 1, 0, 0, 0],",
"# d_max = 20 # num_bins = 10 # q_calc = (np.log(np.max(d)) -",
"= np.array([ [0, 20, 0, 0, 0], [0, 10, 0, 0, 0], [0,",
"# sess.run(images) # # output_predict(depths_val, images_val, depths_discretized_val, # depth_reconstructed_val, 'kunda') # # depth_reconstructed_val",
"= tf.tile(prob_bin_idx, [labels.shape[0], 1]) difference = (label_idx - prob_bin_idx)**2 difference = tf.cast(difference, dtype=tf.float32)",
"depth = depth / 255.0 # # depth = tf.cast(depth, tf.int64) # #",
"= filename_list.flat_map(input_parser) data_pairs = filename_pairs.map(filenames_to_data) data_pairs = data_pairs.batch(batch_size) # # # input #",
"classes] # tf.nn.weighted_cross_entropy_with_logits(labels, logits, weights) losses = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) return losses def prob_to_logit(probs):",
"0})) if __name__ == '__main__': # playing_with_losses() # tf_dataset_experiments() # load_numpy_bin() tf_new_data_api_experiments() #",
"6)) plt.axis('off') plt.imshow(depths_values[j, :, :].T, cmap='gray') plt.savefig('inspections/out-{}-depth.png'.format(j), bbox_inches='tight') # pure numpy calculation of",
"print('labels', '\\n', labels) # print('logits', '\\n', logits) # print('probs', '\\n', probs) # print('probs",
":, :].T, cmap='gray') plt.savefig('inspections/out-{}-depth.png'.format(j), bbox_inches='tight') # pure numpy calculation of depth image from",
"numpy_voxelmap = np.load(name) print(numpy_voxelmap.shape) # numpy_voxelmap = numpy_voxelmap.reshape([240, 160, 100]) numpy_voxelmap = np.flip(numpy_voxelmap,",
"sess = tf.Session(config=tf.ConfigProto(device_count={'GPU': 0})) if __name__ == '__main__': # playing_with_losses() # tf_dataset_experiments() #",
"2, 4], # [4, 4, 4, 8], # ]) # with tf.Graph().as_default(): #",
"for i in range(500): # # if i % 500 == 0: #",
"= \"%s/%03d.png\" % (output_dir, i) depth_pil.save(depth_name) for j in range(dataset.DEPTH_DIM): ra_depth = depth_discretized[:,",
"/ np.max(depth)) * 255.0 else: ra_depth = depth * 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth),",
"(x.shape[1], 1)).T print('e_x', '\\n', e_x) print('sum_per_row', '\\n', sum_per_row) return e_x / sum_per_row def",
"voxels_values[j, :, :, :] occupied_ndc_grid = np.flip(occupied_ndc_grid, axis=2) depth_size = occupied_ndc_grid.shape[2] new_depth =",
"# invalid_depth = tf.sign(depth) # # batch_size = 8 # # generate batch",
"= occupied_ndc_grid.shape[2] new_depth = np.argmax(occupied_ndc_grid, axis=2) new_depth = new_depth.T new_depth *= int(255/depth_size) plt.figure(figsize=(10,",
"= tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) return losses def prob_to_logit(probs): return np.log(probs / (1 - probs))",
"4], # [4, 1, 1, 1, 1], ]) probs = softmax(logits) loss =",
"(num_bins - 1) # # q = 0.5 # width of quantization bin",
"plt.savefig('inspections/2018-03-07--17-57-32--527.png', bbox_inches='tight') sess = tf.Session(config=tf.ConfigProto(device_count={'GPU': 0})) if __name__ == '__main__': # playing_with_losses() #",
"mode=\"L\") depth_name = \"%s/%03d.png\" % (output_dir, i) depth_pil.save(depth_name) for j in range(dataset.DEPTH_DIM): ra_depth",
"mask_lower[:, :, j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_ml.png\" %",
"plt.plot(probs[2, :], color='b') plt.plot(probs[3, :], color='y') plt.show() def input_parser(filename): assert tf.get_default_session() is sess",
"target # depth_png = tf.read_file(depth_filename) # depth = tf.image.decode_png(depth_png, channels=1) # depth =",
"logits): \"\"\"Same behaviour as tf.nn.softmax_cross_entropy_with_logits in tensorflow\"\"\" loss_per_row = - np.sum(labels * np.log(softmax(logits)),",
"# filename_queue = tf.train.string_input_producer(['train.csv'], shuffle=True) # reader = tf.TextLineReader() # _, serialized_example =",
"# [1, 0, 0, 0, 0], ]) logits = np.array([ [0, 20, 0,",
"0, 0], # [0, 1, 0, 0, 0], # [0, 0, 1, 0,",
"image = tf.cast(image, tf.float32) # # target # depth_png = tf.read_file(depth_filename) # depth",
"!= 0: ra_depth = (depth / np.max(depth)) * 255.0 else: ra_depth = depth",
"0, 0], # [3, 1, 1, 1, 1], # [0, 10, 0, 0,",
"= plt.subplots(2, 2) # axarr[0, 0].plot(d) # axarr[0, 1].plot(np.log(d)) # axarr[1, 0].plot(np.log(d) -",
"return e_x / sum_per_row def softmax_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as tf.nn.softmax_cross_entropy_with_logits in tensorflow\"\"\"",
"alpha=0.2): last_axis = len(logits.shape) - 1 label_idx = tf.expand_dims(tf.argmax(labels, axis=last_axis), 0) label_idx =",
"mask[:, :, j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_m.png\" %",
"== 0: # # print('hi', i) # # IMAGE_HEIGHT = 240 # IMAGE_WIDTH",
"* 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_name = \"%s/%03d_reconstructed.png\" % (output_dir, i) depth_pil.save(depth_name)",
"= mask[:, :, j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_m.png\"",
"loss) print('loss_tf', '\\n', loss_tf) print('loss diff', '\\n', loss - loss_tf) print('new_loss', '\\n', new_loss)",
"tf.constant(arr, dtype=tf.float32) # tf_mean = sess.run(tf.reduce_mean(logits_tf)) # print('tf_mean\\n', tf_mean) # # print('mean\\n', np.mean(arr))",
"0, 0, 1], # [1, 0, 0, 0, 0], ]) logits = np.array([",
"coord.join(threads) # # layer = 2 # f, axarr = plt.subplots(2, 3) #",
"matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from PIL import Image import Network import",
"batch # images, depths, depths_discretized, invalid_depths = tf.train.batch( # [image, depth, depth_discretized, invalid_depth],",
"tf_dataset_experiments() # load_numpy_bin() tf_new_data_api_experiments() # arr = np.array([ # [1, 1, 1, 2],",
"# # resize # image = tf.image.resize_images(image, (IMAGE_HEIGHT, IMAGE_WIDTH)) # depth = tf.image.resize_images(depth,",
"return losses def prob_to_logit(probs): return np.log(probs / (1 - probs)) def softmax(x): \"\"\"Same",
"[\"annotation\"]])) return channel_data def filenames_to_data(rgb_filename, voxelmap_filename): tf.logging.warning(('rgb_filename', rgb_filename)) rgb_image = dataset.DataSet.filename_to_input_image(rgb_filename) voxelmap =",
"# resize # image = tf.image.resize_images(image, (IMAGE_HEIGHT, IMAGE_WIDTH)) # depth = tf.image.resize_images(depth, (TARGET_HEIGHT,",
"axis=last_axis), (labels.shape[last_axis], 1)).T prob_bin_idx = np.tile(range(logits.shape[last_axis]), (labels.shape[0], 1)) # print('label_idx', '\\n', label_idx) #",
"tf.int32) voxelmap.set_shape([dataset.TARGET_WIDTH, dataset.TARGET_HEIGHT, dataset.DEPTH_DIM]) # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) return rgb_image,",
"# TARGET_WIDTH = 160 # DEPTH_DIM = 10 # # filename_queue = tf.train.string_input_producer(['train.csv'],",
"0, 0], # [1, 5, 1, 1, 1], # [0, 0, 1, 0,",
"8 # # generate batch # images, depths, depths_discretized, invalid_depths = tf.train.batch( #",
"% (output_dir, i) pilimg.save(image_name) depth = depth.transpose(2, 0, 1) if np.max(depth) != 0:",
"tf.sign(depth) # # batch_size = 8 # # generate batch # images, depths,",
"# for j in range(DEPTH_DIM): # ra_depth = mask[:, :, j] # depth_discr_pil",
"labels_to_info_gain(labels, logits, alpha=0.2): last_axis = len(logits.shape) - 1 label_idx = np.tile(np.argmax(labels, axis=last_axis), (labels.shape[last_axis],",
"value to booleans in higher index depth_size = numpy_voxelmap.shape[2] new_depth = np.argmax(numpy_voxelmap, axis=2)",
"serialized_example = reader.read(filename_queue) # filename, depth_filename = tf.decode_csv(serialized_example, [[\"path\"], [\"annotation\"]]) # # input",
"# plt.show() # with tf.Graph().as_default(): # with tf.Session() as sess: # x =",
"logits=logits) return losses def prob_to_logit(probs): return np.log(probs / (1 - probs)) def softmax(x):",
"print('mean_of_sum\\n', np.mean(np.sum(arr, axis=1), axis=0)) # ds = DataSet(8) # ds.load_params('train.csv') # # d",
"= np.argmax(numpy_voxelmap, axis=2) new_depth = new_depth.T new_depth *= int(255 / depth_size) plt.figure(figsize=(10, 6))",
"coord = tf.train.Coordinator() # threads = tf.train.start_queue_runners(sess=sess, coord=coord) # # images_val, depths_val, depths_discretized_val,",
"axis=2) # now I have just boolean for each value # so I",
"print(numpy_voxelmap.shape) # numpy_voxelmap = numpy_voxelmap.reshape([240, 160, 100]) numpy_voxelmap = np.flip(numpy_voxelmap, axis=2) # now",
"# for i in range(500): # # if i % 500 == 0:",
"j in range(batch_size): plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(images_values[j, :, :, :].astype(dtype=np.uint8)) plt.savefig('inspections/out-{}-rgb.png'.format(j), bbox_inches='tight') plt.figure(figsize=(10,",
"with tf.Session() as sess: logits_tf = tf.constant(logits, dtype=tf.float32) labels_tf = tf.constant(labels, dtype=tf.float32) probs_tf",
"# [images, depths, depths_discretized, invalid_depths, depth_reconstructed, mask, mask_multiplied, mask_multiplied_sum]) # sess.run(images) # #",
"depths_values = sess.run([batch_images, batch_voxels, batch_depths]) for j in range(batch_size): plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(images_values[j,",
"tf.data.TextLineDataset(filename).map(lambda line: tf.decode_csv(line, [[\"path\"], [\"annotation\"]])) return channel_data def filenames_to_data(rgb_filename, voxelmap_filename): tf.logging.warning(('rgb_filename', rgb_filename)) rgb_image",
"(1 - probs)) def softmax(x): \"\"\"Same behaviour as tf.nn.softmax in tensorflow\"\"\" e_x =",
"# with tf.Graph().as_default(): # with tf.Session() as sess: # x = tf.constant(d) #",
"tf.Graph().as_default(): with tf.Session() as sess: logits_tf = tf.constant(logits, dtype=tf.float32) labels_tf = tf.constant(labels, dtype=tf.float32)",
"[0, 1, 0, 0, 0], # [0, 0, 1, 0, 0], # [0,",
"4') # axarr[1, 1].plot(probs[3, :]) plt.plot(probs[0, :], color='r') plt.plot(probs[1, :], color='g') plt.plot(probs[2, :],",
"new_depth = new_depth.T new_depth *= int(255/depth_size) plt.figure(figsize=(10, 7)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/out-{}-depth-np.png'.format(j), bbox_inches='tight')",
"sess.run([batch_images, batch_voxels, batch_depths]) for j in range(batch_size): plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(images_values[j, :, :,",
"def labels_to_info_gain(labels, logits, alpha=0.2): last_axis = len(logits.shape) - 1 label_idx = np.tile(np.argmax(labels, axis=last_axis),",
"= depth_reconstructed_val[:, :, :, 0] # coord.request_stop() # coord.join(threads) # # layer =",
"for v in tf.trainable_variables()]) # print('trainable vars: ', total_vars) # for output bins",
"def playing_with_losses(): labels = np.array([ [0, 1, 0, 0, 0], [0, 1, 0,",
"tf.Session() as sess: # x = tf.constant(d) # # # for i in",
"depth / 255.0 # # depth = tf.cast(depth, tf.int64) # # resize #",
"= softmax_cross_entropy_loss(labels=labels, logits=logits) new_loss = informed_cross_entropy_loss(labels=labels, logits=logits) with tf.Graph().as_default(): with tf.Session() as sess:",
"[1, 1, 1, 4, 1], # [1, 1, 1, 1, 4], # [4,",
"# jpg = tf.read_file(filename) # image = tf.image.decode_jpeg(jpg, channels=3) # image = tf.cast(image,",
"]) probs = softmax(logits) loss = softmax_cross_entropy_loss(labels=labels, logits=logits) new_loss = informed_cross_entropy_loss(labels=labels, logits=logits) with",
"= depth.transpose(2, 0, 1) if np.max(depth) != 0: ra_depth = (depth / np.max(depth))",
"axis=1) return loss_per_row def playing_with_losses(): labels = np.array([ [0, 1, 0, 0, 0],",
"# depth = tf.cast(depth, tf.int64) # # resize # image = tf.image.resize_images(image, (IMAGE_HEIGHT,",
":]) # axarr[1, 2].set_title('depth_reconstructed_val') # axarr[1, 2].imshow(depth_reconstructed_val[0, :, :]) # plt.show() # network",
"# image = tf.image.decode_jpeg(jpg, channels=3) # image = tf.cast(image, tf.float32) # # target",
"0].plot(np.log(d) - np.log(d_min)) # axarr[1, 1].plot((np.log(d) - np.log(d_min)) / q_calc) # plt.show() #",
"depths_reconstructed[i] pilimg = Image.fromarray(np.uint8(image)) image_name = \"%s/%03d_org.png\" % (output_dir, i) pilimg.save(image_name) depth =",
"[4, 4, 4, 8], # ]) # with tf.Graph().as_default(): # with tf.Session() as",
"# [0, 0, 1, 0, 0], # [0, 0, 0, 1, 0], #",
"of quantization bin # l = np.round((np.log(d) - np.log(d_min)) / q_calc) # #",
"- 1 label_idx = np.tile(np.argmax(labels, axis=last_axis), (labels.shape[last_axis], 1)).T prob_bin_idx = np.tile(range(logits.shape[last_axis]), (labels.shape[0], 1))",
"depths, depths_discretized, invalid_depths, depth_reconstructed, mask, mask_multiplied, mask_multiplied_sum]) # sess.run(images) # # output_predict(depths_val, images_val,",
"tf.read_file(depth_filename) # depth = tf.image.decode_png(depth_png, channels=1) # depth = tf.cast(depth, tf.float32) # depth",
"# x = tf.constant(d) # # # for i in range(500): # #",
"1, 0, 0, 0], # [3, 1, 1, 1, 1], # [0, 10,",
"'inspections/2018-03-07--17-57-32--527.npy' # numpy_voxelmap = np.fromfile(name, sep=';') numpy_voxelmap = np.load(name) print(numpy_voxelmap.shape) # numpy_voxelmap =",
"for j in range(batch_size): plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(images_values[j, :, :, :].astype(dtype=np.uint8)) plt.savefig('inspections/out-{}-rgb.png'.format(j), bbox_inches='tight')",
"0].set_title('sample 3') # axarr[1, 0].plot(probs[2, :]) # axarr[1, 1].set_title('sample 4') # axarr[1, 1].plot(probs[3,",
"\"%s/%03d_%03d_discr.png\" % (output_dir, i, j) depth_discr_pil.save(depth_discr_name) # for j in range(DEPTH_DIM): # ra_depth",
"4, 1, 1], # [1, 1, 1, 4, 1], # [1, 1, 1,",
"print('new loss diff', '\\n', new_loss - new_loss_tf) # f, axarr = plt.subplots(2, 3)",
"np.sum(labels_to_info_gain(labels, logits) * logged_probs, axis=1) return loss_per_row def playing_with_losses(): labels = np.array([ [0,",
"0, 0], [0, 1, 0, 0, 1], [0, 1, 0, 0, 0], #",
"tf.image.decode_jpeg(jpg, channels=3) # image = tf.cast(image, tf.float32) # # target # depth_png =",
"= depth_discretized[:, :, j] * 255.0 depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_discr_name = \"%s/%03d_%03d_discr.png\"",
"= - np.sum(labels * np.log(softmax(logits)), axis=1) return loss_per_row def labels_to_info_gain(labels, logits, alpha=0.2): last_axis",
"]) # with tf.Graph().as_default(): # with tf.Session() as sess: # logits_tf = tf.constant(arr,",
"in range(1): images_values, voxels_values, depths_values = sess.run([batch_images, batch_voxels, batch_depths]) for j in range(batch_size):",
"depth_discr_name = \"%s/%03d_%03d_discr_m.png\" % (output_dir, i, j) # depth_discr_pil.save(depth_discr_name) # # for j",
"images_val, depths_val, depths_discretized_val, invalid_depths_val, depth_reconstructed_val, mask_val, mask_multiplied_val, mask_multiplied_sum_val = sess.run( # [images, depths,",
"e_x) print('sum_per_row', '\\n', sum_per_row) return e_x / sum_per_row def softmax_cross_entropy_loss(labels, logits): \"\"\"Same behaviour",
"plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/2018-03-07--17-57-32--527.png', bbox_inches='tight') sess = tf.Session(config=tf.ConfigProto(device_count={'GPU': 0})) if __name__ == '__main__': #",
"bbox_inches='tight') plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(depths_values[j, :, :].T, cmap='gray') plt.savefig('inspections/out-{}-depth.png'.format(j), bbox_inches='tight') # pure numpy",
"# depth_reconstructed, weights, mask, mask_multiplied, mask_multiplied_sum = Network.Network.bins_to_depth(depths_discretized) # # print('weights: ', weights)",
"0) label_idx = tf.cast(label_idx, dtype=tf.int32) label_idx = tf.tile(label_idx, [labels.shape[last_axis], 1]) label_idx = tf.transpose(label_idx)",
"1, 1, 1], # [0, 10, 0, 0, 0], # [1, 5, 1,",
"tf.int64) # # resize # image = tf.image.resize_images(image, (IMAGE_HEIGHT, IMAGE_WIDTH)) # depth =",
"[0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0,",
"print('new_loss_tf', '\\n', new_loss_tf) print('new loss diff', '\\n', new_loss - new_loss_tf) # f, axarr",
"tf.constant(logits, dtype=tf.float32) labels_tf = tf.constant(labels, dtype=tf.float32) probs_tf = sess.run(tf.nn.softmax(logits_tf)) loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=labels_tf, logits=logits_tf))",
"= 0.5 # width of quantization bin # l = np.round((np.log(d) - np.log(d_min))",
"\"%s/%03d_%03d_discr_m.png\" % (output_dir, i, j) # depth_discr_pil.save(depth_discr_name) # # for j in range(DEPTH_DIM):",
"loss_tf) print('loss diff', '\\n', loss - loss_tf) print('new_loss', '\\n', new_loss) print('new_loss_tf', '\\n', new_loss_tf)",
"depth_reconstructed = images[i], depths[i], depths_discretized[i], \\ depths_reconstructed[i] pilimg = Image.fromarray(np.uint8(image)) image_name = \"%s/%03d_org.png\"",
"mode=\"L\") depth_name = \"%s/%03d_reconstructed.png\" % (output_dir, i) depth_pil.save(depth_name) def playground_loss_function(labels, logits): # in",
"tf.logging.warning(('rgb_filename', rgb_filename)) rgb_image = dataset.DataSet.filename_to_input_image(rgb_filename) voxelmap = tf.py_func(dataset.DataSet.filename_to_target_voxelmap, [voxelmap_filename], tf.int32) voxelmap.set_shape([dataset.TARGET_WIDTH, dataset.TARGET_HEIGHT, dataset.DEPTH_DIM])",
"logits, weights) losses = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) return losses def prob_to_logit(probs): return np.log(probs /",
"np.log(probs / (1 - probs)) def softmax(x): \"\"\"Same behaviour as tf.nn.softmax in tensorflow\"\"\"",
"= - np.sum(labels_to_info_gain(labels, logits) * logged_probs, axis=1) return loss_per_row def playing_with_losses(): labels =",
"(labels.shape[0], 1)) # print('label_idx', '\\n', label_idx) # print('probs_idx', '\\n', prob_bin_idx) info_gain = np.exp(-alpha",
":, :]) # axarr[1, 2].set_title('depth_reconstructed_val') # axarr[1, 2].imshow(depth_reconstructed_val[0, :, :]) # plt.show() #",
"axarr[1, 0].plot(np.log(d) - np.log(d_min)) # axarr[1, 1].plot((np.log(d) - np.log(d_min)) / q_calc) # plt.show()",
"- np.log(d_min)) / q_calc) # plt.show() # with tf.Graph().as_default(): # with tf.Session() as",
"0], [1, 1, 1, 0, 0], [0, 1, 0, 0, 1], [0, 1,",
"tf.float32) # # target # depth_png = tf.read_file(depth_filename) # depth = tf.image.decode_png(depth_png, channels=1)",
"tf.image.resize_images(depth, (TARGET_HEIGHT, TARGET_WIDTH)) # # depth_discretized = dataset.DataSet.discretize_depth(depth) # # invalid_depth = tf.sign(depth)",
"# coord.join(threads) # # layer = 2 # f, axarr = plt.subplots(2, 3)",
"new_depth.T new_depth *= int(255/depth_size) plt.figure(figsize=(10, 7)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/out-{}-depth-np.png'.format(j), bbox_inches='tight') def load_numpy_bin():",
"1 label_idx = np.tile(np.argmax(labels, axis=last_axis), (labels.shape[last_axis], 1)).T prob_bin_idx = np.tile(range(logits.shape[last_axis]), (labels.shape[0], 1)) #",
"sess: logits_tf = tf.constant(logits, dtype=tf.float32) labels_tf = tf.constant(labels, dtype=tf.float32) probs_tf = sess.run(tf.nn.softmax(logits_tf)) loss_tf",
"- np.log(d_min)) / q_calc) # # print(d) # print(l) # # print('q_calc', q_calc)",
"# axarr[1, 0].imshow(depths_val[0, :, :, 0]) # axarr[1, 1].set_title('depths_discretized_val') # axarr[1, 1].imshow(depths_discretized_val[0, :,",
"tensorflow\"\"\" e_x = np.exp(x) sum_per_row = np.tile(e_x.sum(axis=1), (x.shape[1], 1)).T print('e_x', '\\n', e_x) print('sum_per_row',",
"# tf_mean = sess.run(tf.reduce_mean(logits_tf)) # print('tf_mean\\n', tf_mean) # # print('mean\\n', np.mean(arr)) # print('sum_per_row\\n',",
"i in range(1): images_values, voxels_values, depths_values = sess.run([batch_images, batch_voxels, batch_depths]) for j in",
"20 # num_bins = 10 # q_calc = (np.log(np.max(d)) - np.log(d_min)) / (num_bins",
"5, 1, 1, 1], # [0, 0, 1, 0, 0], # [1, 1,",
"depth = tf.image.decode_png(depth_png, channels=1) # depth = tf.cast(depth, tf.float32) # depth = depth",
"# now I have just boolean for each value # so I create",
"mask to assign higher value to booleans in higher index depth_size = numpy_voxelmap.shape[2]",
"# ra_depth = mask_lower[:, :, j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name",
"- probs_tf) print('loss', '\\n', loss) print('loss_tf', '\\n', loss_tf) print('loss diff', '\\n', loss -",
"# # generate batch # images, depths, depths_discretized, invalid_depths = tf.train.batch( # [image,",
"axarr[0, 2].imshow(mask_multiplied_sum_val[0, :, :]) # axarr[1, 2].set_title('depth_reconstructed_val') # axarr[1, 2].imshow(depth_reconstructed_val[0, :, :]) #",
"# # target # depth_png = tf.read_file(depth_filename) # depth = tf.image.decode_png(depth_png, channels=1) #",
"axarr[0, 1].plot(np.log(d)) # axarr[1, 0].plot(np.log(d) - np.log(d_min)) # axarr[1, 1].plot((np.log(d) - np.log(d_min)) /",
"in tensorflow\"\"\" loss_per_row = - np.sum(labels * np.log(softmax(logits)), axis=1) return loss_per_row def labels_to_info_gain(labels,",
"depths[i], depths_discretized[i], \\ depths_reconstructed[i] pilimg = Image.fromarray(np.uint8(image)) image_name = \"%s/%03d_org.png\" % (output_dir, i)",
"tf.float32) # depth = depth / 255.0 # # depth = tf.cast(depth, tf.int64)",
"arr = np.array([ # [1, 1, 1, 2], # [2, 2, 2, 4],",
"(output_dir, i) depth_pil.save(depth_name) for j in range(dataset.DEPTH_DIM): ra_depth = depth_discretized[:, :, j] *",
"= tf.train.string_input_producer(['train.csv'], shuffle=True) # reader = tf.TextLineReader() # _, serialized_example = reader.read(filename_queue) #",
"# in rank 2, [elements, classes] # tf.nn.weighted_cross_entropy_with_logits(labels, logits, weights) losses = tf.nn.softmax_cross_entropy_with_logits(labels=labels,",
"axarr[0, 0].plot(probs[0, :]) # axarr[0, 1].set_title('sample 2') # axarr[0, 1].plot(probs[1, :]) # axarr[1,",
"= np.flip(numpy_voxelmap, axis=2) # now I have just boolean for each value #",
"= sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=labels_tf, logits=logits_tf)) new_loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=tf_labels_to_info_gain(labels, logits_tf), logits=logits_tf)) # print('labels', '\\n', labels) #",
"0, 0], ]) logits = np.array([ [0, 20, 0, 0, 0], [0, 10,",
"info_gain) return info_gain def tf_labels_to_info_gain(labels, logits, alpha=0.2): last_axis = len(logits.shape) - 1 label_idx",
"# axarr[1, 0].plot(np.log(d) - np.log(d_min)) # axarr[1, 1].plot((np.log(d) - np.log(d_min)) / q_calc) #",
"into %s\" % output_dir) if not tf.gfile.Exists(output_dir): tf.gfile.MakeDirs(output_dir) for i, _ in enumerate(images):",
"ra_depth = depth * 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth[0]), mode=\"L\") depth_name = \"%s/%03d.png\" %",
"Image.fromarray(np.uint8(image)) image_name = \"%s/%03d_org.png\" % (output_dir, i) pilimg.save(image_name) depth = depth.transpose(2, 0, 1)",
"value # so I create mask to assign higher value to booleans in",
"\"\"\"Same behaviour as tf.nn.weighted_cross_entropy_with_logits in tensorflow\"\"\" probs = softmax(logits) print('probs', '\\n', probs) logged_probs",
"tf.cast(image, tf.float32) # # target # depth_png = tf.read_file(depth_filename) # depth = tf.image.decode_png(depth_png,",
"tf.transpose(label_idx) prob_bin_idx = tf.expand_dims(tf.range(logits.shape[last_axis], dtype=tf.int32), last_axis) prob_bin_idx = tf.transpose(prob_bin_idx) prob_bin_idx = tf.tile(prob_bin_idx, [labels.shape[0],",
"sess: # x = tf.constant(d) # # # for i in range(500): #",
"sess.run( # [images, depths, depths_discretized, invalid_depths, depth_reconstructed, mask, mask_multiplied, mask_multiplied_sum]) # sess.run(images) #",
"# # IMAGE_HEIGHT = 240 # IMAGE_WIDTH = 320 # TARGET_HEIGHT = 120",
"1, 1, 4], # [4, 1, 1, 1, 1], ]) probs = softmax(logits)",
"240 # IMAGE_WIDTH = 320 # TARGET_HEIGHT = 120 # TARGET_WIDTH = 160",
"= \"%s/%03d_reconstructed.png\" % (output_dir, i) depth_pil.save(depth_name) def playground_loss_function(labels, logits): # in rank 2,",
"0], [0, 2, 0, 0, 0], [1, 1, 1, 0, 0], [0, 1,",
"width of quantization bin # l = np.round((np.log(d) - np.log(d_min)) / q_calc) #",
"in enumerate(images): image, depth, depth_discretized, depth_reconstructed = images[i], depths[i], depths_discretized[i], \\ depths_reconstructed[i] pilimg",
"- 1) # # q = 0.5 # width of quantization bin #",
"# print('probs diff', '\\n', probs - probs_tf) print('loss', '\\n', loss) print('loss_tf', '\\n', loss_tf)",
":, j] * 255.0 depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_discr_name = \"%s/%03d_%03d_discr.png\" % (output_dir,",
"160 # DEPTH_DIM = 10 # # filename_queue = tf.train.string_input_producer(['train.csv'], shuffle=True) # reader",
"# [4, 4, 4, 8], # ]) # with tf.Graph().as_default(): # with tf.Session()",
"ra_depth = mask_lower[:, :, j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name =",
"[4, 1, 1, 1, 1], ]) probs = softmax(logits) loss = softmax_cross_entropy_loss(labels=labels, logits=logits)",
"= dataset.DataSet.filename_to_input_image(rgb_filename) voxelmap = tf.py_func(dataset.DataSet.filename_to_target_voxelmap, [voxelmap_filename], tf.int32) voxelmap.set_shape([dataset.TARGET_WIDTH, dataset.TARGET_HEIGHT, dataset.DEPTH_DIM]) # voxelmap =",
"behaviour as tf.nn.softmax_cross_entropy_with_logits in tensorflow\"\"\" loss_per_row = - np.sum(labels * np.log(softmax(logits)), axis=1) return",
"plt.figure(figsize=(10, 7)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/out-{}-depth-np.png'.format(j), bbox_inches='tight') def load_numpy_bin(): # name = 'inspections/2018-03-07--17-57-32--527.bin'",
"axarr[0, 0].set_title('sample 1') # axarr[0, 0].plot(probs[0, :]) # axarr[0, 1].set_title('sample 2') # axarr[0,",
"= np.tile(e_x.sum(axis=1), (x.shape[1], 1)).T print('e_x', '\\n', e_x) print('sum_per_row', '\\n', sum_per_row) return e_x /",
"print('info gain', '\\n', info_gain) return info_gain def tf_labels_to_info_gain(labels, logits, alpha=0.2): last_axis = len(logits.shape)",
"0], # [1, 1, 4, 1, 1], # [1, 1, 1, 4, 1],",
"\"%s/%03d_%03d_discr_ml.png\" % (output_dir, i, j) # depth_discr_pil.save(depth_discr_name) depth = depth_reconstructed[:, :, 0] if",
"10 # # filename_queue = tf.train.string_input_producer(['train.csv'], shuffle=True) # reader = tf.TextLineReader() # _,",
"diff', '\\n', probs - probs_tf) print('loss', '\\n', loss) print('loss_tf', '\\n', loss_tf) print('loss diff',",
"= np.min(d) # d_max = 20 # num_bins = 10 # q_calc =",
"axis=1) return loss_per_row def labels_to_info_gain(labels, logits, alpha=0.2): last_axis = len(logits.shape) - 1 label_idx",
"depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) iterator = data_pairs.make_one_shot_iterator() batch_images, batch_voxels, batch_depths = iterator.get_next() for i",
"# generate batch # images, depths, depths_discretized, invalid_depths = tf.train.batch( # [image, depth,",
"tf_new_data_api_experiments() # arr = np.array([ # [1, 1, 1, 2], # [2, 2,",
"def tf_new_data_api_experiments(): # global sess batch_size = 4 with sess.as_default(): tf.logging.set_verbosity(tf.logging.INFO) # dataset",
"= dataset.DataSet.filename_to_input_image(filename) # # target # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) # depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap)",
"(output_dir, i) pilimg.save(image_name) depth = depth.transpose(2, 0, 1) if np.max(depth) != 0: ra_depth",
"new_depth = np.argmax(occupied_ndc_grid, axis=2) new_depth = new_depth.T new_depth *= int(255/depth_size) plt.figure(figsize=(10, 7)) plt.axis('off')",
"as tf import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt",
"= dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) return rgb_image, voxelmap, depth_reconstructed def tf_new_data_api_experiments(): # global",
"(np.log(np.max(d)) - np.log(d_min)) / (num_bins - 1) # # q = 0.5 #",
"probs) # print('probs diff', '\\n', probs - probs_tf) print('loss', '\\n', loss) print('loss_tf', '\\n',",
"[voxelmap_filename], tf.int32) voxelmap.set_shape([dataset.TARGET_WIDTH, dataset.TARGET_HEIGHT, dataset.DEPTH_DIM]) # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) return",
"0, 0, 0, 1], # [1, 0, 0, 0, 0], ]) logits =",
"numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from PIL import",
"0, 1], # [1, 0, 0, 0, 0], ]) logits = np.array([ [0,",
"in range(500): # # if i % 500 == 0: # # print('hi',",
"# batch_size = 8 # # generate batch # images, depths, depths_discretized, invalid_depths",
"tensorflow as tf import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as",
"num_threads=4, # capacity=40) # # depth_reconstructed, weights, mask, mask_multiplied, mask_multiplied_sum = Network.Network.bins_to_depth(depths_discretized) #",
"= 200: 73 696 786 # for output bins = 100: 65 312",
"depth = tf.image.resize_images(depth, (TARGET_HEIGHT, TARGET_WIDTH)) # # depth_discretized = dataset.DataSet.discretize_depth(depth) # # invalid_depth",
"for i in range(1): images_values, voxels_values, depths_values = sess.run([batch_images, batch_voxels, batch_depths]) for j",
"sum_per_row def softmax_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as tf.nn.softmax_cross_entropy_with_logits in tensorflow\"\"\" loss_per_row = -",
"(output_dir, i, j) depth_discr_pil.save(depth_discr_name) # for j in range(DEPTH_DIM): # ra_depth = mask[:,",
"return info_gain def tf_labels_to_info_gain(labels, logits, alpha=0.2): last_axis = len(logits.shape) - 1 label_idx =",
"1, 0, 0, 1], [0, 1, 0, 0, 0], # [3, 1, 1,",
"= np.round((np.log(d) - np.log(d_min)) / q_calc) # # print(d) # print(l) # #",
"depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_m.png\" % (output_dir, i, j) #",
"[0, 1, 0, 0, 1], [0, 1, 0, 0, 0], # [3, 1,",
"assign higher value to booleans in higher index depth_size = numpy_voxelmap.shape[2] new_depth =",
"np.sum(arr, axis=1)) # print('mean_of_sum\\n', np.mean(np.sum(arr, axis=1), axis=0)) # ds = DataSet(8) # ds.load_params('train.csv')",
":, layer]) # axarr[0, 2].set_title('mask_multiplied_sum_val') # axarr[0, 2].imshow(mask_multiplied_sum_val[0, :, :]) # axarr[1, 2].set_title('depth_reconstructed_val')",
"1, 1], # [0, 10, 0, 0, 0], # [1, 5, 1, 1,",
":, :, layer]) # axarr[0, 1].set_title('mask_multiplied_val') # axarr[0, 1].imshow(mask_multiplied_val[0, :, :, layer]) #",
"# voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) return rgb_image, voxelmap, depth_reconstructed def tf_new_data_api_experiments():",
"tf.gfile.Exists(output_dir): tf.gfile.MakeDirs(output_dir) for i, _ in enumerate(images): image, depth, depth_discretized, depth_reconstructed = images[i],",
"print('probs diff', '\\n', probs - probs_tf) print('loss', '\\n', loss) print('loss_tf', '\\n', loss_tf) print('loss",
"print('logged probs', '\\n', logged_probs) loss_per_row = - np.sum(labels_to_info_gain(labels, logits) * logged_probs, axis=1) return",
"info_gain = np.exp(-alpha * (label_idx - prob_bin_idx)**2) print('info gain', '\\n', info_gain) return info_gain",
"'\\n', new_loss) print('new_loss_tf', '\\n', new_loss_tf) print('new loss diff', '\\n', new_loss - new_loss_tf) #",
"depth_reconstructed_val, mask_val, mask_multiplied_val, mask_multiplied_sum_val = sess.run( # [images, depths, depths_discretized, invalid_depths, depth_reconstructed, mask,",
"= tf.read_file(depth_filename) # depth = tf.image.decode_png(depth_png, channels=1) # depth = tf.cast(depth, tf.float32) #",
"200: 73 696 786 # for output bins = 100: 65 312 586",
"image = tf.image.resize_images(image, (IMAGE_HEIGHT, IMAGE_WIDTH)) # depth = tf.image.resize_images(depth, (TARGET_HEIGHT, TARGET_WIDTH)) # #",
"# images_val, depths_val, depths_discretized_val, invalid_depths_val, depth_reconstructed_val, mask_val, mask_multiplied_val, mask_multiplied_sum_val = sess.run( # [images,",
"depth_discretized = dataset.DataSet.discretize_depth(depth) # # invalid_depth = tf.sign(depth) # # batch_size = 8",
"# # print('mean\\n', np.mean(arr)) # print('sum_per_row\\n', np.sum(arr, axis=1)) # print('mean_of_sum\\n', np.mean(np.sum(arr, axis=1), axis=0))",
"500 == 0: # # print('hi', i) # # IMAGE_HEIGHT = 240 #",
"# axarr[0, 2].imshow(mask_multiplied_sum_val[0, :, :]) # axarr[1, 2].set_title('depth_reconstructed_val') # axarr[1, 2].imshow(depth_reconstructed_val[0, :, :])",
"def softmax_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as tf.nn.softmax_cross_entropy_with_logits in tensorflow\"\"\" loss_per_row = - np.sum(labels",
"logits, alpha=0.2): last_axis = len(logits.shape) - 1 label_idx = np.tile(np.argmax(labels, axis=last_axis), (labels.shape[last_axis], 1)).T",
"# depth = tf.image.decode_png(depth_png, channels=1) # depth = tf.cast(depth, tf.float32) # depth =",
"0, 0, 0], # [0, 1, 0, 0, 0], # [0, 0, 1,",
"10 # q_calc = (np.log(np.max(d)) - np.log(d_min)) / (num_bins - 1) # #",
"10, 0, 0, 0], [0, 2, 0, 0, 0], [1, 1, 1, 0,",
"np.log(softmax(logits)), axis=1) return loss_per_row def labels_to_info_gain(labels, logits, alpha=0.2): last_axis = len(logits.shape) - 1",
"numpy_voxelmap.reshape([240, 160, 100]) numpy_voxelmap = np.flip(numpy_voxelmap, axis=2) # now I have just boolean",
"name = 'inspections/2018-03-07--17-57-32--527.npy' # numpy_voxelmap = np.fromfile(name, sep=';') numpy_voxelmap = np.load(name) print(numpy_voxelmap.shape) #",
"labels = np.array([ [0, 1, 0, 0, 0], [0, 1, 0, 0, 0],",
"255.0 else: ra_depth = depth * 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_name =",
"0, 0], # [0, 0, 1, 0, 0], # [0, 0, 0, 1,",
"/ q_calc) # plt.show() # with tf.Graph().as_default(): # with tf.Session() as sess: #",
"4, 8], # ]) # with tf.Graph().as_default(): # with tf.Session() as sess: #",
"= np.fromfile(name, sep=';') numpy_voxelmap = np.load(name) print(numpy_voxelmap.shape) # numpy_voxelmap = numpy_voxelmap.reshape([240, 160, 100])",
"# playing_with_losses() # tf_dataset_experiments() # load_numpy_bin() tf_new_data_api_experiments() # arr = np.array([ # [1,",
"plt.subplots(2, 3) # axarr[0, 0].set_title('sample 1') # axarr[0, 0].plot(probs[0, :]) # axarr[0, 1].set_title('sample",
"# # depth = tf.cast(depth, tf.int64) # # resize # image = tf.image.resize_images(image,",
"gain', '\\n', info_gain) return info_gain def tf_labels_to_info_gain(labels, logits, alpha=0.2): last_axis = len(logits.shape) -",
"j in range(DEPTH_DIM): # ra_depth = mask[:, :, j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth),",
"in rank 2, [elements, classes] # tf.nn.weighted_cross_entropy_with_logits(labels, logits, weights) losses = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits)",
":]) # axarr[1, 0].set_title('sample 3') # axarr[1, 0].plot(probs[2, :]) # axarr[1, 1].set_title('sample 4')",
"# # # for i in range(500): # # if i % 500",
"numpy_voxelmap = numpy_voxelmap.reshape([240, 160, 100]) numpy_voxelmap = np.flip(numpy_voxelmap, axis=2) # now I have",
"ra_depth = mask[:, :, j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name =",
"= tf.Session(config=tf.ConfigProto(device_count={'GPU': 0})) if __name__ == '__main__': # playing_with_losses() # tf_dataset_experiments() # load_numpy_bin()",
"just boolean for each value # so I create mask to assign higher",
"each value # so I create mask to assign higher value to booleans",
"# q_calc = (np.log(np.max(d)) - np.log(d_min)) / (num_bins - 1) # # q",
"# depth_png = tf.read_file(depth_filename) # depth = tf.image.decode_png(depth_png, channels=1) # depth = tf.cast(depth,",
"in range(DEPTH_DIM): # ra_depth = mask_lower[:, :, j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\")",
"logits=logits) with tf.Graph().as_default(): with tf.Session() as sess: logits_tf = tf.constant(logits, dtype=tf.float32) labels_tf =",
"Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_ml.png\" % (output_dir, i, j) # depth_discr_pil.save(depth_discr_name) depth",
"assert tf.get_default_session() is sess tf.logging.warning(('filename', filename)) channel_data = tf.data.TextLineDataset(filename).map(lambda line: tf.decode_csv(line, [[\"path\"], [\"annotation\"]]))",
"# # print(d) # print(l) # # print('q_calc', q_calc) # # f, axarr",
"(label_idx - prob_bin_idx)**2 difference = tf.cast(difference, dtype=tf.float32) info_gain = tf.exp(-alpha * difference) return",
"0, 0, 0], # [3, 1, 1, 1, 1], # [0, 10, 0,",
"= np.tile(range(logits.shape[last_axis]), (labels.shape[0], 1)) # print('label_idx', '\\n', label_idx) # print('probs_idx', '\\n', prob_bin_idx) info_gain",
"print('probs', '\\n', probs) logged_probs = np.log(probs) print('logged probs', '\\n', logged_probs) loss_per_row = -",
"label_idx = tf.transpose(label_idx) prob_bin_idx = tf.expand_dims(tf.range(logits.shape[last_axis], dtype=tf.int32), last_axis) prob_bin_idx = tf.transpose(prob_bin_idx) prob_bin_idx =",
"bins = 200: 73 696 786 # for output bins = 100: 65",
"# # for j in range(DEPTH_DIM): # ra_depth = mask_lower[:, :, j] #",
"prob_to_logit(probs): return np.log(probs / (1 - probs)) def softmax(x): \"\"\"Same behaviour as tf.nn.softmax",
"def tf_labels_to_info_gain(labels, logits, alpha=0.2): last_axis = len(logits.shape) - 1 label_idx = tf.expand_dims(tf.argmax(labels, axis=last_axis),",
"# axarr[0, 0].set_title('sample 1') # axarr[0, 0].plot(probs[0, :]) # axarr[0, 1].set_title('sample 2') #",
"depth, depth_discretized, invalid_depth], # batch_size=batch_size, # num_threads=4, # capacity=40) # # depth_reconstructed, weights,",
"depth_discr_name = \"%s/%03d_%03d_discr_ml.png\" % (output_dir, i, j) # depth_discr_pil.save(depth_discr_name) depth = depth_reconstructed[:, :,",
"7)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/out-{}-depth-np.png'.format(j), bbox_inches='tight') def load_numpy_bin(): # name = 'inspections/2018-03-07--17-57-32--527.bin' name",
":, 0]) # axarr[1, 1].set_title('depths_discretized_val') # axarr[1, 1].imshow(depths_discretized_val[0, :, :, layer]) # axarr[0,",
"Image.fromarray(np.uint8(ra_depth[0]), mode=\"L\") depth_name = \"%s/%03d.png\" % (output_dir, i) depth_pil.save(depth_name) for j in range(dataset.DEPTH_DIM):",
"plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(depths_values[j, :, :].T, cmap='gray') plt.savefig('inspections/out-{}-depth.png'.format(j), bbox_inches='tight') # pure numpy calculation",
"2].imshow(mask_multiplied_sum_val[0, :, :]) # axarr[1, 2].set_title('depth_reconstructed_val') # axarr[1, 2].imshow(depth_reconstructed_val[0, :, :]) # plt.show()",
"# image = tf.image.resize_images(image, (IMAGE_HEIGHT, IMAGE_WIDTH)) # depth = tf.image.resize_images(depth, (TARGET_HEIGHT, TARGET_WIDTH)) #",
"higher index depth_size = numpy_voxelmap.shape[2] new_depth = np.argmax(numpy_voxelmap, axis=2) new_depth = new_depth.T new_depth",
"loss_tf) print('new_loss', '\\n', new_loss) print('new_loss_tf', '\\n', new_loss_tf) print('new loss diff', '\\n', new_loss -",
"= np.exp(x) sum_per_row = np.tile(e_x.sum(axis=1), (x.shape[1], 1)).T print('e_x', '\\n', e_x) print('sum_per_row', '\\n', sum_per_row)",
"logits_tf = tf.constant(arr, dtype=tf.float32) # tf_mean = sess.run(tf.reduce_mean(logits_tf)) # print('tf_mean\\n', tf_mean) # #",
"= Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_discr_name = \"%s/%03d_%03d_discr.png\" % (output_dir, i, j) depth_discr_pil.save(depth_discr_name) # for",
"prob_bin_idx = np.tile(range(logits.shape[last_axis]), (labels.shape[0], 1)) # print('label_idx', '\\n', label_idx) # print('probs_idx', '\\n', prob_bin_idx)",
"# d = list(range(1, 100)) # d_min = np.min(d) # d_max = 20",
"= plt.subplots(2, 3) # axarr[0, 0].set_title('masks_val') # axarr[0, 0].imshow(mask_val[0, :, :, layer]) #",
"new_loss - new_loss_tf) # f, axarr = plt.subplots(2, 3) # axarr[0, 0].set_title('sample 1')",
"depth_discretized[:, :, j] * 255.0 depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_discr_name = \"%s/%03d_%03d_discr.png\" %",
"invalid_depths = tf.train.batch( # [image, depth, depth_discretized, invalid_depth], # batch_size=batch_size, # num_threads=4, #",
"diff', '\\n', new_loss - new_loss_tf) # f, axarr = plt.subplots(2, 3) # axarr[0,",
"1], # [1, 0, 0, 0, 0], ]) logits = np.array([ [0, 20,",
"last_axis = len(logits.shape) - 1 label_idx = tf.expand_dims(tf.argmax(labels, axis=last_axis), 0) label_idx = tf.cast(label_idx,",
"2, 0, 0, 0], [1, 1, 1, 0, 0], [0, 1, 0, 0,",
"def filenames_to_data(rgb_filename, voxelmap_filename): tf.logging.warning(('rgb_filename', rgb_filename)) rgb_image = dataset.DataSet.filename_to_input_image(rgb_filename) voxelmap = tf.py_func(dataset.DataSet.filename_to_target_voxelmap, [voxelmap_filename], tf.int32)",
"# # d = list(range(1, 100)) # d_min = np.min(d) # d_max =",
"8], # ]) # with tf.Graph().as_default(): # with tf.Session() as sess: # logits_tf",
"# logits_tf = tf.constant(arr, dtype=tf.float32) # tf_mean = sess.run(tf.reduce_mean(logits_tf)) # print('tf_mean\\n', tf_mean) #",
"print('tf_mean\\n', tf_mean) # # print('mean\\n', np.mean(arr)) # print('sum_per_row\\n', np.sum(arr, axis=1)) # print('mean_of_sum\\n', np.mean(np.sum(arr,",
"len(logits.shape) - 1 label_idx = np.tile(np.argmax(labels, axis=last_axis), (labels.shape[last_axis], 1)).T prob_bin_idx = np.tile(range(logits.shape[last_axis]), (labels.shape[0],",
"= filename_pairs.map(filenames_to_data) data_pairs = data_pairs.batch(batch_size) # # # input # image = dataset.DataSet.filename_to_input_image(filename)",
"# # depth_reconstructed_val = depth_reconstructed_val[:, :, :, 0] # coord.request_stop() # coord.join(threads) #",
"= tf.constant(arr, dtype=tf.float32) # tf_mean = sess.run(tf.reduce_mean(logits_tf)) # print('tf_mean\\n', tf_mean) # # print('mean\\n',",
"1, 1, 2], # [2, 2, 2, 4], # [4, 4, 4, 8],",
"# target # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) # depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) iterator = data_pairs.make_one_shot_iterator()",
"- 1 label_idx = tf.expand_dims(tf.argmax(labels, axis=last_axis), 0) label_idx = tf.cast(label_idx, dtype=tf.int32) label_idx =",
"1].plot(np.log(d)) # axarr[1, 0].plot(np.log(d) - np.log(d_min)) # axarr[1, 1].plot((np.log(d) - np.log(d_min)) / q_calc)",
":, j] # depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_m.png\" % (output_dir,",
"/ q_calc) # # print(d) # print(l) # # print('q_calc', q_calc) # #",
"# depth_discr_name = \"%s/%03d_%03d_discr_ml.png\" % (output_dir, i, j) # depth_discr_pil.save(depth_discr_name) depth = depth_reconstructed[:,",
"= tf.transpose(prob_bin_idx) prob_bin_idx = tf.tile(prob_bin_idx, [labels.shape[0], 1]) difference = (label_idx - prob_bin_idx)**2 difference",
"mask, mask_multiplied, mask_multiplied_sum = Network.Network.bins_to_depth(depths_discretized) # # print('weights: ', weights) # # coord",
"0].imshow(depths_val[0, :, :, 0]) # axarr[1, 1].set_title('depths_discretized_val') # axarr[1, 1].imshow(depths_discretized_val[0, :, :, layer])",
"coord.request_stop() # coord.join(threads) # # layer = 2 # f, axarr = plt.subplots(2,",
"total_vars = np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()]) # print('trainable vars: ', total_vars) #",
"sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=labels_tf, logits=logits_tf)) new_loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=tf_labels_to_info_gain(labels, logits_tf), logits=logits_tf)) # print('labels', '\\n', labels) # print('logits',",
"data_pairs.batch(batch_size) # # # input # image = dataset.DataSet.filename_to_input_image(filename) # # target #",
"informed_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as tf.nn.weighted_cross_entropy_with_logits in tensorflow\"\"\" probs = softmax(logits) print('probs', '\\n',",
"= list(range(1, 100)) # d_min = np.min(d) # d_max = 20 # num_bins",
"axarr[1, 0].plot(probs[2, :]) # axarr[1, 1].set_title('sample 4') # axarr[1, 1].plot(probs[3, :]) plt.plot(probs[0, :],",
"# print('hi', i) # # IMAGE_HEIGHT = 240 # IMAGE_WIDTH = 320 #",
"for j in range(dataset.DEPTH_DIM): ra_depth = depth_discretized[:, :, j] * 255.0 depth_discr_pil =",
"# coord = tf.train.Coordinator() # threads = tf.train.start_queue_runners(sess=sess, coord=coord) # # images_val, depths_val,",
"(depth / np.max(depth)) * 255.0 else: ra_depth = depth * 255.0 depth_pil =",
"mask_val, mask_multiplied_val, mask_multiplied_sum_val = sess.run( # [images, depths, depths_discretized, invalid_depths, depth_reconstructed, mask, mask_multiplied,",
"ra_depth = depth_discretized[:, :, j] * 255.0 depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_discr_name =",
"dataset import DataSet def output_predict(depths, images, depths_discretized, depths_reconstructed, output_dir): print(\"output predict into %s\"",
"depth_filename = tf.decode_csv(serialized_example, [[\"path\"], [\"annotation\"]]) # # input # jpg = tf.read_file(filename) #",
"i, j) # depth_discr_pil.save(depth_discr_name) # # for j in range(DEPTH_DIM): # ra_depth =",
"tf.TextLineReader() # _, serialized_example = reader.read(filename_queue) # filename, depth_filename = tf.decode_csv(serialized_example, [[\"path\"], [\"annotation\"]])",
"have just boolean for each value # so I create mask to assign",
"# voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) # depth_reconstructed = dataset.DataSet.tf_voxelmap_to_depth(voxelmap) iterator = data_pairs.make_one_shot_iterator() batch_images, batch_voxels,",
"reader = tf.TextLineReader() # _, serialized_example = reader.read(filename_queue) # filename, depth_filename = tf.decode_csv(serialized_example,",
"0: ra_depth = (depth / np.max(depth)) * 255.0 else: ra_depth = depth *",
"depth_discretized, depth_reconstructed = images[i], depths[i], depths_discretized[i], \\ depths_reconstructed[i] pilimg = Image.fromarray(np.uint8(image)) image_name =",
"= Image.fromarray(np.uint8(ra_depth), mode=\"L\") # depth_discr_name = \"%s/%03d_%03d_discr_ml.png\" % (output_dir, i, j) # depth_discr_pil.save(depth_discr_name)",
"depth_size) plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/2018-03-07--17-57-32--527.png', bbox_inches='tight') sess = tf.Session(config=tf.ConfigProto(device_count={'GPU': 0})) if",
"# input # image = dataset.DataSet.filename_to_input_image(filename) # # target # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename)",
"]) logits = np.array([ [0, 20, 0, 0, 0], [0, 10, 0, 0,",
"plt.axis('off') plt.imshow(images_values[j, :, :, :].astype(dtype=np.uint8)) plt.savefig('inspections/out-{}-rgb.png'.format(j), bbox_inches='tight') plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(depths_values[j, :, :].T,",
"for j in range(DEPTH_DIM): # ra_depth = mask[:, :, j] # depth_discr_pil =",
"# print('mean\\n', np.mean(arr)) # print('sum_per_row\\n', np.sum(arr, axis=1)) # print('mean_of_sum\\n', np.mean(np.sum(arr, axis=1), axis=0)) #",
"'\\n', loss) print('loss_tf', '\\n', loss_tf) print('loss diff', '\\n', loss - loss_tf) print('new_loss', '\\n',",
"depth_reconstructed def tf_new_data_api_experiments(): # global sess batch_size = 4 with sess.as_default(): tf.logging.set_verbosity(tf.logging.INFO) #",
"dataset.DataSet.discretize_depth(depth) # # invalid_depth = tf.sign(depth) # # batch_size = 8 # #",
"depth_reconstructed[:, :, 0] if np.max(depth) != 0: ra_depth = (depth / np.max(depth)) *",
"0]) # axarr[1, 1].set_title('depths_discretized_val') # axarr[1, 1].imshow(depths_discretized_val[0, :, :, layer]) # axarr[0, 2].set_title('mask_multiplied_sum_val')",
"q_calc) # plt.show() # with tf.Graph().as_default(): # with tf.Session() as sess: # x",
"if not tf.gfile.Exists(output_dir): tf.gfile.MakeDirs(output_dir) for i, _ in enumerate(images): image, depth, depth_discretized, depth_reconstructed",
"i in range(500): # # if i % 500 == 0: # #",
"depth_pil.save(depth_name) def playground_loss_function(labels, logits): # in rank 2, [elements, classes] # tf.nn.weighted_cross_entropy_with_logits(labels, logits,",
"[[\"path\"], [\"annotation\"]])) return channel_data def filenames_to_data(rgb_filename, voxelmap_filename): tf.logging.warning(('rgb_filename', rgb_filename)) rgb_image = dataset.DataSet.filename_to_input_image(rgb_filename) voxelmap",
"print('loss', '\\n', loss) print('loss_tf', '\\n', loss_tf) print('loss diff', '\\n', loss - loss_tf) print('new_loss',",
"0] # coord.request_stop() # coord.join(threads) # # layer = 2 # f, axarr",
"= 120 # TARGET_WIDTH = 160 # DEPTH_DIM = 10 # # filename_queue",
"# name = 'inspections/2018-03-07--17-57-32--527.bin' name = 'inspections/2018-03-07--17-57-32--527.npy' # numpy_voxelmap = np.fromfile(name, sep=';') numpy_voxelmap",
"# # batch_size = 8 # # generate batch # images, depths, depths_discretized,",
"return loss_per_row def labels_to_info_gain(labels, logits, alpha=0.2): last_axis = len(logits.shape) - 1 label_idx =",
"as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from PIL import Image",
"0, 1) if np.max(depth) != 0: ra_depth = (depth / np.max(depth)) * 255.0",
"difference) return info_gain def informed_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as tf.nn.weighted_cross_entropy_with_logits in tensorflow\"\"\" probs",
"1, 1], ]) probs = softmax(logits) loss = softmax_cross_entropy_loss(labels=labels, logits=logits) new_loss = informed_cross_entropy_loss(labels=labels,",
"rank 2, [elements, classes] # tf.nn.weighted_cross_entropy_with_logits(labels, logits, weights) losses = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) return",
"# with tf.Session() as sess: # x = tf.constant(d) # # # for",
"4 with sess.as_default(): tf.logging.set_verbosity(tf.logging.INFO) # dataset = tf.data.TFRecordDataset(['train-voxel-gta.csv', 'test-voxel-gta.csv']) train_imgs = tf.constant(['train-voxel-gta.csv']) filename_list",
"axarr[0, 1].imshow(mask_multiplied_val[0, :, :, layer]) # axarr[1, 0].set_title('depths_val') # axarr[1, 0].imshow(depths_val[0, :, :,",
":, :]) # plt.show() # network = Network.Network() # network.prepare() # total_vars =",
"plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/2018-03-07--17-57-32--527.png', bbox_inches='tight') sess = tf.Session(config=tf.ConfigProto(device_count={'GPU': 0})) if __name__",
"input # jpg = tf.read_file(filename) # image = tf.image.decode_jpeg(jpg, channels=3) # image =",
"j in range(dataset.DEPTH_DIM): ra_depth = depth_discretized[:, :, j] * 255.0 depth_discr_pil = Image.fromarray(np.uint8(ra_depth),",
"0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0],",
"axarr[0, 1].set_title('mask_multiplied_val') # axarr[0, 1].imshow(mask_multiplied_val[0, :, :, layer]) # axarr[1, 0].set_title('depths_val') # axarr[1,",
"[0, 1, 0, 0, 0], # [0, 1, 0, 0, 0], # [0,",
"axis=2) new_depth = new_depth.T new_depth *= int(255 / depth_size) plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(new_depth,",
"= Image.fromarray(np.uint8(ra_depth[0]), mode=\"L\") depth_name = \"%s/%03d.png\" % (output_dir, i) depth_pil.save(depth_name) for j in",
"1') # axarr[0, 0].plot(probs[0, :]) # axarr[0, 1].set_title('sample 2') # axarr[0, 1].plot(probs[1, :])",
"= voxels_values[j, :, :, :] occupied_ndc_grid = np.flip(occupied_ndc_grid, axis=2) depth_size = occupied_ndc_grid.shape[2] new_depth",
"layer]) # axarr[0, 1].set_title('mask_multiplied_val') # axarr[0, 1].imshow(mask_multiplied_val[0, :, :, layer]) # axarr[1, 0].set_title('depths_val')",
"tf.Graph().as_default(): # with tf.Session() as sess: # logits_tf = tf.constant(arr, dtype=tf.float32) # tf_mean",
"- np.sum(labels * np.log(softmax(logits)), axis=1) return loss_per_row def labels_to_info_gain(labels, logits, alpha=0.2): last_axis =",
"- prob_bin_idx)**2 difference = tf.cast(difference, dtype=tf.float32) info_gain = tf.exp(-alpha * difference) return info_gain",
"color='b') plt.plot(probs[3, :], color='y') plt.show() def input_parser(filename): assert tf.get_default_session() is sess tf.logging.warning(('filename', filename))",
"0] if np.max(depth) != 0: ra_depth = (depth / np.max(depth)) * 255.0 else:",
"new_loss) print('new_loss_tf', '\\n', new_loss_tf) print('new loss diff', '\\n', new_loss - new_loss_tf) # f,",
"filename, depth_filename = tf.decode_csv(serialized_example, [[\"path\"], [\"annotation\"]]) # # input # jpg = tf.read_file(filename)",
"dtype=tf.float32) info_gain = tf.exp(-alpha * difference) return info_gain def informed_cross_entropy_loss(labels, logits): \"\"\"Same behaviour",
"tf.constant(labels, dtype=tf.float32) probs_tf = sess.run(tf.nn.softmax(logits_tf)) loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=labels_tf, logits=logits_tf)) new_loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=tf_labels_to_info_gain(labels, logits_tf),",
"= tf.sign(depth) # # batch_size = 8 # # generate batch # images,",
"= informed_cross_entropy_loss(labels=labels, logits=logits) with tf.Graph().as_default(): with tf.Session() as sess: logits_tf = tf.constant(logits, dtype=tf.float32)",
"* 255.0 depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_discr_name = \"%s/%03d_%03d_discr.png\" % (output_dir, i, j)",
"# # print('hi', i) # # IMAGE_HEIGHT = 240 # IMAGE_WIDTH = 320",
"1) if np.max(depth) != 0: ra_depth = (depth / np.max(depth)) * 255.0 else:",
"np.tile(range(logits.shape[last_axis]), (labels.shape[0], 1)) # print('label_idx', '\\n', label_idx) # print('probs_idx', '\\n', prob_bin_idx) info_gain =",
"mask, mask_multiplied, mask_multiplied_sum]) # sess.run(images) # # output_predict(depths_val, images_val, depths_discretized_val, # depth_reconstructed_val, 'kunda')",
"is sess tf.logging.warning(('filename', filename)) channel_data = tf.data.TextLineDataset(filename).map(lambda line: tf.decode_csv(line, [[\"path\"], [\"annotation\"]])) return channel_data",
"def softmax(x): \"\"\"Same behaviour as tf.nn.softmax in tensorflow\"\"\" e_x = np.exp(x) sum_per_row =",
"playing_with_losses(): labels = np.array([ [0, 1, 0, 0, 0], [0, 1, 0, 0,",
"plt.plot(probs[1, :], color='g') plt.plot(probs[2, :], color='b') plt.plot(probs[3, :], color='y') plt.show() def input_parser(filename): assert",
"= numpy_voxelmap.reshape([240, 160, 100]) numpy_voxelmap = np.flip(numpy_voxelmap, axis=2) # now I have just",
"layer = 2 # f, axarr = plt.subplots(2, 3) # axarr[0, 0].set_title('masks_val') #",
"jpg = tf.read_file(filename) # image = tf.image.decode_jpeg(jpg, channels=3) # image = tf.cast(image, tf.float32)",
":, :, :].astype(dtype=np.uint8)) plt.savefig('inspections/out-{}-rgb.png'.format(j), bbox_inches='tight') plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(depths_values[j, :, :].T, cmap='gray') plt.savefig('inspections/out-{}-depth.png'.format(j),",
"iterator = data_pairs.make_one_shot_iterator() batch_images, batch_voxels, batch_depths = iterator.get_next() for i in range(1): images_values,",
"- np.log(d_min)) / (num_bins - 1) # # q = 0.5 # width",
"0], # [0, 0, 0, 1, 0], # [0, 0, 0, 0, 1],",
"# for j in range(DEPTH_DIM): # ra_depth = mask_lower[:, :, j] # depth_discr_pil",
"q_calc) # # f, axarr = plt.subplots(2, 2) # axarr[0, 0].plot(d) # axarr[0,",
"# # output_predict(depths_val, images_val, depths_discretized_val, # depth_reconstructed_val, 'kunda') # # depth_reconstructed_val = depth_reconstructed_val[:,",
"plt.plot(probs[3, :], color='y') plt.show() def input_parser(filename): assert tf.get_default_session() is sess tf.logging.warning(('filename', filename)) channel_data",
"depths_discretized, invalid_depths, depth_reconstructed, mask, mask_multiplied, mask_multiplied_sum]) # sess.run(images) # # output_predict(depths_val, images_val, depths_discretized_val,",
"0].set_title('sample 1') # axarr[0, 0].plot(probs[0, :]) # axarr[0, 1].set_title('sample 2') # axarr[0, 1].plot(probs[1,",
"2].set_title('depth_reconstructed_val') # axarr[1, 2].imshow(depth_reconstructed_val[0, :, :]) # plt.show() # network = Network.Network() #",
"# width of quantization bin # l = np.round((np.log(d) - np.log(d_min)) / q_calc)",
":, :, layer]) # axarr[1, 0].set_title('depths_val') # axarr[1, 0].imshow(depths_val[0, :, :, 0]) #",
"difference = tf.cast(difference, dtype=tf.float32) info_gain = tf.exp(-alpha * difference) return info_gain def informed_cross_entropy_loss(labels,",
"line: tf.decode_csv(line, [[\"path\"], [\"annotation\"]])) return channel_data def filenames_to_data(rgb_filename, voxelmap_filename): tf.logging.warning(('rgb_filename', rgb_filename)) rgb_image =",
"i) pilimg.save(image_name) depth = depth.transpose(2, 0, 1) if np.max(depth) != 0: ra_depth =",
"tf.cast(label_idx, dtype=tf.int32) label_idx = tf.tile(label_idx, [labels.shape[last_axis], 1]) label_idx = tf.transpose(label_idx) prob_bin_idx = tf.expand_dims(tf.range(logits.shape[last_axis],",
"else: ra_depth = depth * 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_name = \"%s/%03d_reconstructed.png\"",
"# DEPTH_DIM = 10 # # filename_queue = tf.train.string_input_producer(['train.csv'], shuffle=True) # reader =",
"= tf.image.decode_jpeg(jpg, channels=3) # image = tf.cast(image, tf.float32) # # target # depth_png",
"filename_queue = tf.train.string_input_producer(['train.csv'], shuffle=True) # reader = tf.TextLineReader() # _, serialized_example = reader.read(filename_queue)",
"tf.nn.softmax in tensorflow\"\"\" e_x = np.exp(x) sum_per_row = np.tile(e_x.sum(axis=1), (x.shape[1], 1)).T print('e_x', '\\n',",
"tf.cast(depth, tf.float32) # depth = depth / 255.0 # # depth = tf.cast(depth,",
"coord=coord) # # images_val, depths_val, depths_discretized_val, invalid_depths_val, depth_reconstructed_val, mask_val, mask_multiplied_val, mask_multiplied_sum_val = sess.run(",
"logged_probs, axis=1) return loss_per_row def playing_with_losses(): labels = np.array([ [0, 1, 0, 0,",
"depths_discretized[i], \\ depths_reconstructed[i] pilimg = Image.fromarray(np.uint8(image)) image_name = \"%s/%03d_org.png\" % (output_dir, i) pilimg.save(image_name)",
"1)).T print('e_x', '\\n', e_x) print('sum_per_row', '\\n', sum_per_row) return e_x / sum_per_row def softmax_cross_entropy_loss(labels,",
"with tf.Session() as sess: # x = tf.constant(d) # # # for i",
"plt.show() # with tf.Graph().as_default(): # with tf.Session() as sess: # x = tf.constant(d)",
"= softmax(logits) loss = softmax_cross_entropy_loss(labels=labels, logits=logits) new_loss = informed_cross_entropy_loss(labels=labels, logits=logits) with tf.Graph().as_default(): with",
"# f, axarr = plt.subplots(2, 3) # axarr[0, 0].set_title('masks_val') # axarr[0, 0].imshow(mask_val[0, :,",
"= np.load(name) print(numpy_voxelmap.shape) # numpy_voxelmap = numpy_voxelmap.reshape([240, 160, 100]) numpy_voxelmap = np.flip(numpy_voxelmap, axis=2)",
"cmap='gray') plt.savefig('inspections/2018-03-07--17-57-32--527.png', bbox_inches='tight') sess = tf.Session(config=tf.ConfigProto(device_count={'GPU': 0})) if __name__ == '__main__': # playing_with_losses()",
"depth_discr_pil.save(depth_discr_name) # for j in range(DEPTH_DIM): # ra_depth = mask[:, :, j] #",
"% (output_dir, i) depth_pil.save(depth_name) def playground_loss_function(labels, logits): # in rank 2, [elements, classes]",
"plt.axis('off') plt.imshow(depths_values[j, :, :].T, cmap='gray') plt.savefig('inspections/out-{}-depth.png'.format(j), bbox_inches='tight') # pure numpy calculation of depth",
"axarr[0, 0].set_title('masks_val') # axarr[0, 0].imshow(mask_val[0, :, :, layer]) # axarr[0, 1].set_title('mask_multiplied_val') # axarr[0,",
"filename)) channel_data = tf.data.TextLineDataset(filename).map(lambda line: tf.decode_csv(line, [[\"path\"], [\"annotation\"]])) return channel_data def filenames_to_data(rgb_filename, voxelmap_filename):",
"[[\"path\"], [\"annotation\"]]) # # input # jpg = tf.read_file(filename) # image = tf.image.decode_jpeg(jpg,",
"logits): \"\"\"Same behaviour as tf.nn.weighted_cross_entropy_with_logits in tensorflow\"\"\" probs = softmax(logits) print('probs', '\\n', probs)",
"plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(images_values[j, :, :, :].astype(dtype=np.uint8)) plt.savefig('inspections/out-{}-rgb.png'.format(j), bbox_inches='tight') plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(depths_values[j,",
"depth_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_name = \"%s/%03d_reconstructed.png\" % (output_dir, i) depth_pil.save(depth_name) def playground_loss_function(labels,",
"i, j) depth_discr_pil.save(depth_discr_name) # for j in range(DEPTH_DIM): # ra_depth = mask[:, :,",
"0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], #",
"loss - loss_tf) print('new_loss', '\\n', new_loss) print('new_loss_tf', '\\n', new_loss_tf) print('new loss diff', '\\n',",
"dtype=tf.float32) probs_tf = sess.run(tf.nn.softmax(logits_tf)) loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=labels_tf, logits=logits_tf)) new_loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=tf_labels_to_info_gain(labels, logits_tf), logits=logits_tf))",
"# TARGET_HEIGHT = 120 # TARGET_WIDTH = 160 # DEPTH_DIM = 10 #",
"len(logits.shape) - 1 label_idx = tf.expand_dims(tf.argmax(labels, axis=last_axis), 0) label_idx = tf.cast(label_idx, dtype=tf.int32) label_idx",
"voxels_values, depths_values = sess.run([batch_images, batch_voxels, batch_depths]) for j in range(batch_size): plt.figure(figsize=(10, 6)) plt.axis('off')",
"prob_bin_idx) info_gain = np.exp(-alpha * (label_idx - prob_bin_idx)**2) print('info gain', '\\n', info_gain) return",
"probs)) def softmax(x): \"\"\"Same behaviour as tf.nn.softmax in tensorflow\"\"\" e_x = np.exp(x) sum_per_row",
"# # print('weights: ', weights) # # coord = tf.train.Coordinator() # threads =",
"i) depth_pil.save(depth_name) def playground_loss_function(labels, logits): # in rank 2, [elements, classes] # tf.nn.weighted_cross_entropy_with_logits(labels,",
"# depth_discr_pil.save(depth_discr_name) depth = depth_reconstructed[:, :, 0] if np.max(depth) != 0: ra_depth =",
"(output_dir, i, j) # depth_discr_pil.save(depth_discr_name) # # for j in range(DEPTH_DIM): # ra_depth",
"/ np.max(depth)) * 255.0 else: ra_depth = depth * 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth[0]),",
"# print('label_idx', '\\n', label_idx) # print('probs_idx', '\\n', prob_bin_idx) info_gain = np.exp(-alpha * (label_idx",
"probs) logged_probs = np.log(probs) print('logged probs', '\\n', logged_probs) loss_per_row = - np.sum(labels_to_info_gain(labels, logits)",
"logits) # print('probs', '\\n', probs) # print('probs diff', '\\n', probs - probs_tf) print('loss',",
"new_loss = informed_cross_entropy_loss(labels=labels, logits=logits) with tf.Graph().as_default(): with tf.Session() as sess: logits_tf = tf.constant(logits,",
"import DataSet def output_predict(depths, images, depths_discretized, depths_reconstructed, output_dir): print(\"output predict into %s\" %",
"'\\n', labels) # print('logits', '\\n', logits) # print('probs', '\\n', probs) # print('probs diff',",
"# print(d) # print(l) # # print('q_calc', q_calc) # # f, axarr =",
"network.prepare() # total_vars = np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()]) # print('trainable vars: ',",
"matplotlib.use('Agg') import matplotlib.pyplot as plt from PIL import Image import Network import dataset",
"tf.get_default_session() is sess tf.logging.warning(('filename', filename)) channel_data = tf.data.TextLineDataset(filename).map(lambda line: tf.decode_csv(line, [[\"path\"], [\"annotation\"]])) return",
"= tf.train.batch( # [image, depth, depth_discretized, invalid_depth], # batch_size=batch_size, # num_threads=4, # capacity=40)",
"dtype=tf.float32) # tf_mean = sess.run(tf.reduce_mean(logits_tf)) # print('tf_mean\\n', tf_mean) # # print('mean\\n', np.mean(arr)) #",
"prob_bin_idx = tf.transpose(prob_bin_idx) prob_bin_idx = tf.tile(prob_bin_idx, [labels.shape[0], 1]) difference = (label_idx - prob_bin_idx)**2",
"dataset.DataSet.tf_voxelmap_to_depth(voxelmap) return rgb_image, voxelmap, depth_reconstructed def tf_new_data_api_experiments(): # global sess batch_size = 4",
"IMAGE_WIDTH)) # depth = tf.image.resize_images(depth, (TARGET_HEIGHT, TARGET_WIDTH)) # # depth_discretized = dataset.DataSet.discretize_depth(depth) #",
"= np.log(probs) print('logged probs', '\\n', logged_probs) loss_per_row = - np.sum(labels_to_info_gain(labels, logits) * logged_probs,",
"# [1, 1, 1, 4, 1], # [1, 1, 1, 1, 4], #",
"# [0, 10, 0, 0, 0], # [1, 5, 1, 1, 1], #",
"1].imshow(mask_multiplied_val[0, :, :, layer]) # axarr[1, 0].set_title('depths_val') # axarr[1, 0].imshow(depths_val[0, :, :, 0])",
"= Image.fromarray(np.uint8(image)) image_name = \"%s/%03d_org.png\" % (output_dir, i) pilimg.save(image_name) depth = depth.transpose(2, 0,",
"'\\n', probs) # print('probs diff', '\\n', probs - probs_tf) print('loss', '\\n', loss) print('loss_tf',",
"# load_numpy_bin() tf_new_data_api_experiments() # arr = np.array([ # [1, 1, 1, 2], #",
"batch_images, batch_voxels, batch_depths = iterator.get_next() for i in range(1): images_values, voxels_values, depths_values =",
"q_calc) # # print(d) # print(l) # # print('q_calc', q_calc) # # f,",
"load_numpy_bin(): # name = 'inspections/2018-03-07--17-57-32--527.bin' name = 'inspections/2018-03-07--17-57-32--527.npy' # numpy_voxelmap = np.fromfile(name, sep=';')",
"== '__main__': # playing_with_losses() # tf_dataset_experiments() # load_numpy_bin() tf_new_data_api_experiments() # arr = np.array([",
"import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from PIL import Image import Network",
"pilimg = Image.fromarray(np.uint8(image)) image_name = \"%s/%03d_org.png\" % (output_dir, i) pilimg.save(image_name) depth = depth.transpose(2,",
"return channel_data def filenames_to_data(rgb_filename, voxelmap_filename): tf.logging.warning(('rgb_filename', rgb_filename)) rgb_image = dataset.DataSet.filename_to_input_image(rgb_filename) voxelmap = tf.py_func(dataset.DataSet.filename_to_target_voxelmap,",
"0], # [0, 0, 0, 0, 1], # [1, 0, 0, 0, 0],",
"last_axis) prob_bin_idx = tf.transpose(prob_bin_idx) prob_bin_idx = tf.tile(prob_bin_idx, [labels.shape[0], 1]) difference = (label_idx -",
":, 0] if np.max(depth) != 0: ra_depth = (depth / np.max(depth)) * 255.0",
"from voxelmap occupied_ndc_grid = voxels_values[j, :, :, :] occupied_ndc_grid = np.flip(occupied_ndc_grid, axis=2) depth_size",
"axarr[1, 2].imshow(depth_reconstructed_val[0, :, :]) # plt.show() # network = Network.Network() # network.prepare() #",
"as tf.nn.softmax_cross_entropy_with_logits in tensorflow\"\"\" loss_per_row = - np.sum(labels * np.log(softmax(logits)), axis=1) return loss_per_row",
"[0, 0, 0, 0, 1], # [1, 0, 0, 0, 0], ]) logits",
"= 240 # IMAGE_WIDTH = 320 # TARGET_HEIGHT = 120 # TARGET_WIDTH =",
"layer]) # axarr[1, 0].set_title('depths_val') # axarr[1, 0].imshow(depths_val[0, :, :, 0]) # axarr[1, 1].set_title('depths_discretized_val')",
"# axarr[1, 1].set_title('sample 4') # axarr[1, 1].plot(probs[3, :]) plt.plot(probs[0, :], color='r') plt.plot(probs[1, :],",
"axarr[1, 1].set_title('depths_discretized_val') # axarr[1, 1].imshow(depths_discretized_val[0, :, :, layer]) # axarr[0, 2].set_title('mask_multiplied_sum_val') # axarr[0,",
"_ in enumerate(images): image, depth, depth_discretized, depth_reconstructed = images[i], depths[i], depths_discretized[i], \\ depths_reconstructed[i]",
"predict into %s\" % output_dir) if not tf.gfile.Exists(output_dir): tf.gfile.MakeDirs(output_dir) for i, _ in",
"* difference) return info_gain def informed_cross_entropy_loss(labels, logits): \"\"\"Same behaviour as tf.nn.weighted_cross_entropy_with_logits in tensorflow\"\"\"",
"plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/2018-03-07--17-57-32--527.png', bbox_inches='tight') sess = tf.Session(config=tf.ConfigProto(device_count={'GPU': 0})) if __name__ == '__main__':",
"images, depths, depths_discretized, invalid_depths = tf.train.batch( # [image, depth, depth_discretized, invalid_depth], # batch_size=batch_size,",
"'\\n', label_idx) # print('probs_idx', '\\n', prob_bin_idx) info_gain = np.exp(-alpha * (label_idx - prob_bin_idx)**2)",
"rgb_filename)) rgb_image = dataset.DataSet.filename_to_input_image(rgb_filename) voxelmap = tf.py_func(dataset.DataSet.filename_to_target_voxelmap, [voxelmap_filename], tf.int32) voxelmap.set_shape([dataset.TARGET_WIDTH, dataset.TARGET_HEIGHT, dataset.DEPTH_DIM]) #",
"np.tile(np.argmax(labels, axis=last_axis), (labels.shape[last_axis], 1)).T prob_bin_idx = np.tile(range(logits.shape[last_axis]), (labels.shape[0], 1)) # print('label_idx', '\\n', label_idx)",
"def prob_to_logit(probs): return np.log(probs / (1 - probs)) def softmax(x): \"\"\"Same behaviour as",
"new_depth *= int(255 / depth_size) plt.figure(figsize=(10, 6)) plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/2018-03-07--17-57-32--527.png', bbox_inches='tight') sess",
"label_idx = tf.cast(label_idx, dtype=tf.int32) label_idx = tf.tile(label_idx, [labels.shape[last_axis], 1]) label_idx = tf.transpose(label_idx) prob_bin_idx",
"255.0 # # depth = tf.cast(depth, tf.int64) # # resize # image =",
"bbox_inches='tight') # pure numpy calculation of depth image from voxelmap occupied_ndc_grid = voxels_values[j,",
"= depth_reconstructed[:, :, 0] if np.max(depth) != 0: ra_depth = (depth / np.max(depth))",
"I have just boolean for each value # so I create mask to",
"Image import Network import dataset from Network import BATCH_SIZE from dataset import DataSet",
"prob_bin_idx = tf.expand_dims(tf.range(logits.shape[last_axis], dtype=tf.int32), last_axis) prob_bin_idx = tf.transpose(prob_bin_idx) prob_bin_idx = tf.tile(prob_bin_idx, [labels.shape[0], 1])",
"logits): # in rank 2, [elements, classes] # tf.nn.weighted_cross_entropy_with_logits(labels, logits, weights) losses =",
"# f, axarr = plt.subplots(2, 2) # axarr[0, 0].plot(d) # axarr[0, 1].plot(np.log(d)) #",
"i, _ in enumerate(images): image, depth, depth_discretized, depth_reconstructed = images[i], depths[i], depths_discretized[i], \\",
"255.0 depth_pil = Image.fromarray(np.uint8(ra_depth[0]), mode=\"L\") depth_name = \"%s/%03d.png\" % (output_dir, i) depth_pil.save(depth_name) for",
"plt.subplots(2, 2) # axarr[0, 0].plot(d) # axarr[0, 1].plot(np.log(d)) # axarr[1, 0].plot(np.log(d) - np.log(d_min))",
"= tf.expand_dims(tf.argmax(labels, axis=last_axis), 0) label_idx = tf.cast(label_idx, dtype=tf.int32) label_idx = tf.tile(label_idx, [labels.shape[last_axis], 1])",
"# if i % 500 == 0: # # print('hi', i) # #",
"[labels.shape[0], 1]) difference = (label_idx - prob_bin_idx)**2 difference = tf.cast(difference, dtype=tf.float32) info_gain =",
"j) depth_discr_pil.save(depth_discr_name) # for j in range(DEPTH_DIM): # ra_depth = mask[:, :, j]",
"np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from PIL import Image import",
"depth image from voxelmap occupied_ndc_grid = voxels_values[j, :, :, :] occupied_ndc_grid = np.flip(occupied_ndc_grid,",
"sess.run(tf.nn.softmax(logits_tf)) loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=labels_tf, logits=logits_tf)) new_loss_tf = sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=tf_labels_to_info_gain(labels, logits_tf), logits=logits_tf)) # print('labels', '\\n',",
"1].plot(probs[3, :]) plt.plot(probs[0, :], color='r') plt.plot(probs[1, :], color='g') plt.plot(probs[2, :], color='b') plt.plot(probs[3, :],",
"1], # [1, 1, 1, 4, 1], # [1, 1, 1, 1, 4],",
"# # invalid_depth = tf.sign(depth) # # batch_size = 8 # # generate",
"# [0, 0, 0, 0, 1], # [1, 0, 0, 0, 0], ])",
"to booleans in higher index depth_size = numpy_voxelmap.shape[2] new_depth = np.argmax(numpy_voxelmap, axis=2) new_depth",
"plt.axis('off') plt.imshow(new_depth, cmap='gray') plt.savefig('inspections/out-{}-depth-np.png'.format(j), bbox_inches='tight') def load_numpy_bin(): # name = 'inspections/2018-03-07--17-57-32--527.bin' name =",
"depths_reconstructed, output_dir): print(\"output predict into %s\" % output_dir) if not tf.gfile.Exists(output_dir): tf.gfile.MakeDirs(output_dir) for",
"filename_list = tf.data.Dataset.from_tensor_slices(train_imgs) filename_pairs = filename_list.flat_map(input_parser) data_pairs = filename_pairs.map(filenames_to_data) data_pairs = data_pairs.batch(batch_size) #",
"0, 0, 0], [0, 1, 0, 0, 0], # [0, 1, 0, 0,",
"# f, axarr = plt.subplots(2, 3) # axarr[0, 0].set_title('sample 1') # axarr[0, 0].plot(probs[0,",
"Network.Network() # network.prepare() # total_vars = np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()]) # print('trainable",
"as tf.nn.weighted_cross_entropy_with_logits in tensorflow\"\"\" probs = softmax(logits) print('probs', '\\n', probs) logged_probs = np.log(probs)",
"import dataset from Network import BATCH_SIZE from dataset import DataSet def output_predict(depths, images,",
"global sess batch_size = 4 with sess.as_default(): tf.logging.set_verbosity(tf.logging.INFO) # dataset = tf.data.TFRecordDataset(['train-voxel-gta.csv', 'test-voxel-gta.csv'])",
"0, 0, 0], ]) logits = np.array([ [0, 20, 0, 0, 0], [0,",
"255.0 depth_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_name = \"%s/%03d_reconstructed.png\" % (output_dir, i) depth_pil.save(depth_name) def",
"# depth = tf.cast(depth, tf.float32) # depth = depth / 255.0 # #",
"labels) # print('logits', '\\n', logits) # print('probs', '\\n', probs) # print('probs diff', '\\n',",
"in range(dataset.DEPTH_DIM): ra_depth = depth_discretized[:, :, j] * 255.0 depth_discr_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\")",
"20, 0, 0, 0], [0, 10, 0, 0, 0], [0, 2, 0, 0,",
"# print('labels', '\\n', labels) # print('logits', '\\n', logits) # print('probs', '\\n', probs) #",
"np.exp(-alpha * (label_idx - prob_bin_idx)**2) print('info gain', '\\n', info_gain) return info_gain def tf_labels_to_info_gain(labels,",
"mask_multiplied_sum]) # sess.run(images) # # output_predict(depths_val, images_val, depths_discretized_val, # depth_reconstructed_val, 'kunda') # #",
"(label_idx - prob_bin_idx)**2) print('info gain', '\\n', info_gain) return info_gain def tf_labels_to_info_gain(labels, logits, alpha=0.2):",
"axis=2) depth_size = occupied_ndc_grid.shape[2] new_depth = np.argmax(occupied_ndc_grid, axis=2) new_depth = new_depth.T new_depth *=",
"0, 0], [1, 1, 1, 0, 0], [0, 1, 0, 0, 1], [0,",
"loss_per_row = - np.sum(labels * np.log(softmax(logits)), axis=1) return loss_per_row def labels_to_info_gain(labels, logits, alpha=0.2):",
":].T, cmap='gray') plt.savefig('inspections/out-{}-depth.png'.format(j), bbox_inches='tight') # pure numpy calculation of depth image from voxelmap",
"tf_labels_to_info_gain(labels, logits, alpha=0.2): last_axis = len(logits.shape) - 1 label_idx = tf.expand_dims(tf.argmax(labels, axis=last_axis), 0)",
"for each value # so I create mask to assign higher value to",
"loss = softmax_cross_entropy_loss(labels=labels, logits=logits) new_loss = informed_cross_entropy_loss(labels=labels, logits=logits) with tf.Graph().as_default(): with tf.Session() as",
"1, 1, 1], # [0, 0, 1, 0, 0], # [1, 1, 4,",
"ra_depth = depth * 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth), mode=\"L\") depth_name = \"%s/%03d_reconstructed.png\" %",
"0.5 # width of quantization bin # l = np.round((np.log(d) - np.log(d_min)) /",
"axarr[0, 0].plot(d) # axarr[0, 1].plot(np.log(d)) # axarr[1, 0].plot(np.log(d) - np.log(d_min)) # axarr[1, 1].plot((np.log(d)",
"in higher index depth_size = numpy_voxelmap.shape[2] new_depth = np.argmax(numpy_voxelmap, axis=2) new_depth = new_depth.T",
"255.0 else: ra_depth = depth * 255.0 depth_pil = Image.fromarray(np.uint8(ra_depth[0]), mode=\"L\") depth_name =",
"tf.tile(prob_bin_idx, [labels.shape[0], 1]) difference = (label_idx - prob_bin_idx)**2 difference = tf.cast(difference, dtype=tf.float32) info_gain",
"input # image = dataset.DataSet.filename_to_input_image(filename) # # target # voxelmap = dataset.DataSet.filename_to_target_voxelmap(voxelmap_filename) #",
"* logged_probs, axis=1) return loss_per_row def playing_with_losses(): labels = np.array([ [0, 1, 0,",
"np.array([ # [1, 1, 1, 2], # [2, 2, 2, 4], # [4,",
"new_loss_tf) # f, axarr = plt.subplots(2, 3) # axarr[0, 0].set_title('sample 1') # axarr[0,",
"# IMAGE_WIDTH = 320 # TARGET_HEIGHT = 120 # TARGET_WIDTH = 160 #"
] |
[
"Unless required by applicable law or agreed to in writing, software # distributed",
"own links to a single CacheManager instance # feels hacky; see if there's",
"having resolved through any \"alias\" targets. \"\"\" def __init__(self, cache_manager, target, cache_key): if",
"len(current_group.vts) > 1: # Too big. Close the current group without this vt",
"obtain a copy of the License in the LICENSE file, or at: #",
"'dependencies'): for dep in target.dependencies: for dependency in dep.resolve(): if dependency in versioned_targets_by_target:",
"cache_manager.needs_update(self.cache_key) def update(self): self._cache_manager.update(self) def force_invalidate(self): self._cache_manager.force_invalidate(self) def __repr__(self): return \"VTS(%s. %d)\" %",
"non-flat mode, where we invoke a compiler for each target, which may lead",
"resolved this dependency to the VersionedTargets it # depends on, and use those.",
"+= vt.num_sources def close_current_group(): if len(current_group.vts) > 0: new_vt = VersionedTargetSet.from_versioned_targets(current_group.vts) res.append(new_vt) current_group.vts",
"dependency # graph, looking through targets that don't correspond to VersionedTargets themselves. versioned_target_deps_by_target",
"with that id. We update this as we iterate, # in topological order,",
"on how they # are implemented. class InvalidationCheck(object): @classmethod def _partition_versioned_targets(cls, versioned_targets, partition_size_hint):",
"def _sort_and_validate_targets(self, targets): \"\"\"Validate each target. Returns a topologically ordered set of VersionedTargets,",
"or all operations on either of these, depending on how they # are",
"%s with different\" \" CacheManager instances: %s and %s\" % (first_target, versioned_target, cache_manager,",
"continue. versioned_target_deps.add(versioned_targets_by_target[dependency]) elif dependency in versioned_target_deps_by_target: # Otherwise, see if we've already resolved",
"callers to handle awareness of the CacheManager. for versioned_target in versioned_targets: if versioned_target._cache_manager",
"dependency in versioned_targets_by_target: # If there exists a VersionedTarget corresponding to this Target,",
"VT1 is the combination of [vt1, vt2, vt3], VT2 is the combination of",
"following line is a no-op if cache_key was set in the VersionedTarget __init__",
"targets in a single compiler invocation, and non-flat mode, where we invoke a",
"e.g., [VT1, VT2, VT3, ...] representing the same underlying targets. E.g., VT1 is",
"their own links to a single CacheManager instance # feels hacky; see if",
"for vt in versioned_targets]) self.num_sources = self.cache_key.num_sources self.valid = not cache_manager.needs_update(self.cache_key) def update(self):",
"= [] current_group.total_sources = 0 for vt in versioned_targets: add_to_current_group(vt) if current_group.total_sources >",
"You may obtain a copy of the License in the LICENSE file, or",
"target self.cache_key = cache_key # Must come after the assignments above, as they",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"single compiler invocation, and non-flat mode, where we invoke a compiler for each",
"list of VersionedTargetSet objects in topological order. # Tasks may need to perform",
"of VersionedTargetSet objects, e.g., [VT1, VT2, VT3, ...] representing the same underlying targets.",
"point to the VersionedTargets they depend on. for versioned_target in versioned_targets: versioned_target.dependencies =",
"targets. self.invalid_vts = invalid_vts # Just the invalid targets, partitioned if so requested.",
"dependency in dep.resolve(): if dependency in versioned_targets_by_target: # If there exists a VersionedTarget",
"When checking the artifact cache, this can also be used to represent a",
"that library). if fprint is not None: dependency_keys.add(fprint) else: raise ValueError('Cannot calculate a",
"Otherwise, compute the VersionedTargets that correspond to this dependency's # dependencies, cache and",
"0: new_vt = VersionedTargetSet.from_versioned_targets(current_group.vts) res.append(new_vt) current_group.vts = [] current_group.total_sources = 0 for vt",
"VersionedTarget(self, target, cache_key) # Add the new VersionedTarget to the list of computed",
"last group, if any. return res def __init__(self, all_vts, invalid_vts, partition_size_hint=None): # All",
"immediate deps, because those will already # reflect changes in their own deps.",
"targets, partitioned if so requested. self.invalid_vts_partitioned = self._partition_versioned_targets( invalid_vts, partition_size_hint) if partition_size_hint else",
"self.versioned_targets = versioned_targets self.targets = [vt.target for vt in versioned_targets] # The following",
"been processed in a prior round, and therefore the fprint should # have",
"add_to_current_group(vt) if current_group.total_sources > 1.5 * partition_size_hint and len(current_group.vts) > 1: # Too",
"topological order. The caller can inspect these in order and, e.g., rebuild the",
"update(self): self._cache_manager.update(self) def force_invalidate(self): self._cache_manager.force_invalidate(self) def __repr__(self): return \"VTS(%s. %d)\" % (','.join(target.id for",
"= versioned_target # Having created all applicable VersionedTargets, now we build the VersionedTarget",
"_sort_and_validate_targets(self, targets): \"\"\"Validate each target. Returns a topologically ordered set of VersionedTargets, each",
"created all applicable VersionedTargets, now we build the VersionedTarget dependency # graph, looking",
"above, as they are used in the parent's __init__. VersionedTargetSet.__init__(self, cache_manager, [self]) self.id",
"versioned_targets: if versioned_target._cache_manager != cache_manager: raise ValueError(\"Attempting to combine versioned targets %s and",
"file, or at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"compiler for each target, which may lead to lots of compiler startup overhead.",
"them, and are in topological order. The caller can inspect these in order",
"list of VersionedTargetSet objects, e.g., [VT1, VT2, VT3, ...] representing the same underlying",
"compute the VersionedTargets that correspond to this dependency's # dependencies, cache and use",
"For every dependency of @target, we will store its corresponding VersionedTarget here. For",
"and %s with different\" \" CacheManager instances: %s and %s\" % (first_target, versioned_target,",
"of VersionedTargetSet objects (either valid or invalid). The returned sets 'cover' the input",
"CacheManager(object): \"\"\"Manages cache checks, updates and invalidation keeping track of basic change and",
"targets, valid and invalid. self.all_vts = all_vts # All the targets, partitioned if",
"calling check() on a CacheManager. # Each member is a list of VersionedTargetSet",
"(either valid or invalid). The returned sets 'cover' the input targets, possibly partitioning",
"in vts.versioned_targets: self._invalidator.force_invalidate(vt.cache_key) vt.valid = False self._invalidator.force_invalidate(vts.cache_key) vts.valid = False def check(self, targets,",
"that the wrapped target depends on (after having resolved through any \"alias\" targets.",
"to point to the VersionedTargets they depend on. for versioned_target in versioned_targets: versioned_target.dependencies",
"for use in hooking up VersionedTarget # dependencies below. versioned_targets_by_target[target] = versioned_target #",
"the VersionedTargets it # depends on, and use those. versioned_target_deps.update(versioned_target_deps_by_target[dependency]) else: # Otherwise,",
"and are in topological order. The caller can inspect these in order and,",
"requested. self.invalid_vts_partitioned = self._partition_versioned_targets( invalid_vts, partition_size_hint) if partition_size_hint else invalid_vts class CacheManager(object): \"\"\"Manages",
"at a time. \"\"\" res = [] # Hack around the python outer",
"compromise between flat mode, where we build all targets in a single compiler",
"depends on, and use those. versioned_target_deps.update(versioned_target_deps_by_target[dependency]) else: # Otherwise, compute the VersionedTargets that",
"invalid targets. self.invalid_vts = invalid_vts # Just the invalid targets, partitioned if so",
"the VersionedTargets that correspond to this dependency's # dependencies, cache and use the",
"so. Returns a list of VersionedTargetSet objects (either valid or invalid). The returned",
"twitter.pants.targets import TargetWithSources from twitter.pants.targets.external_dependency import ExternalDependency from twitter.pants.targets.internal import InternalTarget class VersionedTargetSet(object):",
"ImportError: import pickle from twitter.pants import has_sources from twitter.pants.base.build_invalidator import ( BuildInvalidator, CacheKeyGenerator,",
"at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"this case. ordered_targets = self._order_target_list(targets) # This will be a list of VersionedTargets",
"in hooking up VersionedTarget # dependencies below. versioned_targets_by_target[target] = versioned_target # Having created",
"list of targets, a corresponding CacheKey, and a flag determining whether the list",
"try: import cPickle as pickle except ImportError: import pickle from twitter.pants import has_sources",
"VersionedTarget to the list of computed VersionedTargets. versioned_targets.append(versioned_target) # Add to the mapping",
"on a # library target (because the generated code needs that library). if",
"= cache_key.hash # Create a VersionedTarget corresponding to @target. versioned_target = VersionedTarget(self, target,",
"may obtain a copy of the License in the LICENSE file, or at:",
"keeping track of basic change and invalidation statistics. Note that this is distinct",
"that this is distinct from the ArtifactCache concept, and should probably be renamed.",
"the specific language governing permissions and # limitations under the License. # ==================================================================================================",
"VersionedTarget corresponding to this Target, store it and # continue. versioned_target_deps.add(versioned_targets_by_target[dependency]) elif dependency",
"depend on. return versioned_target_deps # Initialize all VersionedTargets to point to the VersionedTargets",
"Version 2.0 (the \"License\"); # you may not use this work except in",
"target to its corresponding VersionedTarget. versioned_targets_by_target = {} # Map from id to",
"to compute later cache keys in this case. ordered_targets = self._order_target_list(targets) # This",
"invalid_vts, partition_size_hint=None): # All the targets, valid and invalid. self.all_vts = all_vts #",
"invalid). The returned sets 'cover' the input targets, possibly partitioning them, and are",
"how they # are implemented. class InvalidationCheck(object): @classmethod def _partition_versioned_targets(cls, versioned_targets, partition_size_hint): \"\"\"Groups",
"there exists a VersionedTarget corresponding to this Target, store it and # continue.",
"# If there exists a VersionedTarget corresponding to this Target, store it and",
"operations on either of these, depending on how they # are implemented. class",
"one input target. \"\"\" # We must check the targets in this order,",
"to most dependent.\"\"\" targets = set(filter(has_sources, targets)) return filter(targets.__contains__, reversed(InternalTarget.sort_targets(targets))) def _key_for(self, target,",
"[vt6]. The new versioned targets are chosen to have roughly partition_size_hint sources. This",
"VersionedTargetSet as successfully processed.\"\"\" for vt in vts.versioned_targets: self._invalidator.update(vt.cache_key) vt.valid = True self._invalidator.update(vts.cache_key)",
"the VersionedTarget dependency # graph, looking through targets that don't correspond to VersionedTargets",
"each of the targets has changed and invalidates it if so. Returns a",
"vt5, vt6, ...]. Returns a list of VersionedTargetSet objects, e.g., [VT1, VT2, VT3,",
"invalidation keeping track of basic change and invalidation statistics. Note that this is",
"correspond to this dependency's # dependencies, cache and use the computed result. versioned_target_deps_by_target[dependency]",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"versioned_targets: versioned_target.dependencies = get_versioned_target_deps_for_target(versioned_target.target) return versioned_targets def needs_update(self, cache_key): return self._invalidator.needs_update(cache_key) def _order_target_list(self,",
"[VT1, VT2, VT3, ...] representing the same underlying targets. E.g., VT1 is the",
"= set() if self._invalidate_dependents and hasattr(target, 'dependencies'): # Note that we only need",
"cache_manager: raise ValueError(\"Attempting to combine versioned targets %s and %s with different\" \"",
"invalidate_dependents, extra_data, only_externaldeps): self._cache_key_generator = cache_key_generator self._invalidate_dependents = invalidate_dependents self._extra_data = pickle.dumps(extra_data) #",
"agreed to in writing, software # distributed under the License is distributed on",
"Close the current group without this vt and add it to the next",
"ArtifactCache concept, and should probably be renamed. \"\"\" def __init__(self, cache_key_generator, build_invalidator_dir, invalidate_dependents,",
"InternalTarget class VersionedTargetSet(object): \"\"\"Represents a list of targets, a corresponding CacheKey, and a",
"target as a singleton. When checking the artifact cache, this can also be",
"if self._invalidate_dependents and hasattr(target, 'dependencies'): # Note that we only need to do",
"# This will be a mapping from each target to its corresponding VersionedTarget.",
"# Add the new VersionedTarget to the list of computed VersionedTargets. versioned_targets.append(versioned_target) #",
"vt.valid = True self._invalidator.update(vts.cache_key) vts.valid = True def force_invalidate(self, vts): \"\"\"Force invalidation of",
"False def check(self, targets, partition_size_hint=None): \"\"\"Checks whether each of the targets has changed",
"VersionedTarget dependencies that this target's VersionedTarget should depend on. return versioned_target_deps # Initialize",
"VersionedTargetSet.__init__(self, cache_manager, [self]) self.id = target.id self.dependencies = set() # The result of",
"we will resolve their actual dependencies and find VersionedTargets for them. versioned_target_deps =",
"versioned_target_deps.update(versioned_target_deps_by_target[dependency]) # Return the VersionedTarget dependencies that this target's VersionedTarget should depend on.",
"%s and %s with different\" \" CacheManager instances: %s and %s\" % (first_target,",
"targets, possibly partitioning them, and are in topological order. The caller can inspect",
"versioned_targets_by_target = {} # Map from id to current fingerprint of the target",
"The returned sets 'cover' the input targets, possibly partitioning them, and are in",
"Add the new VersionedTarget to the list of computed VersionedTargets. versioned_targets.append(versioned_target) # Add",
"self.dependencies = set() # The result of calling check() on a CacheManager. #",
"self.all_vts_partitioned = self._partition_versioned_targets( all_vts, partition_size_hint) if partition_size_hint else all_vts # Just the invalid",
"requested. self.all_vts_partitioned = self._partition_versioned_targets( all_vts, partition_size_hint) if partition_size_hint else all_vts # Just the",
"to in writing, software # distributed under the License is distributed on an",
"codegen target depends on a # library target (because the generated code needs",
"implied. # See the License for the specific language governing permissions and #",
"id_to_hash = {} for target in ordered_targets: dependency_keys = set() if self._invalidate_dependents and",
"group without this vt and add it to the next one. current_group.vts.pop() close_current_group()",
"have already been processed, either in an earlier # round or because they",
"# Otherwise, compute the VersionedTargets that correspond to this dependency's # dependencies, cache",
"True self._invalidator.update(vts.cache_key) vts.valid = True def force_invalidate(self, vts): \"\"\"Force invalidation of a VersionedTargetSet.\"\"\"",
"elif dependency in versioned_target_deps_by_target: # Otherwise, see if we've already resolved this dependency",
"vt.valid = False self._invalidator.force_invalidate(vts.cache_key) vts.valid = False def check(self, targets, partition_size_hint=None): \"\"\"Checks whether",
"reversed(InternalTarget.sort_targets(targets))) def _key_for(self, target, dependency_keys): def fingerprint_extra(sha): sha.update(self._extra_data) for key in sorted(dependency_keys): #",
"\"\"\"Represents a list of targets, a corresponding CacheKey, and a flag determining whether",
"set in the VersionedTarget __init__ method. self.cache_key = CacheKeyGenerator.combine_cache_keys([vt.cache_key for vt in versioned_targets])",
"partition_size_hint): \"\"\"Groups versioned targets so that each group has roughly the same number",
"None here, indicating that the dependency will not be # processed until a",
"a compromise between flat mode, where we build all targets in a single",
"a single artifact. \"\"\" @classmethod def from_versioned_targets(cls, versioned_targets): first_target = versioned_targets[0] cache_manager =",
"ordered_targets. if isinstance(dep, ExternalDependency): dependency_keys.add(dep.cache_key()) elif isinstance(dep, Target): fprint = id_to_hash.get(dep.id, None) if",
"filter(lambda vt: not vt.valid, all_vts) return InvalidationCheck(all_vts, invalid_vts, partition_size_hint) def _sort_and_validate_targets(self, targets): \"\"\"Validate",
"= BuildInvalidator(build_invalidator_dir) def update(self, vts): \"\"\"Mark a changed or invalidated VersionedTargetSet as successfully",
"should # have been written out by the invalidator. fprint = self._invalidator.existing_hash(dep.id) #",
"= all_vts # All the targets, partitioned if so requested. self.all_vts_partitioned = self._partition_versioned_targets(",
"get_versioned_target_deps_for_target( dependency) versioned_target_deps.update(versioned_target_deps_by_target[dependency]) # Return the VersionedTarget dependencies that this target's VersionedTarget should",
"and therefore the fprint should # have been written out by the invalidator.",
"(e.g. pass-through dependency # wrappers), we will resolve their actual dependencies and find",
"@target, we will store its corresponding VersionedTarget here. For # dependencies that don't",
"a single CacheManager instance # feels hacky; see if there's a cleaner way",
"(','.join(target.id for target in self.targets), 1 if self.valid else 0) class VersionedTarget(VersionedTargetSet): \"\"\"This",
"= [] # Hack around the python outer scope problem. class VtGroup(object): def",
"those. versioned_target_deps.update(versioned_target_deps_by_target[dependency]) else: # Otherwise, compute the VersionedTargets that correspond to this dependency's",
"a compiler for each target, which may lead to lots of compiler startup",
"(because the generated code needs that library). if fprint is not None: dependency_keys.add(fprint)",
"work except in compliance with the License. # You may obtain a copy",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"problem. class VtGroup(object): def __init__(self): self.vts = [] self.total_sources = 0 current_group =",
"import ( BuildInvalidator, CacheKeyGenerator, NO_SOURCES, TARGET_SOURCES) from twitter.pants.base.target import Target from twitter.pants.targets import",
"Note that this is distinct from the ArtifactCache concept, and should probably be",
"to the list of computed VersionedTargets. versioned_targets.append(versioned_target) # Add to the mapping from",
"dependent.\"\"\" targets = set(filter(has_sources, targets)) return filter(targets.__contains__, reversed(InternalTarget.sort_targets(targets))) def _key_for(self, target, dependency_keys): def",
"CacheManager. # Each member is a list of VersionedTargetSet objects in topological order.",
"(the \"License\"); # you may not use this work except in compliance with",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"cache_key.hash # Create a VersionedTarget corresponding to @target. versioned_target = VersionedTarget(self, target, cache_key)",
"so requested. self.invalid_vts_partitioned = self._partition_versioned_targets( invalid_vts, partition_size_hint) if partition_size_hint else invalid_vts class CacheManager(object):",
"vt in vts.versioned_targets: self._invalidator.force_invalidate(vt.cache_key) vt.valid = False self._invalidator.force_invalidate(vts.cache_key) vts.valid = False def check(self,",
"objects, e.g., [VT1, VT2, VT3, ...] representing the same underlying targets. E.g., VT1",
"not None: dependency_keys.add(fprint) else: raise ValueError('Cannot calculate a cache_key for a dependency: %s'",
"a single target, this can be used to represent that target as a",
"to the mapping from Targets to VersionedTargets, for use in hooking up VersionedTarget",
"they depend on. for versioned_target in versioned_targets: versioned_target.dependencies = get_versioned_target_deps_for_target(versioned_target.target) return versioned_targets def",
"and has links to VersionedTargets that the wrapped target depends on (after having",
"# Note that we only need to do this for the immediate deps,",
"hacky; see if there's a cleaner way for callers to handle awareness of",
"is a list of VersionedTargetSet objects in topological order. # Tasks may need",
"has roughly the same number of sources. versioned_targets is a list of VersionedTarget",
"each target, which may lead to lots of compiler startup overhead. A task",
"of VersionedTargets, each representing one input target. \"\"\" # We must check the",
"will be a mapping from each target to its corresponding VersionedTarget. versioned_targets_by_target =",
"be a mapping from each target to its corresponding VersionedTarget. versioned_targets_by_target = {}",
"all targets in a single compiler invocation, and non-flat mode, where we invoke",
"= get_versioned_target_deps_for_target(versioned_target.target) return versioned_targets def needs_update(self, cache_key): return self._invalidator.needs_update(cache_key) def _order_target_list(self, targets): \"\"\"Orders",
"there's a cleaner way for callers to handle awareness of the CacheManager. for",
"sources. versioned_targets is a list of VersionedTarget objects [vt1, vt2, vt3, vt4, vt5,",
"all its deps (in # this round). id_to_hash = {} for target in",
"vt.num_sources def close_current_group(): if len(current_group.vts) > 0: new_vt = VersionedTargetSet.from_versioned_targets(current_group.vts) res.append(new_vt) current_group.vts =",
"if so requested. self.all_vts_partitioned = self._partition_versioned_targets( all_vts, partition_size_hint) if partition_size_hint else all_vts #",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"vts): \"\"\"Force invalidation of a VersionedTargetSet.\"\"\" for vt in vts.versioned_targets: self._invalidator.force_invalidate(vt.cache_key) vt.valid =",
"import cPickle as pickle except ImportError: import pickle from twitter.pants import has_sources from",
"Just the invalid targets, partitioned if so requested. self.invalid_vts_partitioned = self._partition_versioned_targets( invalid_vts, partition_size_hint)",
"# You may obtain a copy of the License in the LICENSE file,",
"every dependency of @target, we will store its corresponding VersionedTarget here. For #",
"the way VersionedTargets store their own links to a single CacheManager instance #",
"a topologically ordered set of VersionedTargets, each representing one input target. \"\"\" #",
"from_versioned_targets(cls, versioned_targets): first_target = versioned_targets[0] cache_manager = first_target._cache_manager # Quick sanity check; all",
"combination of [vt1, vt2, vt3], VT2 is the combination of [vt4, vt5] and",
"# Must come after the assignments above, as they are used in the",
"vt2, vt3], VT2 is the combination of [vt4, vt5] and VT3 is [vt6].",
"determining whether the list of targets is currently valid. When invalidating a single",
"cache_key_generator self._invalidate_dependents = invalidate_dependents self._extra_data = pickle.dumps(extra_data) # extra_data may be None. self._sources",
"permissions and # limitations under the License. # ================================================================================================== try: import cPickle as",
"links to a single CacheManager instance # feels hacky; see if there's a",
"has changed and invalidates it if so. Returns a list of VersionedTargetSet objects",
"to ensure hashing in a consistent order. sha.update(key) return self._cache_key_generator.key_for_target( target, sources=self._sources, fingerprint_extra=fingerprint_extra",
"targets. E.g., VT1 is the combination of [vt1, vt2, vt3], VT2 is the",
"target.dependencies: for dependency in dep.resolve(): if dependency in versioned_targets_by_target: # If there exists",
"invalidates it if so. Returns a list of VersionedTargetSet objects (either valid or",
"for key in sorted(dependency_keys): # Sort to ensure hashing in a consistent order.",
"invalid ones. \"\"\" all_vts = self._sort_and_validate_targets(targets) invalid_vts = filter(lambda vt: not vt.valid, all_vts)",
"We must check the targets in this order, to ensure correctness if invalidate_dependents=True,",
"A task can choose instead to build one group at a time. \"\"\"",
"versioned_target_deps # Initialize all VersionedTargets to point to the VersionedTargets they depend on.",
"__init__(self, cache_manager, versioned_targets): self._cache_manager = cache_manager self.versioned_targets = versioned_targets self.targets = [vt.target for",
"the target with that id. We update this as we iterate, # in",
"target. Returns a topologically ordered set of VersionedTargets, each representing one input target.",
"sanity check; all the versioned targets should have the same cache manager. #",
"it and # continue. versioned_target_deps.add(versioned_targets_by_target[dependency]) elif dependency in versioned_target_deps_by_target: # Otherwise, see if",
"%s\" % (first_target, versioned_target, cache_manager, versioned_target._cache_manager)) return cls(cache_manager, versioned_targets) def __init__(self, cache_manager, versioned_targets):",
"represent a list of targets that are built together into a single artifact.",
"mapping from Targets to VersionedTargets, for use in hooking up VersionedTarget # dependencies",
"hasattr(target, 'dependencies'): # Note that we only need to do this for the",
"self.invalid_vts_partitioned = self._partition_versioned_targets( invalid_vts, partition_size_hint) if partition_size_hint else invalid_vts class CacheManager(object): \"\"\"Manages cache",
"= self._sort_and_validate_targets(targets) invalid_vts = filter(lambda vt: not vt.valid, all_vts) return InvalidationCheck(all_vts, invalid_vts, partition_size_hint)",
"dep) cache_key = self._key_for(target, dependency_keys) id_to_hash[target.id] = cache_key.hash # Create a VersionedTarget corresponding",
"% dep) cache_key = self._key_for(target, dependency_keys) id_to_hash[target.id] = cache_key.hash # Create a VersionedTarget",
"the invalid targets. self.invalid_vts = invalid_vts # Just the invalid targets, partitioned if",
"the CacheManager. for versioned_target in versioned_targets: if versioned_target._cache_manager != cache_manager: raise ValueError(\"Attempting to",
"fprint = self._invalidator.existing_hash(dep.id) # Note that fprint may be None here, indicating that",
"if isinstance(dep, ExternalDependency): dependency_keys.add(dep.cache_key()) elif isinstance(dep, Target): fprint = id_to_hash.get(dep.id, None) if fprint",
"the dependency will not be # processed until a later phase. For example,",
"if so. Returns a list of VersionedTargetSet objects (either valid or invalid). The",
"# Just the invalid targets. self.invalid_vts = invalid_vts # Just the invalid targets,",
"self.all_vts = all_vts # All the targets, partitioned if so requested. self.all_vts_partitioned =",
"use the computed result. versioned_target_deps_by_target[dependency] = get_versioned_target_deps_for_target( dependency) versioned_target_deps.update(versioned_target_deps_by_target[dependency]) # Return the VersionedTarget",
"a VersionedTarget (e.g. pass-through dependency # wrappers), we will resolve their actual dependencies",
"id_to_hash[target.id] = cache_key.hash # Create a VersionedTarget corresponding to @target. versioned_target = VersionedTarget(self,",
"We update this as we iterate, # in topological order, so when handling",
"limitations under the License. # ================================================================================================== try: import cPickle as pickle except ImportError:",
"to this Target, store it and # continue. versioned_target_deps.add(versioned_targets_by_target[dependency]) elif dependency in versioned_target_deps_by_target:",
"the License. # ================================================================================================== try: import cPickle as pickle except ImportError: import pickle",
"list of VersionedTarget objects [vt1, vt2, vt3, vt4, vt5, vt6, ...]. Returns a",
"language governing permissions and # limitations under the License. # ================================================================================================== try: import",
"resolved through any \"alias\" targets. \"\"\" def __init__(self, cache_manager, target, cache_key): if not",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"in versioned_target_deps_by_target: # Otherwise, see if we've already resolved this dependency to the",
"cache_key for a dependency: %s' % dep) cache_key = self._key_for(target, dependency_keys) id_to_hash[target.id] =",
"def __init__(self): self.vts = [] self.total_sources = 0 current_group = VtGroup() def add_to_current_group(vt):",
"group has roughly the same number of sources. versioned_targets is a list of",
"self._invalidate_dependents and hasattr(target, 'dependencies'): # Note that we only need to do this",
"= {} for target in ordered_targets: dependency_keys = set() if self._invalidate_dependents and hasattr(target,",
"is useful as a compromise between flat mode, where we build all targets",
"target in self.targets), 1 if self.valid else 0) class VersionedTarget(VersionedTargetSet): \"\"\"This class represents",
"invalidating a single target, this can be used to represent that target as",
"set() # The result of calling check() on a CacheManager. # Each member",
"# reflect changes in their own deps. for dep in target.dependencies: # We",
"updates and invalidation keeping track of basic change and invalidation statistics. Note that",
"the VersionedTargets they depend on. for versioned_target in versioned_targets: versioned_target.dependencies = get_versioned_target_deps_for_target(versioned_target.target) return",
"be # processed until a later phase. For example, if a codegen target",
"target's VersionedTarget should depend on. return versioned_target_deps # Initialize all VersionedTargets to point",
"the VersionedTarget __init__ method. self.cache_key = CacheKeyGenerator.combine_cache_keys([vt.cache_key for vt in versioned_targets]) self.num_sources =",
"each representing one input target. \"\"\" # We must check the targets in",
"BuildInvalidator, CacheKeyGenerator, NO_SOURCES, TARGET_SOURCES) from twitter.pants.base.target import Target from twitter.pants.targets import TargetWithSources from",
"its corresponding VersionedTarget here. For # dependencies that don't correspond to a VersionedTarget",
"targets): \"\"\"Orders the targets topologically, from least to most dependent.\"\"\" targets = set(filter(has_sources,",
"correspond to VersionedTargets themselves. versioned_target_deps_by_target = {} def get_versioned_target_deps_for_target(target): # For every dependency",
"so when handling a target, this will already contain all its deps (in",
"See the License for the specific language governing permissions and # limitations under",
"correspond to @targets. versioned_targets = [] # This will be a mapping from",
"of VersionedTargetSet objects in topological order. # Tasks may need to perform no,",
"# We must check the targets in this order, to ensure correctness if",
"# It may have been processed in a prior round, and therefore the",
"vts.valid = False def check(self, targets, partition_size_hint=None): \"\"\"Checks whether each of the targets",
"with the License. # You may obtain a copy of the License in",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"= self._partition_versioned_targets( all_vts, partition_size_hint) if partition_size_hint else all_vts # Just the invalid targets.",
"not isinstance(target, TargetWithSources): raise ValueError(\"The target %s must support sources and does not.\"",
"is the combination of [vt4, vt5] and VT3 is [vt6]. The new versioned",
"input target. \"\"\" # We must check the targets in this order, to",
"handling a target, this will already contain all its deps (in # this",
"check; all the versioned targets should have the same cache manager. # TODO(ryan):",
"versioned targets %s and %s with different\" \" CacheManager instances: %s and %s\"",
"raise ValueError('Cannot calculate a cache_key for a dependency: %s' % dep) cache_key =",
"# Close the last group, if any. return res def __init__(self, all_vts, invalid_vts,",
"pickle from twitter.pants import has_sources from twitter.pants.base.build_invalidator import ( BuildInvalidator, CacheKeyGenerator, NO_SOURCES, TARGET_SOURCES)",
"return \"VTS(%s. %d)\" % (','.join(target.id for target in self.targets), 1 if self.valid else",
"\"\"\" def __init__(self, cache_manager, target, cache_key): if not isinstance(target, TargetWithSources): raise ValueError(\"The target",
"versioned_target_deps_by_target = {} def get_versioned_target_deps_for_target(target): # For every dependency of @target, we will",
"this round). id_to_hash = {} for target in ordered_targets: dependency_keys = set() if",
"to the VersionedTargets it # depends on, and use those. versioned_target_deps.update(versioned_target_deps_by_target[dependency]) else: #",
"whether the list of targets is currently valid. When invalidating a single target,",
"as successfully processed.\"\"\" for vt in vts.versioned_targets: self._invalidator.update(vt.cache_key) vt.valid = True self._invalidator.update(vts.cache_key) vts.valid",
"e.g., rebuild the invalid ones. \"\"\" all_vts = self._sort_and_validate_targets(targets) invalid_vts = filter(lambda vt:",
"[vt1, vt2, vt3], VT2 is the combination of [vt4, vt5] and VT3 is",
"any deps have already been processed, either in an earlier # round or",
"of VersionedTargets that correspond to @targets. versioned_targets = [] # This will be",
"the mapping from Targets to VersionedTargets, for use in hooking up VersionedTarget #",
"roughly partition_size_hint sources. This is useful as a compromise between flat mode, where",
"lead to lots of compiler startup overhead. A task can choose instead to",
"filter(targets.__contains__, reversed(InternalTarget.sort_targets(targets))) def _key_for(self, target, dependency_keys): def fingerprint_extra(sha): sha.update(self._extra_data) for key in sorted(dependency_keys):",
"cache_key) # Add the new VersionedTarget to the list of computed VersionedTargets. versioned_targets.append(versioned_target)",
"= cache_manager self.versioned_targets = versioned_targets self.targets = [vt.target for vt in versioned_targets] #",
"and should probably be renamed. \"\"\" def __init__(self, cache_key_generator, build_invalidator_dir, invalidate_dependents, extra_data, only_externaldeps):",
"from twitter.pants.targets import TargetWithSources from twitter.pants.targets.external_dependency import ExternalDependency from twitter.pants.targets.internal import InternalTarget class",
"self._invalidator.force_invalidate(vts.cache_key) vts.valid = False def check(self, targets, partition_size_hint=None): \"\"\"Checks whether each of the",
"@targets. versioned_targets = [] # This will be a mapping from each target",
"cache_key # Must come after the assignments above, as they are used in",
"on. for versioned_target in versioned_targets: versioned_target.dependencies = get_versioned_target_deps_for_target(versioned_target.target) return versioned_targets def needs_update(self, cache_key):",
"we use earlier cache keys to compute later cache keys in this case.",
"target depends on a # library target (because the generated code needs that",
"is currently valid. When invalidating a single target, this can be used to",
"we build all targets in a single compiler invocation, and non-flat mode, where",
"fprint should # have been written out by the invalidator. fprint = self._invalidator.existing_hash(dep.id)",
"twitter.pants.base.target import Target from twitter.pants.targets import TargetWithSources from twitter.pants.targets.external_dependency import ExternalDependency from twitter.pants.targets.internal",
"way VersionedTargets store their own links to a single CacheManager instance # feels",
"Too big. Close the current group without this vt and add it to",
"way for callers to handle awareness of the CacheManager. for versioned_target in versioned_targets:",
"if invalidate_dependents=True, # since we use earlier cache keys to compute later cache",
"this dependency's # dependencies, cache and use the computed result. versioned_target_deps_by_target[dependency] = get_versioned_target_deps_for_target(",
"import pickle from twitter.pants import has_sources from twitter.pants.base.build_invalidator import ( BuildInvalidator, CacheKeyGenerator, NO_SOURCES,",
"may not use this work except in compliance with the License. # You",
"target.id self.dependencies = set() # The result of calling check() on a CacheManager.",
"their own deps. for dep in target.dependencies: # We rely on the fact",
"% target.id) self.target = target self.cache_key = cache_key # Must come after the",
"KIND, either express or implied. # See the License for the specific language",
"member is a list of VersionedTargetSet objects in topological order. # Tasks may",
"and %s\" % (first_target, versioned_target, cache_manager, versioned_target._cache_manager)) return cls(cache_manager, versioned_targets) def __init__(self, cache_manager,",
"as a compromise between flat mode, where we build all targets in a",
"= VersionedTargetSet.from_versioned_targets(current_group.vts) res.append(new_vt) current_group.vts = [] current_group.total_sources = 0 for vt in versioned_targets:",
"resolve their actual dependencies and find VersionedTargets for them. versioned_target_deps = set([]) if",
"time. \"\"\" res = [] # Hack around the python outer scope problem.",
"have been processed in a prior round, and therefore the fprint should #",
"Create a VersionedTarget corresponding to @target. versioned_target = VersionedTarget(self, target, cache_key) # Add",
"have been written out by the invalidator. fprint = self._invalidator.existing_hash(dep.id) # Note that",
"CacheManager. for versioned_target in versioned_targets: if versioned_target._cache_manager != cache_manager: raise ValueError(\"Attempting to combine",
"vt in vts.versioned_targets: self._invalidator.update(vt.cache_key) vt.valid = True self._invalidator.update(vts.cache_key) vts.valid = True def force_invalidate(self,",
"wrappers), we will resolve their actual dependencies and find VersionedTargets for them. versioned_target_deps",
"iterate, # in topological order, so when handling a target, this will already",
"check() on a CacheManager. # Each member is a list of VersionedTargetSet objects",
"now we build the VersionedTarget dependency # graph, looking through targets that don't",
"id to current fingerprint of the target with that id. We update this",
"self.id = target.id self.dependencies = set() # The result of calling check() on",
"if there's a cleaner way for callers to handle awareness of the CacheManager.",
"# extra_data may be None. self._sources = NO_SOURCES if only_externaldeps else TARGET_SOURCES self._invalidator",
"from least to most dependent.\"\"\" targets = set(filter(has_sources, targets)) return filter(targets.__contains__, reversed(InternalTarget.sort_targets(targets))) def",
"CacheKeyGenerator, NO_SOURCES, TARGET_SOURCES) from twitter.pants.base.target import Target from twitter.pants.targets import TargetWithSources from twitter.pants.targets.external_dependency",
"ANY KIND, either express or implied. # See the License for the specific",
"VersionedTargets they depend on. for versioned_target in versioned_targets: versioned_target.dependencies = get_versioned_target_deps_for_target(versioned_target.target) return versioned_targets",
"all applicable VersionedTargets, now we build the VersionedTarget dependency # graph, looking through",
"example, if a codegen target depends on a # library target (because the",
"vt and add it to the next one. current_group.vts.pop() close_current_group() add_to_current_group(vt) elif current_group.total_sources",
"Target): fprint = id_to_hash.get(dep.id, None) if fprint is None: # It may have",
"class VersionedTargetSet(object): \"\"\"Represents a list of targets, a corresponding CacheKey, and a flag",
"self._sort_and_validate_targets(targets) invalid_vts = filter(lambda vt: not vt.valid, all_vts) return InvalidationCheck(all_vts, invalid_vts, partition_size_hint) def",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"versioned_targets = [] # This will be a mapping from each target to",
"instance # feels hacky; see if there's a cleaner way for callers to",
"if only_externaldeps else TARGET_SOURCES self._invalidator = BuildInvalidator(build_invalidator_dir) def update(self, vts): \"\"\"Mark a changed",
"TODO(ryan): the way VersionedTargets store their own links to a single CacheManager instance",
"dependency to the VersionedTargets it # depends on, and use those. versioned_target_deps.update(versioned_target_deps_by_target[dependency]) else:",
"in the VersionedTarget __init__ method. self.cache_key = CacheKeyGenerator.combine_cache_keys([vt.cache_key for vt in versioned_targets]) self.num_sources",
"versioned targets are chosen to have roughly partition_size_hint sources. This is useful as",
"(after having resolved through any \"alias\" targets. \"\"\" def __init__(self, cache_manager, target, cache_key):",
"objects in topological order. # Tasks may need to perform no, some or",
"if partition_size_hint else all_vts # Just the invalid targets. self.invalid_vts = invalid_vts #",
"from twitter.pants.base.target import Target from twitter.pants.targets import TargetWithSources from twitter.pants.targets.external_dependency import ExternalDependency from",
"def update(self): self._cache_manager.update(self) def force_invalidate(self): self._cache_manager.force_invalidate(self) def __repr__(self): return \"VTS(%s. %d)\" % (','.join(target.id",
"for versioned_target in versioned_targets: versioned_target.dependencies = get_versioned_target_deps_for_target(versioned_target.target) return versioned_targets def needs_update(self, cache_key): return",
"single CacheManager instance # feels hacky; see if there's a cleaner way for",
"targets topologically, from least to most dependent.\"\"\" targets = set(filter(has_sources, targets)) return filter(targets.__contains__,",
"a singleton. When checking the artifact cache, this can also be used to",
"cPickle as pickle except ImportError: import pickle from twitter.pants import has_sources from twitter.pants.base.build_invalidator",
"id. We update this as we iterate, # in topological order, so when",
"the combination of [vt1, vt2, vt3], VT2 is the combination of [vt4, vt5]",
"sources and does not.\" % target.id) self.target = target self.cache_key = cache_key #",
"> 0: new_vt = VersionedTargetSet.from_versioned_targets(current_group.vts) res.append(new_vt) current_group.vts = [] current_group.total_sources = 0 for",
"def __init__(self, cache_key_generator, build_invalidator_dir, invalidate_dependents, extra_data, only_externaldeps): self._cache_key_generator = cache_key_generator self._invalidate_dependents = invalidate_dependents",
"method. self.cache_key = CacheKeyGenerator.combine_cache_keys([vt.cache_key for vt in versioned_targets]) self.num_sources = self.cache_key.num_sources self.valid =",
"artifact cache, this can also be used to represent a list of targets",
"targets are chosen to have roughly partition_size_hint sources. This is useful as a",
"dep.resolve(): if dependency in versioned_targets_by_target: # If there exists a VersionedTarget corresponding to",
"CacheKey, and a flag determining whether the list of targets is currently valid.",
"add_to_current_group(vt) elif current_group.total_sources > partition_size_hint: close_current_group() close_current_group() # Close the last group, if",
"vt3, vt4, vt5, vt6, ...]. Returns a list of VersionedTargetSet objects, e.g., [VT1,",
"processed in a prior round, and therefore the fprint should # have been",
"instances: %s and %s\" % (first_target, versioned_target, cache_manager, versioned_target._cache_manager)) return cls(cache_manager, versioned_targets) def",
"True def force_invalidate(self, vts): \"\"\"Force invalidation of a VersionedTargetSet.\"\"\" for vt in vts.versioned_targets:",
"The following line is a no-op if cache_key was set in the VersionedTarget",
"most dependent.\"\"\" targets = set(filter(has_sources, targets)) return filter(targets.__contains__, reversed(InternalTarget.sort_targets(targets))) def _key_for(self, target, dependency_keys):",
"earlier # round or because they came first in ordered_targets. if isinstance(dep, ExternalDependency):",
"= True self._invalidator.update(vts.cache_key) vts.valid = True def force_invalidate(self, vts): \"\"\"Force invalidation of a",
"\"\"\"Checks whether each of the targets has changed and invalidates it if so.",
"chosen to have roughly partition_size_hint sources. This is useful as a compromise between",
"and len(current_group.vts) > 1: # Too big. Close the current group without this",
"cache_manager self.versioned_targets = versioned_targets self.targets = [vt.target for vt in versioned_targets] # The",
"None. self._sources = NO_SOURCES if only_externaldeps else TARGET_SOURCES self._invalidator = BuildInvalidator(build_invalidator_dir) def update(self,",
"dep in target.dependencies: # We rely on the fact that any deps have",
"a singleton VersionedTargetSet, and has links to VersionedTargets that the wrapped target depends",
"twitter.pants import has_sources from twitter.pants.base.build_invalidator import ( BuildInvalidator, CacheKeyGenerator, NO_SOURCES, TARGET_SOURCES) from twitter.pants.base.target",
"fingerprint of the target with that id. We update this as we iterate,",
"store it and # continue. versioned_target_deps.add(versioned_targets_by_target[dependency]) elif dependency in versioned_target_deps_by_target: # Otherwise, see",
"cache_key was set in the VersionedTarget __init__ method. self.cache_key = CacheKeyGenerator.combine_cache_keys([vt.cache_key for vt",
"targets has changed and invalidates it if so. Returns a list of VersionedTargetSet",
"if self.valid else 0) class VersionedTarget(VersionedTargetSet): \"\"\"This class represents a singleton VersionedTargetSet, and",
"invalidate_dependents=True, # since we use earlier cache keys to compute later cache keys",
"after the assignments above, as they are used in the parent's __init__. VersionedTargetSet.__init__(self,",
"twitter.pants.base.build_invalidator import ( BuildInvalidator, CacheKeyGenerator, NO_SOURCES, TARGET_SOURCES) from twitter.pants.base.target import Target from twitter.pants.targets",
"VersionedTarget # dependencies below. versioned_targets_by_target[target] = versioned_target # Having created all applicable VersionedTargets,",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"Note that we only need to do this for the immediate deps, because",
"all_vts, invalid_vts, partition_size_hint=None): # All the targets, valid and invalid. self.all_vts = all_vts",
"represent that target as a singleton. When checking the artifact cache, this can",
"else TARGET_SOURCES self._invalidator = BuildInvalidator(build_invalidator_dir) def update(self, vts): \"\"\"Mark a changed or invalidated",
"VersionedTargets to point to the VersionedTargets they depend on. for versioned_target in versioned_targets:",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"target %s must support sources and does not.\" % target.id) self.target = target",
"which may lead to lots of compiler startup overhead. A task can choose",
"It may have been processed in a prior round, and therefore the fprint",
"self.valid = not cache_manager.needs_update(self.cache_key) def update(self): self._cache_manager.update(self) def force_invalidate(self): self._cache_manager.force_invalidate(self) def __repr__(self): return",
"% (first_target, versioned_target, cache_manager, versioned_target._cache_manager)) return cls(cache_manager, versioned_targets) def __init__(self, cache_manager, versioned_targets): self._cache_manager",
"a list of VersionedTargetSet objects, e.g., [VT1, VT2, VT3, ...] representing the same",
"If there exists a VersionedTarget corresponding to this Target, store it and #",
"applicable law or agreed to in writing, software # distributed under the License",
"all_vts # All the targets, partitioned if so requested. self.all_vts_partitioned = self._partition_versioned_targets( all_vts,",
"we only need to do this for the immediate deps, because those will",
"_key_for(self, target, dependency_keys): def fingerprint_extra(sha): sha.update(self._extra_data) for key in sorted(dependency_keys): # Sort to",
"in sorted(dependency_keys): # Sort to ensure hashing in a consistent order. sha.update(key) return",
"= target.id self.dependencies = set() # The result of calling check() on a",
"dependencies below. versioned_targets_by_target[target] = versioned_target # Having created all applicable VersionedTargets, now we",
"cache manager. # TODO(ryan): the way VersionedTargets store their own links to a",
"only_externaldeps else TARGET_SOURCES self._invalidator = BuildInvalidator(build_invalidator_dir) def update(self, vts): \"\"\"Mark a changed or",
"cache_key_generator, build_invalidator_dir, invalidate_dependents, extra_data, only_externaldeps): self._cache_key_generator = cache_key_generator self._invalidate_dependents = invalidate_dependents self._extra_data =",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"dependency_keys.add(dep.cache_key()) elif isinstance(dep, Target): fprint = id_to_hash.get(dep.id, None) if fprint is None: #",
"ExternalDependency): dependency_keys.add(dep.cache_key()) elif isinstance(dep, Target): fprint = id_to_hash.get(dep.id, None) if fprint is None:",
"returned sets 'cover' the input targets, possibly partitioning them, and are in topological",
"and use those. versioned_target_deps.update(versioned_target_deps_by_target[dependency]) else: # Otherwise, compute the VersionedTargets that correspond to",
"they # are implemented. class InvalidationCheck(object): @classmethod def _partition_versioned_targets(cls, versioned_targets, partition_size_hint): \"\"\"Groups versioned",
"update(self, vts): \"\"\"Mark a changed or invalidated VersionedTargetSet as successfully processed.\"\"\" for vt",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"# Just the invalid targets, partitioned if so requested. self.invalid_vts_partitioned = self._partition_versioned_targets( invalid_vts,",
"self.target = target self.cache_key = cache_key # Must come after the assignments above,",
"keys in this case. ordered_targets = self._order_target_list(targets) # This will be a list",
"reflect changes in their own deps. for dep in target.dependencies: # We rely",
"result of calling check() on a CacheManager. # Each member is a list",
"should probably be renamed. \"\"\" def __init__(self, cache_key_generator, build_invalidator_dir, invalidate_dependents, extra_data, only_externaldeps): self._cache_key_generator",
"= filter(lambda vt: not vt.valid, all_vts) return InvalidationCheck(all_vts, invalid_vts, partition_size_hint) def _sort_and_validate_targets(self, targets):",
"compliance with the License. # You may obtain a copy of the License",
"a prior round, and therefore the fprint should # have been written out",
"order. # Tasks may need to perform no, some or all operations on",
"in topological order. The caller can inspect these in order and, e.g., rebuild",
"that each group has roughly the same number of sources. versioned_targets is a",
"vts.versioned_targets: self._invalidator.force_invalidate(vt.cache_key) vt.valid = False self._invalidator.force_invalidate(vts.cache_key) vts.valid = False def check(self, targets, partition_size_hint=None):",
"these in order and, e.g., rebuild the invalid ones. \"\"\" all_vts = self._sort_and_validate_targets(targets)",
"next one. current_group.vts.pop() close_current_group() add_to_current_group(vt) elif current_group.total_sources > partition_size_hint: close_current_group() close_current_group() # Close",
"= [vt.target for vt in versioned_targets] # The following line is a no-op",
"fprint is None: # It may have been processed in a prior round,",
"VersionedTarget dependency # graph, looking through targets that don't correspond to VersionedTargets themselves.",
"correctness if invalidate_dependents=True, # since we use earlier cache keys to compute later",
"them. versioned_target_deps = set([]) if hasattr(target, 'dependencies'): for dep in target.dependencies: for dependency",
"that correspond to @targets. versioned_targets = [] # This will be a mapping",
"targets. \"\"\" def __init__(self, cache_manager, target, cache_key): if not isinstance(target, TargetWithSources): raise ValueError(\"The",
"case. ordered_targets = self._order_target_list(targets) # This will be a list of VersionedTargets that",
"# Quick sanity check; all the versioned targets should have the same cache",
"VersionedTargetSet objects in topological order. # Tasks may need to perform no, some",
"Just the invalid targets. self.invalid_vts = invalid_vts # Just the invalid targets, partitioned",
"corresponding to this Target, store it and # continue. versioned_target_deps.add(versioned_targets_by_target[dependency]) elif dependency in",
"that we only need to do this for the immediate deps, because those",
"# limitations under the License. # ================================================================================================== try: import cPickle as pickle except",
"* partition_size_hint and len(current_group.vts) > 1: # Too big. Close the current group",
"roughly the same number of sources. versioned_targets is a list of VersionedTarget objects",
"in versioned_targets: add_to_current_group(vt) if current_group.total_sources > 1.5 * partition_size_hint and len(current_group.vts) > 1:",
"if dependency in versioned_targets_by_target: # If there exists a VersionedTarget corresponding to this",
"cache_manager, versioned_target._cache_manager)) return cls(cache_manager, versioned_targets) def __init__(self, cache_manager, versioned_targets): self._cache_manager = cache_manager self.versioned_targets",
"\"\"\" def __init__(self, cache_key_generator, build_invalidator_dir, invalidate_dependents, extra_data, only_externaldeps): self._cache_key_generator = cache_key_generator self._invalidate_dependents =",
"through targets that don't correspond to VersionedTargets themselves. versioned_target_deps_by_target = {} def get_versioned_target_deps_for_target(target):",
"import InternalTarget class VersionedTargetSet(object): \"\"\"Represents a list of targets, a corresponding CacheKey, and",
"self._cache_manager.force_invalidate(self) def __repr__(self): return \"VTS(%s. %d)\" % (','.join(target.id for target in self.targets), 1",
"self.vts = [] self.total_sources = 0 current_group = VtGroup() def add_to_current_group(vt): current_group.vts.append(vt) current_group.total_sources",
"current_group.vts.append(vt) current_group.total_sources += vt.num_sources def close_current_group(): if len(current_group.vts) > 0: new_vt = VersionedTargetSet.from_versioned_targets(current_group.vts)",
"self.cache_key = CacheKeyGenerator.combine_cache_keys([vt.cache_key for vt in versioned_targets]) self.num_sources = self.cache_key.num_sources self.valid = not",
"else: # Otherwise, compute the VersionedTargets that correspond to this dependency's # dependencies,",
"the input targets, possibly partitioning them, and are in topological order. The caller",
"in versioned_targets] # The following line is a no-op if cache_key was set",
"build one group at a time. \"\"\" res = [] # Hack around",
"will already contain all its deps (in # this round). id_to_hash = {}",
"# Unless required by applicable law or agreed to in writing, software #",
"invalid targets, partitioned if so requested. self.invalid_vts_partitioned = self._partition_versioned_targets( invalid_vts, partition_size_hint) if partition_size_hint",
"by applicable law or agreed to in writing, software # distributed under the",
"the list of computed VersionedTargets. versioned_targets.append(versioned_target) # Add to the mapping from Targets",
"of targets, a corresponding CacheKey, and a flag determining whether the list of",
"CacheKeyGenerator.combine_cache_keys([vt.cache_key for vt in versioned_targets]) self.num_sources = self.cache_key.num_sources self.valid = not cache_manager.needs_update(self.cache_key) def",
"the targets, partitioned if so requested. self.all_vts_partitioned = self._partition_versioned_targets( all_vts, partition_size_hint) if partition_size_hint",
"@classmethod def _partition_versioned_targets(cls, versioned_targets, partition_size_hint): \"\"\"Groups versioned targets so that each group has",
"= False def check(self, targets, partition_size_hint=None): \"\"\"Checks whether each of the targets has",
"# Too big. Close the current group without this vt and add it",
"don't correspond to a VersionedTarget (e.g. pass-through dependency # wrappers), we will resolve",
"partition_size_hint) if partition_size_hint else invalid_vts class CacheManager(object): \"\"\"Manages cache checks, updates and invalidation",
"2.0 (the \"License\"); # you may not use this work except in compliance",
"of the License in the LICENSE file, or at: # # http://www.apache.org/licenses/LICENSE-2.0 #",
"elif current_group.total_sources > partition_size_hint: close_current_group() close_current_group() # Close the last group, if any.",
"sha.update(self._extra_data) for key in sorted(dependency_keys): # Sort to ensure hashing in a consistent",
"for callers to handle awareness of the CacheManager. for versioned_target in versioned_targets: if",
"[] current_group.total_sources = 0 for vt in versioned_targets: add_to_current_group(vt) if current_group.total_sources > 1.5",
"dependency_keys): def fingerprint_extra(sha): sha.update(self._extra_data) for key in sorted(dependency_keys): # Sort to ensure hashing",
"calculate a cache_key for a dependency: %s' % dep) cache_key = self._key_for(target, dependency_keys)",
"if fprint is None: # It may have been processed in a prior",
"the VersionedTarget dependencies that this target's VersionedTarget should depend on. return versioned_target_deps #",
"# in topological order, so when handling a target, this will already contain",
"\"\"\"Groups versioned targets so that each group has roughly the same number of",
"are implemented. class InvalidationCheck(object): @classmethod def _partition_versioned_targets(cls, versioned_targets, partition_size_hint): \"\"\"Groups versioned targets so",
"be a list of VersionedTargets that correspond to @targets. versioned_targets = [] #",
"class VersionedTarget(VersionedTargetSet): \"\"\"This class represents a singleton VersionedTargetSet, and has links to VersionedTargets",
"with different\" \" CacheManager instances: %s and %s\" % (first_target, versioned_target, cache_manager, versioned_target._cache_manager))",
"find VersionedTargets for them. versioned_target_deps = set([]) if hasattr(target, 'dependencies'): for dep in",
"of [vt4, vt5] and VT3 is [vt6]. The new versioned targets are chosen",
"see if there's a cleaner way for callers to handle awareness of the",
"{} def get_versioned_target_deps_for_target(target): # For every dependency of @target, we will store its",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"for vt in versioned_targets: add_to_current_group(vt) if current_group.total_sources > 1.5 * partition_size_hint and len(current_group.vts)",
"renamed. \"\"\" def __init__(self, cache_key_generator, build_invalidator_dir, invalidate_dependents, extra_data, only_externaldeps): self._cache_key_generator = cache_key_generator self._invalidate_dependents",
"# graph, looking through targets that don't correspond to VersionedTargets themselves. versioned_target_deps_by_target =",
"underlying targets. E.g., VT1 is the combination of [vt1, vt2, vt3], VT2 is",
"if cache_key was set in the VersionedTarget __init__ method. self.cache_key = CacheKeyGenerator.combine_cache_keys([vt.cache_key for",
"currently valid. When invalidating a single target, this can be used to represent",
"all the versioned targets should have the same cache manager. # TODO(ryan): the",
"each group has roughly the same number of sources. versioned_targets is a list",
"force_invalidate(self): self._cache_manager.force_invalidate(self) def __repr__(self): return \"VTS(%s. %d)\" % (','.join(target.id for target in self.targets),",
"under the License. # ================================================================================================== try: import cPickle as pickle except ImportError: import",
"has links to VersionedTargets that the wrapped target depends on (after having resolved",
"__init__(self, cache_manager, target, cache_key): if not isinstance(target, TargetWithSources): raise ValueError(\"The target %s must",
"def from_versioned_targets(cls, versioned_targets): first_target = versioned_targets[0] cache_manager = first_target._cache_manager # Quick sanity check;",
"wrapped target depends on (after having resolved through any \"alias\" targets. \"\"\" def",
"VT3 is [vt6]. The new versioned targets are chosen to have roughly partition_size_hint",
"= self._partition_versioned_targets( invalid_vts, partition_size_hint) if partition_size_hint else invalid_vts class CacheManager(object): \"\"\"Manages cache checks,",
"contain all its deps (in # this round). id_to_hash = {} for target",
"extra_data, only_externaldeps): self._cache_key_generator = cache_key_generator self._invalidate_dependents = invalidate_dependents self._extra_data = pickle.dumps(extra_data) # extra_data",
"return versioned_target_deps # Initialize all VersionedTargets to point to the VersionedTargets they depend",
"Copyright 2012 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version",
"scope problem. class VtGroup(object): def __init__(self): self.vts = [] self.total_sources = 0 current_group",
"self.invalid_vts = invalid_vts # Just the invalid targets, partitioned if so requested. self.invalid_vts_partitioned",
"be None here, indicating that the dependency will not be # processed until",
"# wrappers), we will resolve their actual dependencies and find VersionedTargets for them.",
"can inspect these in order and, e.g., rebuild the invalid ones. \"\"\" all_vts",
"for dep in target.dependencies: # We rely on the fact that any deps",
"earlier cache keys to compute later cache keys in this case. ordered_targets =",
"isinstance(dep, ExternalDependency): dependency_keys.add(dep.cache_key()) elif isinstance(dep, Target): fprint = id_to_hash.get(dep.id, None) if fprint is",
"a no-op if cache_key was set in the VersionedTarget __init__ method. self.cache_key =",
"a list of VersionedTargetSet objects in topological order. # Tasks may need to",
"targets that are built together into a single artifact. \"\"\" @classmethod def from_versioned_targets(cls,",
"as we iterate, # in topological order, so when handling a target, this",
"invalidated VersionedTargetSet as successfully processed.\"\"\" for vt in vts.versioned_targets: self._invalidator.update(vt.cache_key) vt.valid = True",
"from twitter.pants.base.build_invalidator import ( BuildInvalidator, CacheKeyGenerator, NO_SOURCES, TARGET_SOURCES) from twitter.pants.base.target import Target from",
"self._cache_manager = cache_manager self.versioned_targets = versioned_targets self.targets = [vt.target for vt in versioned_targets]",
"sorted(dependency_keys): # Sort to ensure hashing in a consistent order. sha.update(key) return self._cache_key_generator.key_for_target(",
"parent's __init__. VersionedTargetSet.__init__(self, cache_manager, [self]) self.id = target.id self.dependencies = set() # The",
"LICENSE file, or at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"> partition_size_hint: close_current_group() close_current_group() # Close the last group, if any. return res",
"prior round, and therefore the fprint should # have been written out by",
"# continue. versioned_target_deps.add(versioned_targets_by_target[dependency]) elif dependency in versioned_target_deps_by_target: # Otherwise, see if we've already",
"the parent's __init__. VersionedTargetSet.__init__(self, cache_manager, [self]) self.id = target.id self.dependencies = set() #",
"Otherwise, see if we've already resolved this dependency to the VersionedTargets it #",
"= {} # Map from id to current fingerprint of the target with",
"'cover' the input targets, possibly partitioning them, and are in topological order. The",
"[] # This will be a mapping from each target to its corresponding",
"this for the immediate deps, because those will already # reflect changes in",
"graph, looking through targets that don't correspond to VersionedTargets themselves. versioned_target_deps_by_target = {}",
"\"\"\"Mark a changed or invalidated VersionedTargetSet as successfully processed.\"\"\" for vt in vts.versioned_targets:",
"check the targets in this order, to ensure correctness if invalidate_dependents=True, # since",
"of compiler startup overhead. A task can choose instead to build one group",
"for vt in vts.versioned_targets: self._invalidator.force_invalidate(vt.cache_key) vt.valid = False self._invalidator.force_invalidate(vts.cache_key) vts.valid = False def",
"they are used in the parent's __init__. VersionedTargetSet.__init__(self, cache_manager, [self]) self.id = target.id",
"targets should have the same cache manager. # TODO(ryan): the way VersionedTargets store",
"each target to its corresponding VersionedTarget. versioned_targets_by_target = {} # Map from id",
"[vt1, vt2, vt3, vt4, vt5, vt6, ...]. Returns a list of VersionedTargetSet objects,",
"the fact that any deps have already been processed, either in an earlier",
"can also be used to represent a list of targets that are built",
"close_current_group() close_current_group() # Close the last group, if any. return res def __init__(self,",
"changed and invalidates it if so. Returns a list of VersionedTargetSet objects (either",
"set(filter(has_sources, targets)) return filter(targets.__contains__, reversed(InternalTarget.sort_targets(targets))) def _key_for(self, target, dependency_keys): def fingerprint_extra(sha): sha.update(self._extra_data) for",
"self._invalidator.update(vt.cache_key) vt.valid = True self._invalidator.update(vts.cache_key) vts.valid = True def force_invalidate(self, vts): \"\"\"Force invalidation",
"of the targets has changed and invalidates it if so. Returns a list",
"this as we iterate, # in topological order, so when handling a target,",
"the current group without this vt and add it to the next one.",
"if we've already resolved this dependency to the VersionedTargets it # depends on,",
"statistics. Note that this is distinct from the ArtifactCache concept, and should probably",
"For example, if a codegen target depends on a # library target (because",
"it to the next one. current_group.vts.pop() close_current_group() add_to_current_group(vt) elif current_group.total_sources > partition_size_hint: close_current_group()",
"= False self._invalidator.force_invalidate(vts.cache_key) vts.valid = False def check(self, targets, partition_size_hint=None): \"\"\"Checks whether each",
"overhead. A task can choose instead to build one group at a time.",
"versioned targets so that each group has roughly the same number of sources.",
"deps have already been processed, either in an earlier # round or because",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"been written out by the invalidator. fprint = self._invalidator.existing_hash(dep.id) # Note that fprint",
"targets is currently valid. When invalidating a single target, this can be used",
"therefore the fprint should # have been written out by the invalidator. fprint",
"actual dependencies and find VersionedTargets for them. versioned_target_deps = set([]) if hasattr(target, 'dependencies'):",
"result. versioned_target_deps_by_target[dependency] = get_versioned_target_deps_for_target( dependency) versioned_target_deps.update(versioned_target_deps_by_target[dependency]) # Return the VersionedTarget dependencies that this",
"the list of targets is currently valid. When invalidating a single target, this",
"cleaner way for callers to handle awareness of the CacheManager. for versioned_target in",
"in versioned_targets]) self.num_sources = self.cache_key.num_sources self.valid = not cache_manager.needs_update(self.cache_key) def update(self): self._cache_manager.update(self) def",
"set of VersionedTargets, each representing one input target. \"\"\" # We must check",
"def update(self, vts): \"\"\"Mark a changed or invalidated VersionedTargetSet as successfully processed.\"\"\" for",
"= [] # This will be a mapping from each target to its",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"library). if fprint is not None: dependency_keys.add(fprint) else: raise ValueError('Cannot calculate a cache_key",
"self._invalidator.force_invalidate(vt.cache_key) vt.valid = False self._invalidator.force_invalidate(vts.cache_key) vts.valid = False def check(self, targets, partition_size_hint=None): \"\"\"Checks",
"================================================================================================== try: import cPickle as pickle except ImportError: import pickle from twitter.pants import",
"VersionedTargets for them. versioned_target_deps = set([]) if hasattr(target, 'dependencies'): for dep in target.dependencies:",
"hooking up VersionedTarget # dependencies below. versioned_targets_by_target[target] = versioned_target # Having created all",
"self.num_sources = self.cache_key.num_sources self.valid = not cache_manager.needs_update(self.cache_key) def update(self): self._cache_manager.update(self) def force_invalidate(self): self._cache_manager.force_invalidate(self)",
"all_vts) return InvalidationCheck(all_vts, invalid_vts, partition_size_hint) def _sort_and_validate_targets(self, targets): \"\"\"Validate each target. Returns a",
"use those. versioned_target_deps.update(versioned_target_deps_by_target[dependency]) else: # Otherwise, compute the VersionedTargets that correspond to this",
"this can be used to represent that target as a singleton. When checking",
"VersionedTargets, each representing one input target. \"\"\" # We must check the targets",
"ensure hashing in a consistent order. sha.update(key) return self._cache_key_generator.key_for_target( target, sources=self._sources, fingerprint_extra=fingerprint_extra )",
"# The following line is a no-op if cache_key was set in the",
"hasattr(target, 'dependencies'): for dep in target.dependencies: for dependency in dep.resolve(): if dependency in",
"represents a singleton VersionedTargetSet, and has links to VersionedTargets that the wrapped target",
"# are implemented. class InvalidationCheck(object): @classmethod def _partition_versioned_targets(cls, versioned_targets, partition_size_hint): \"\"\"Groups versioned targets",
"VersionedTarget. versioned_targets_by_target = {} # Map from id to current fingerprint of the",
"where we build all targets in a single compiler invocation, and non-flat mode,",
"of targets is currently valid. When invalidating a single target, this can be",
"versioned_targets_by_target[target] = versioned_target # Having created all applicable VersionedTargets, now we build the",
"in versioned_targets_by_target: # If there exists a VersionedTarget corresponding to this Target, store",
"VersionedTarget corresponding to @target. versioned_target = VersionedTarget(self, target, cache_key) # Add the new",
"# since we use earlier cache keys to compute later cache keys in",
"below. versioned_targets_by_target[target] = versioned_target # Having created all applicable VersionedTargets, now we build",
"Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the \"License\");",
"= self._order_target_list(targets) # This will be a list of VersionedTargets that correspond to",
"dep in target.dependencies: for dependency in dep.resolve(): if dependency in versioned_targets_by_target: # If",
"versioned_targets self.targets = [vt.target for vt in versioned_targets] # The following line is",
"the License for the specific language governing permissions and # limitations under the",
"of these, depending on how they # are implemented. class InvalidationCheck(object): @classmethod def",
"0 for vt in versioned_targets: add_to_current_group(vt) if current_group.total_sources > 1.5 * partition_size_hint and",
"[vt4, vt5] and VT3 is [vt6]. The new versioned targets are chosen to",
"# Note that fprint may be None here, indicating that the dependency will",
"group at a time. \"\"\" res = [] # Hack around the python",
"VersionedTargetSet objects (either valid or invalid). The returned sets 'cover' the input targets,",
"pickle except ImportError: import pickle from twitter.pants import has_sources from twitter.pants.base.build_invalidator import (",
"singleton. When checking the artifact cache, this can also be used to represent",
"self._invalidator = BuildInvalidator(build_invalidator_dir) def update(self, vts): \"\"\"Mark a changed or invalidated VersionedTargetSet as",
"generated code needs that library). if fprint is not None: dependency_keys.add(fprint) else: raise",
"fprint is not None: dependency_keys.add(fprint) else: raise ValueError('Cannot calculate a cache_key for a",
"self._invalidate_dependents = invalidate_dependents self._extra_data = pickle.dumps(extra_data) # extra_data may be None. self._sources =",
"# ================================================================================================== # Copyright 2012 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the",
"the generated code needs that library). if fprint is not None: dependency_keys.add(fprint) else:",
"versioned_target.dependencies = get_versioned_target_deps_for_target(versioned_target.target) return versioned_targets def needs_update(self, cache_key): return self._invalidator.needs_update(cache_key) def _order_target_list(self, targets):",
"res.append(new_vt) current_group.vts = [] current_group.total_sources = 0 for vt in versioned_targets: add_to_current_group(vt) if",
"dependency in versioned_target_deps_by_target: # Otherwise, see if we've already resolved this dependency to",
"VersionedTarget (e.g. pass-through dependency # wrappers), we will resolve their actual dependencies and",
"looking through targets that don't correspond to VersionedTargets themselves. versioned_target_deps_by_target = {} def",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"valid or invalid). The returned sets 'cover' the input targets, possibly partitioning them,",
"TARGET_SOURCES self._invalidator = BuildInvalidator(build_invalidator_dir) def update(self, vts): \"\"\"Mark a changed or invalidated VersionedTargetSet",
"License. # You may obtain a copy of the License in the LICENSE",
"__repr__(self): return \"VTS(%s. %d)\" % (','.join(target.id for target in self.targets), 1 if self.valid",
"ValueError('Cannot calculate a cache_key for a dependency: %s' % dep) cache_key = self._key_for(target,",
"here. For # dependencies that don't correspond to a VersionedTarget (e.g. pass-through dependency",
"on a CacheManager. # Each member is a list of VersionedTargetSet objects in",
"invalidation of a VersionedTargetSet.\"\"\" for vt in vts.versioned_targets: self._invalidator.force_invalidate(vt.cache_key) vt.valid = False self._invalidator.force_invalidate(vts.cache_key)",
"ordered_targets: dependency_keys = set() if self._invalidate_dependents and hasattr(target, 'dependencies'): # Note that we",
"a target, this will already contain all its deps (in # this round).",
"and add it to the next one. current_group.vts.pop() close_current_group() add_to_current_group(vt) elif current_group.total_sources >",
"checks, updates and invalidation keeping track of basic change and invalidation statistics. Note",
"def close_current_group(): if len(current_group.vts) > 0: new_vt = VersionedTargetSet.from_versioned_targets(current_group.vts) res.append(new_vt) current_group.vts = []",
"Each member is a list of VersionedTargetSet objects in topological order. # Tasks",
"can be used to represent that target as a singleton. When checking the",
"to @target. versioned_target = VersionedTarget(self, target, cache_key) # Add the new VersionedTarget to",
"VersionedTargets themselves. versioned_target_deps_by_target = {} def get_versioned_target_deps_for_target(target): # For every dependency of @target,",
"not be # processed until a later phase. For example, if a codegen",
"need to perform no, some or all operations on either of these, depending",
"versioned_target._cache_manager)) return cls(cache_manager, versioned_targets) def __init__(self, cache_manager, versioned_targets): self._cache_manager = cache_manager self.versioned_targets =",
"= not cache_manager.needs_update(self.cache_key) def update(self): self._cache_manager.update(self) def force_invalidate(self): self._cache_manager.force_invalidate(self) def __repr__(self): return \"VTS(%s.",
"of basic change and invalidation statistics. Note that this is distinct from the",
"this target's VersionedTarget should depend on. return versioned_target_deps # Initialize all VersionedTargets to",
"to the next one. current_group.vts.pop() close_current_group() add_to_current_group(vt) elif current_group.total_sources > partition_size_hint: close_current_group() close_current_group()",
"partition_size_hint) def _sort_and_validate_targets(self, targets): \"\"\"Validate each target. Returns a topologically ordered set of",
"for vt in vts.versioned_targets: self._invalidator.update(vt.cache_key) vt.valid = True self._invalidator.update(vts.cache_key) vts.valid = True def",
"to the VersionedTargets they depend on. for versioned_target in versioned_targets: versioned_target.dependencies = get_versioned_target_deps_for_target(versioned_target.target)",
"versioned_targets): first_target = versioned_targets[0] cache_manager = first_target._cache_manager # Quick sanity check; all the",
"res def __init__(self, all_vts, invalid_vts, partition_size_hint=None): # All the targets, valid and invalid.",
"We rely on the fact that any deps have already been processed, either",
"choose instead to build one group at a time. \"\"\" res = []",
"valid and invalid. self.all_vts = all_vts # All the targets, partitioned if so",
"= NO_SOURCES if only_externaldeps else TARGET_SOURCES self._invalidator = BuildInvalidator(build_invalidator_dir) def update(self, vts): \"\"\"Mark",
"to do this for the immediate deps, because those will already # reflect",
"a CacheManager. # Each member is a list of VersionedTargetSet objects in topological",
"in dep.resolve(): if dependency in versioned_targets_by_target: # If there exists a VersionedTarget corresponding",
"the invalid targets, partitioned if so requested. self.invalid_vts_partitioned = self._partition_versioned_targets( invalid_vts, partition_size_hint) if",
"a # library target (because the generated code needs that library). if fprint",
"check(self, targets, partition_size_hint=None): \"\"\"Checks whether each of the targets has changed and invalidates",
"cache keys in this case. ordered_targets = self._order_target_list(targets) # This will be a",
"cache_manager, [self]) self.id = target.id self.dependencies = set() # The result of calling",
"def __init__(self, cache_manager, versioned_targets): self._cache_manager = cache_manager self.versioned_targets = versioned_targets self.targets = [vt.target",
"manager. # TODO(ryan): the way VersionedTargets store their own links to a single",
"possibly partitioning them, and are in topological order. The caller can inspect these",
"# TODO(ryan): the way VersionedTargets store their own links to a single CacheManager",
"rely on the fact that any deps have already been processed, either in",
"License in the LICENSE file, or at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"until a later phase. For example, if a codegen target depends on a",
"the immediate deps, because those will already # reflect changes in their own",
"[vt.target for vt in versioned_targets] # The following line is a no-op if",
"Tasks may need to perform no, some or all operations on either of",
"Quick sanity check; all the versioned targets should have the same cache manager.",
"versioned_target in versioned_targets: versioned_target.dependencies = get_versioned_target_deps_for_target(versioned_target.target) return versioned_targets def needs_update(self, cache_key): return self._invalidator.needs_update(cache_key)",
"return versioned_targets def needs_update(self, cache_key): return self._invalidator.needs_update(cache_key) def _order_target_list(self, targets): \"\"\"Orders the targets",
"def __repr__(self): return \"VTS(%s. %d)\" % (','.join(target.id for target in self.targets), 1 if",
"ensure correctness if invalidate_dependents=True, # since we use earlier cache keys to compute",
"_order_target_list(self, targets): \"\"\"Orders the targets topologically, from least to most dependent.\"\"\" targets =",
"because they came first in ordered_targets. if isinstance(dep, ExternalDependency): dependency_keys.add(dep.cache_key()) elif isinstance(dep, Target):",
"...]. Returns a list of VersionedTargetSet objects, e.g., [VT1, VT2, VT3, ...] representing",
"else 0) class VersionedTarget(VersionedTargetSet): \"\"\"This class represents a singleton VersionedTargetSet, and has links",
"whether each of the targets has changed and invalidates it if so. Returns",
"if current_group.total_sources > 1.5 * partition_size_hint and len(current_group.vts) > 1: # Too big.",
"outer scope problem. class VtGroup(object): def __init__(self): self.vts = [] self.total_sources = 0",
"targets = set(filter(has_sources, targets)) return filter(targets.__contains__, reversed(InternalTarget.sort_targets(targets))) def _key_for(self, target, dependency_keys): def fingerprint_extra(sha):",
"build_invalidator_dir, invalidate_dependents, extra_data, only_externaldeps): self._cache_key_generator = cache_key_generator self._invalidate_dependents = invalidate_dependents self._extra_data = pickle.dumps(extra_data)",
"its corresponding VersionedTarget. versioned_targets_by_target = {} # Map from id to current fingerprint",
"self._key_for(target, dependency_keys) id_to_hash[target.id] = cache_key.hash # Create a VersionedTarget corresponding to @target. versioned_target",
"> 1.5 * partition_size_hint and len(current_group.vts) > 1: # Too big. Close the",
"================================================================================================== # Copyright 2012 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache",
"dependencies that don't correspond to a VersionedTarget (e.g. pass-through dependency # wrappers), we",
"= set(filter(has_sources, targets)) return filter(targets.__contains__, reversed(InternalTarget.sort_targets(targets))) def _key_for(self, target, dependency_keys): def fingerprint_extra(sha): sha.update(self._extra_data)",
"import TargetWithSources from twitter.pants.targets.external_dependency import ExternalDependency from twitter.pants.targets.internal import InternalTarget class VersionedTargetSet(object): \"\"\"Represents",
"def needs_update(self, cache_key): return self._invalidator.needs_update(cache_key) def _order_target_list(self, targets): \"\"\"Orders the targets topologically, from",
"# depends on, and use those. versioned_target_deps.update(versioned_target_deps_by_target[dependency]) else: # Otherwise, compute the VersionedTargets",
"the License in the LICENSE file, or at: # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"used to represent a list of targets that are built together into a",
"will be a list of VersionedTargets that correspond to @targets. versioned_targets = []",
"# round or because they came first in ordered_targets. if isinstance(dep, ExternalDependency): dependency_keys.add(dep.cache_key())",
"or because they came first in ordered_targets. if isinstance(dep, ExternalDependency): dependency_keys.add(dep.cache_key()) elif isinstance(dep,",
"by the invalidator. fprint = self._invalidator.existing_hash(dep.id) # Note that fprint may be None",
"any. return res def __init__(self, all_vts, invalid_vts, partition_size_hint=None): # All the targets, valid",
"target.dependencies: # We rely on the fact that any deps have already been",
"the invalidator. fprint = self._invalidator.existing_hash(dep.id) # Note that fprint may be None here,",
"is not None: dependency_keys.add(fprint) else: raise ValueError('Cannot calculate a cache_key for a dependency:",
"the targets, valid and invalid. self.all_vts = all_vts # All the targets, partitioned",
"cache checks, updates and invalidation keeping track of basic change and invalidation statistics.",
"startup overhead. A task can choose instead to build one group at a",
"and invalidation statistics. Note that this is distinct from the ArtifactCache concept, and",
"the combination of [vt4, vt5] and VT3 is [vt6]. The new versioned targets",
"input targets, possibly partitioning them, and are in topological order. The caller can",
"License. # ================================================================================================== try: import cPickle as pickle except ImportError: import pickle from",
"versioned_targets, partition_size_hint): \"\"\"Groups versioned targets so that each group has roughly the same",
"are built together into a single artifact. \"\"\" @classmethod def from_versioned_targets(cls, versioned_targets): first_target",
"not.\" % target.id) self.target = target self.cache_key = cache_key # Must come after",
"versioned_target_deps.add(versioned_targets_by_target[dependency]) elif dependency in versioned_target_deps_by_target: # Otherwise, see if we've already resolved this",
"to represent that target as a singleton. When checking the artifact cache, this",
"# feels hacky; see if there's a cleaner way for callers to handle",
"to handle awareness of the CacheManager. for versioned_target in versioned_targets: if versioned_target._cache_manager !=",
"if hasattr(target, 'dependencies'): for dep in target.dependencies: for dependency in dep.resolve(): if dependency",
"InvalidationCheck(object): @classmethod def _partition_versioned_targets(cls, versioned_targets, partition_size_hint): \"\"\"Groups versioned targets so that each group",
"in this order, to ensure correctness if invalidate_dependents=True, # since we use earlier",
"order, to ensure correctness if invalidate_dependents=True, # since we use earlier cache keys",
"in topological order. # Tasks may need to perform no, some or all",
"# ================================================================================================== try: import cPickle as pickle except ImportError: import pickle from twitter.pants",
"to have roughly partition_size_hint sources. This is useful as a compromise between flat",
"# library target (because the generated code needs that library). if fprint is",
"vt6, ...]. Returns a list of VersionedTargetSet objects, e.g., [VT1, VT2, VT3, ...]",
"res = [] # Hack around the python outer scope problem. class VtGroup(object):",
"from the ArtifactCache concept, and should probably be renamed. \"\"\" def __init__(self, cache_key_generator,",
"# Create a VersionedTarget corresponding to @target. versioned_target = VersionedTarget(self, target, cache_key) #",
"OF ANY KIND, either express or implied. # See the License for the",
"key in sorted(dependency_keys): # Sort to ensure hashing in a consistent order. sha.update(key)",
"be renamed. \"\"\" def __init__(self, cache_key_generator, build_invalidator_dir, invalidate_dependents, extra_data, only_externaldeps): self._cache_key_generator = cache_key_generator",
"in order and, e.g., rebuild the invalid ones. \"\"\" all_vts = self._sort_and_validate_targets(targets) invalid_vts",
"this will already contain all its deps (in # this round). id_to_hash =",
"current_group.total_sources > partition_size_hint: close_current_group() close_current_group() # Close the last group, if any. return",
"to @targets. versioned_targets = [] # This will be a mapping from each",
"to build one group at a time. \"\"\" res = [] # Hack",
"%s and %s\" % (first_target, versioned_target, cache_manager, versioned_target._cache_manager)) return cls(cache_manager, versioned_targets) def __init__(self,",
"# We rely on the fact that any deps have already been processed,",
"to perform no, some or all operations on either of these, depending on",
"that this target's VersionedTarget should depend on. return versioned_target_deps # Initialize all VersionedTargets",
"self._partition_versioned_targets( invalid_vts, partition_size_hint) if partition_size_hint else invalid_vts class CacheManager(object): \"\"\"Manages cache checks, updates",
"dependency) versioned_target_deps.update(versioned_target_deps_by_target[dependency]) # Return the VersionedTarget dependencies that this target's VersionedTarget should depend",
"not cache_manager.needs_update(self.cache_key) def update(self): self._cache_manager.update(self) def force_invalidate(self): self._cache_manager.force_invalidate(self) def __repr__(self): return \"VTS(%s. %d)\"",
"invoke a compiler for each target, which may lead to lots of compiler",
"feels hacky; see if there's a cleaner way for callers to handle awareness",
"self.valid else 0) class VersionedTarget(VersionedTargetSet): \"\"\"This class represents a singleton VersionedTargetSet, and has",
"basic change and invalidation statistics. Note that this is distinct from the ArtifactCache",
"vts.valid = True def force_invalidate(self, vts): \"\"\"Force invalidation of a VersionedTargetSet.\"\"\" for vt",
"caller can inspect these in order and, e.g., rebuild the invalid ones. \"\"\"",
"all_vts, partition_size_hint) if partition_size_hint else all_vts # Just the invalid targets. self.invalid_vts =",
"should depend on. return versioned_target_deps # Initialize all VersionedTargets to point to the",
"versioned_target = VersionedTarget(self, target, cache_key) # Add the new VersionedTarget to the list",
"invalid_vts class CacheManager(object): \"\"\"Manages cache checks, updates and invalidation keeping track of basic",
"list of computed VersionedTargets. versioned_targets.append(versioned_target) # Add to the mapping from Targets to",
"cache keys to compute later cache keys in this case. ordered_targets = self._order_target_list(targets)",
"of [vt1, vt2, vt3], VT2 is the combination of [vt4, vt5] and VT3",
"All the targets, partitioned if so requested. self.all_vts_partitioned = self._partition_versioned_targets( all_vts, partition_size_hint) if",
"or invalid). The returned sets 'cover' the input targets, possibly partitioning them, and",
"a VersionedTargetSet.\"\"\" for vt in vts.versioned_targets: self._invalidator.force_invalidate(vt.cache_key) vt.valid = False self._invalidator.force_invalidate(vts.cache_key) vts.valid =",
"cache_key): return self._invalidator.needs_update(cache_key) def _order_target_list(self, targets): \"\"\"Orders the targets topologically, from least to",
"it if so. Returns a list of VersionedTargetSet objects (either valid or invalid).",
"# you may not use this work except in compliance with the License.",
"corresponding VersionedTarget. versioned_targets_by_target = {} # Map from id to current fingerprint of",
"> 1: # Too big. Close the current group without this vt and",
"= pickle.dumps(extra_data) # extra_data may be None. self._sources = NO_SOURCES if only_externaldeps else",
"self._sources = NO_SOURCES if only_externaldeps else TARGET_SOURCES self._invalidator = BuildInvalidator(build_invalidator_dir) def update(self, vts):",
"versioned_target, cache_manager, versioned_target._cache_manager)) return cls(cache_manager, versioned_targets) def __init__(self, cache_manager, versioned_targets): self._cache_manager = cache_manager",
"or agreed to in writing, software # distributed under the License is distributed",
"list of VersionedTargetSet objects (either valid or invalid). The returned sets 'cover' the",
"dependencies and find VersionedTargets for them. versioned_target_deps = set([]) if hasattr(target, 'dependencies'): for",
"either in an earlier # round or because they came first in ordered_targets.",
"on the fact that any deps have already been processed, either in an",
"\"License\"); # you may not use this work except in compliance with the",
"None) if fprint is None: # It may have been processed in a",
"used in the parent's __init__. VersionedTargetSet.__init__(self, cache_manager, [self]) self.id = target.id self.dependencies =",
"assignments above, as they are used in the parent's __init__. VersionedTargetSet.__init__(self, cache_manager, [self])",
"else: raise ValueError('Cannot calculate a cache_key for a dependency: %s' % dep) cache_key",
"needs that library). if fprint is not None: dependency_keys.add(fprint) else: raise ValueError('Cannot calculate",
"vt in versioned_targets]) self.num_sources = self.cache_key.num_sources self.valid = not cache_manager.needs_update(self.cache_key) def update(self): self._cache_manager.update(self)",
"class represents a singleton VersionedTargetSet, and has links to VersionedTargets that the wrapped",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"big. Close the current group without this vt and add it to the",
"VersionedTargets. versioned_targets.append(versioned_target) # Add to the mapping from Targets to VersionedTargets, for use",
"# Initialize all VersionedTargets to point to the VersionedTargets they depend on. for",
"= VtGroup() def add_to_current_group(vt): current_group.vts.append(vt) current_group.total_sources += vt.num_sources def close_current_group(): if len(current_group.vts) >",
"changed or invalidated VersionedTargetSet as successfully processed.\"\"\" for vt in vts.versioned_targets: self._invalidator.update(vt.cache_key) vt.valid",
"target with that id. We update this as we iterate, # in topological",
"close_current_group() # Close the last group, if any. return res def __init__(self, all_vts,",
"python outer scope problem. class VtGroup(object): def __init__(self): self.vts = [] self.total_sources =",
"target (because the generated code needs that library). if fprint is not None:",
"valid. When invalidating a single target, this can be used to represent that",
"versioned_target_deps_by_target[dependency] = get_versioned_target_deps_for_target( dependency) versioned_target_deps.update(versioned_target_deps_by_target[dependency]) # Return the VersionedTarget dependencies that this target's",
"vt.valid, all_vts) return InvalidationCheck(all_vts, invalid_vts, partition_size_hint) def _sort_and_validate_targets(self, targets): \"\"\"Validate each target. Returns",
"\"\"\" res = [] # Hack around the python outer scope problem. class",
"versioned_targets_by_target: # If there exists a VersionedTarget corresponding to this Target, store it",
"vts): \"\"\"Mark a changed or invalidated VersionedTargetSet as successfully processed.\"\"\" for vt in",
"a list of targets, a corresponding CacheKey, and a flag determining whether the",
"copy of the License in the LICENSE file, or at: # # http://www.apache.org/licenses/LICENSE-2.0",
"useful as a compromise between flat mode, where we build all targets in",
"that don't correspond to a VersionedTarget (e.g. pass-through dependency # wrappers), we will",
"and VT3 is [vt6]. The new versioned targets are chosen to have roughly",
"= get_versioned_target_deps_for_target( dependency) versioned_target_deps.update(versioned_target_deps_by_target[dependency]) # Return the VersionedTarget dependencies that this target's VersionedTarget",
"return cls(cache_manager, versioned_targets) def __init__(self, cache_manager, versioned_targets): self._cache_manager = cache_manager self.versioned_targets = versioned_targets",
"raise ValueError(\"The target %s must support sources and does not.\" % target.id) self.target",
"'dependencies'): # Note that we only need to do this for the immediate",
"representing one input target. \"\"\" # We must check the targets in this",
"of calling check() on a CacheManager. # Each member is a list of",
"a changed or invalidated VersionedTargetSet as successfully processed.\"\"\" for vt in vts.versioned_targets: self._invalidator.update(vt.cache_key)",
"def _order_target_list(self, targets): \"\"\"Orders the targets topologically, from least to most dependent.\"\"\" targets",
"partitioned if so requested. self.all_vts_partitioned = self._partition_versioned_targets( all_vts, partition_size_hint) if partition_size_hint else all_vts",
"already been processed, either in an earlier # round or because they came",
"self._invalidator.update(vts.cache_key) vts.valid = True def force_invalidate(self, vts): \"\"\"Force invalidation of a VersionedTargetSet.\"\"\" for",
"changes in their own deps. for dep in target.dependencies: # We rely on",
"for target in self.targets), 1 if self.valid else 0) class VersionedTarget(VersionedTargetSet): \"\"\"This class",
"ordered set of VersionedTargets, each representing one input target. \"\"\" # We must",
"this order, to ensure correctness if invalidate_dependents=True, # since we use earlier cache",
"and does not.\" % target.id) self.target = target self.cache_key = cache_key # Must",
"self._invalidator.existing_hash(dep.id) # Note that fprint may be None here, indicating that the dependency",
"VersionedTarget objects [vt1, vt2, vt3, vt4, vt5, vt6, ...]. Returns a list of",
"in the LICENSE file, or at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"for target in ordered_targets: dependency_keys = set() if self._invalidate_dependents and hasattr(target, 'dependencies'): #",
"partitioning them, and are in topological order. The caller can inspect these in",
"for versioned_target in versioned_targets: if versioned_target._cache_manager != cache_manager: raise ValueError(\"Attempting to combine versioned",
"targets): \"\"\"Validate each target. Returns a topologically ordered set of VersionedTargets, each representing",
"isinstance(target, TargetWithSources): raise ValueError(\"The target %s must support sources and does not.\" %",
"are used in the parent's __init__. VersionedTargetSet.__init__(self, cache_manager, [self]) self.id = target.id self.dependencies",
"be used to represent a list of targets that are built together into",
"= set() # The result of calling check() on a CacheManager. # Each",
"add_to_current_group(vt): current_group.vts.append(vt) current_group.total_sources += vt.num_sources def close_current_group(): if len(current_group.vts) > 0: new_vt =",
"we iterate, # in topological order, so when handling a target, this will",
"in versioned_targets: if versioned_target._cache_manager != cache_manager: raise ValueError(\"Attempting to combine versioned targets %s",
"VersionedTargetSet, and has links to VersionedTargets that the wrapped target depends on (after",
"later phase. For example, if a codegen target depends on a # library",
"For # dependencies that don't correspond to a VersionedTarget (e.g. pass-through dependency #",
"dependency_keys) id_to_hash[target.id] = cache_key.hash # Create a VersionedTarget corresponding to @target. versioned_target =",
"have roughly partition_size_hint sources. This is useful as a compromise between flat mode,",
"of the target with that id. We update this as we iterate, #",
"on (after having resolved through any \"alias\" targets. \"\"\" def __init__(self, cache_manager, target,",
"target, cache_key): if not isinstance(target, TargetWithSources): raise ValueError(\"The target %s must support sources",
"def force_invalidate(self, vts): \"\"\"Force invalidation of a VersionedTargetSet.\"\"\" for vt in vts.versioned_targets: self._invalidator.force_invalidate(vt.cache_key)",
"VtGroup(object): def __init__(self): self.vts = [] self.total_sources = 0 current_group = VtGroup() def",
"not vt.valid, all_vts) return InvalidationCheck(all_vts, invalid_vts, partition_size_hint) def _sort_and_validate_targets(self, targets): \"\"\"Validate each target.",
"or invalidated VersionedTargetSet as successfully processed.\"\"\" for vt in vts.versioned_targets: self._invalidator.update(vt.cache_key) vt.valid =",
"\"\"\"Force invalidation of a VersionedTargetSet.\"\"\" for vt in vts.versioned_targets: self._invalidator.force_invalidate(vt.cache_key) vt.valid = False",
"VersionedTargets it # depends on, and use those. versioned_target_deps.update(versioned_target_deps_by_target[dependency]) else: # Otherwise, compute",
"in target.dependencies: # We rely on the fact that any deps have already",
"awareness of the CacheManager. for versioned_target in versioned_targets: if versioned_target._cache_manager != cache_manager: raise",
"needs_update(self, cache_key): return self._invalidator.needs_update(cache_key) def _order_target_list(self, targets): \"\"\"Orders the targets topologically, from least",
"invalid. self.all_vts = all_vts # All the targets, partitioned if so requested. self.all_vts_partitioned",
"new VersionedTarget to the list of computed VersionedTargets. versioned_targets.append(versioned_target) # Add to the",
"sets 'cover' the input targets, possibly partitioning them, and are in topological order.",
"see if we've already resolved this dependency to the VersionedTargets it # depends",
"and invalidation keeping track of basic change and invalidation statistics. Note that this",
"invalid_vts, partition_size_hint) if partition_size_hint else invalid_vts class CacheManager(object): \"\"\"Manages cache checks, updates and",
"class InvalidationCheck(object): @classmethod def _partition_versioned_targets(cls, versioned_targets, partition_size_hint): \"\"\"Groups versioned targets so that each",
"all_vts = self._sort_and_validate_targets(targets) invalid_vts = filter(lambda vt: not vt.valid, all_vts) return InvalidationCheck(all_vts, invalid_vts,",
"except ImportError: import pickle from twitter.pants import has_sources from twitter.pants.base.build_invalidator import ( BuildInvalidator,",
"corresponding CacheKey, and a flag determining whether the list of targets is currently",
"len(current_group.vts) > 0: new_vt = VersionedTargetSet.from_versioned_targets(current_group.vts) res.append(new_vt) current_group.vts = [] current_group.total_sources = 0",
"# Having created all applicable VersionedTargets, now we build the VersionedTarget dependency #",
"versioned_targets]) self.num_sources = self.cache_key.num_sources self.valid = not cache_manager.needs_update(self.cache_key) def update(self): self._cache_manager.update(self) def force_invalidate(self):",
"current group without this vt and add it to the next one. current_group.vts.pop()",
"code needs that library). if fprint is not None: dependency_keys.add(fprint) else: raise ValueError('Cannot",
"use this work except in compliance with the License. # You may obtain",
"def _key_for(self, target, dependency_keys): def fingerprint_extra(sha): sha.update(self._extra_data) for key in sorted(dependency_keys): # Sort",
"governing permissions and # limitations under the License. # ================================================================================================== try: import cPickle",
"versioned_targets) def __init__(self, cache_manager, versioned_targets): self._cache_manager = cache_manager self.versioned_targets = versioned_targets self.targets =",
"# The result of calling check() on a CacheManager. # Each member is",
"Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the",
"or implied. # See the License for the specific language governing permissions and",
"build all targets in a single compiler invocation, and non-flat mode, where we",
"__init__(self, all_vts, invalid_vts, partition_size_hint=None): # All the targets, valid and invalid. self.all_vts =",
"License, Version 2.0 (the \"License\"); # you may not use this work except",
"store its corresponding VersionedTarget here. For # dependencies that don't correspond to a",
"already contain all its deps (in # this round). id_to_hash = {} for",
"order, so when handling a target, this will already contain all its deps",
"and, e.g., rebuild the invalid ones. \"\"\" all_vts = self._sort_and_validate_targets(targets) invalid_vts = filter(lambda",
"dependency_keys = set() if self._invalidate_dependents and hasattr(target, 'dependencies'): # Note that we only",
"VersionedTarget(VersionedTargetSet): \"\"\"This class represents a singleton VersionedTargetSet, and has links to VersionedTargets that",
"the targets topologically, from least to most dependent.\"\"\" targets = set(filter(has_sources, targets)) return",
"artifact. \"\"\" @classmethod def from_versioned_targets(cls, versioned_targets): first_target = versioned_targets[0] cache_manager = first_target._cache_manager #",
"# All the targets, valid and invalid. self.all_vts = all_vts # All the",
"versioned_target_deps_by_target: # Otherwise, see if we've already resolved this dependency to the VersionedTargets",
"# Each member is a list of VersionedTargetSet objects in topological order. #",
"are in topological order. The caller can inspect these in order and, e.g.,",
"to ensure correctness if invalidate_dependents=True, # since we use earlier cache keys to",
"E.g., VT1 is the combination of [vt1, vt2, vt3], VT2 is the combination",
"self._invalidator.needs_update(cache_key) def _order_target_list(self, targets): \"\"\"Orders the targets topologically, from least to most dependent.\"\"\"",
"distinct from the ArtifactCache concept, and should probably be renamed. \"\"\" def __init__(self,",
"Targets to VersionedTargets, for use in hooking up VersionedTarget # dependencies below. versioned_targets_by_target[target]",
"mapping from each target to its corresponding VersionedTarget. versioned_targets_by_target = {} # Map",
"force_invalidate(self, vts): \"\"\"Force invalidation of a VersionedTargetSet.\"\"\" for vt in vts.versioned_targets: self._invalidator.force_invalidate(vt.cache_key) vt.valid",
"vt5] and VT3 is [vt6]. The new versioned targets are chosen to have",
"import Target from twitter.pants.targets import TargetWithSources from twitter.pants.targets.external_dependency import ExternalDependency from twitter.pants.targets.internal import",
"targets, a corresponding CacheKey, and a flag determining whether the list of targets",
"the next one. current_group.vts.pop() close_current_group() add_to_current_group(vt) elif current_group.total_sources > partition_size_hint: close_current_group() close_current_group() #",
"dependencies that this target's VersionedTarget should depend on. return versioned_target_deps # Initialize all",
"store their own links to a single CacheManager instance # feels hacky; see",
"may be None here, indicating that the dependency will not be # processed",
"be used to represent that target as a singleton. When checking the artifact",
"does not.\" % target.id) self.target = target self.cache_key = cache_key # Must come",
"is [vt6]. The new versioned targets are chosen to have roughly partition_size_hint sources.",
"and find VersionedTargets for them. versioned_target_deps = set([]) if hasattr(target, 'dependencies'): for dep",
"round, and therefore the fprint should # have been written out by the",
"and use the computed result. versioned_target_deps_by_target[dependency] = get_versioned_target_deps_for_target( dependency) versioned_target_deps.update(versioned_target_deps_by_target[dependency]) # Return the",
"and a flag determining whether the list of targets is currently valid. When",
"written out by the invalidator. fprint = self._invalidator.existing_hash(dep.id) # Note that fprint may",
"id_to_hash.get(dep.id, None) if fprint is None: # It may have been processed in",
"support sources and does not.\" % target.id) self.target = target self.cache_key = cache_key",
"was set in the VersionedTarget __init__ method. self.cache_key = CacheKeyGenerator.combine_cache_keys([vt.cache_key for vt in",
"topologically ordered set of VersionedTargets, each representing one input target. \"\"\" # We",
"they came first in ordered_targets. if isinstance(dep, ExternalDependency): dependency_keys.add(dep.cache_key()) elif isinstance(dep, Target): fprint",
"Returns a list of VersionedTargetSet objects (either valid or invalid). The returned sets",
"The caller can inspect these in order and, e.g., rebuild the invalid ones.",
"a cleaner way for callers to handle awareness of the CacheManager. for versioned_target",
"come after the assignments above, as they are used in the parent's __init__.",
"Return the VersionedTarget dependencies that this target's VersionedTarget should depend on. return versioned_target_deps",
"one. current_group.vts.pop() close_current_group() add_to_current_group(vt) elif current_group.total_sources > partition_size_hint: close_current_group() close_current_group() # Close the",
"# Copyright 2012 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License,",
"Apache License, Version 2.0 (the \"License\"); # you may not use this work",
"__init__. VersionedTargetSet.__init__(self, cache_manager, [self]) self.id = target.id self.dependencies = set() # The result",
"else all_vts # Just the invalid targets. self.invalid_vts = invalid_vts # Just the",
"for the specific language governing permissions and # limitations under the License. #",
"the versioned targets should have the same cache manager. # TODO(ryan): the way",
"class VtGroup(object): def __init__(self): self.vts = [] self.total_sources = 0 current_group = VtGroup()",
"to VersionedTargets, for use in hooking up VersionedTarget # dependencies below. versioned_targets_by_target[target] =",
"the fprint should # have been written out by the invalidator. fprint =",
"processed.\"\"\" for vt in vts.versioned_targets: self._invalidator.update(vt.cache_key) vt.valid = True self._invalidator.update(vts.cache_key) vts.valid = True",
"VT2 is the combination of [vt4, vt5] and VT3 is [vt6]. The new",
"self._partition_versioned_targets( all_vts, partition_size_hint) if partition_size_hint else all_vts # Just the invalid targets. self.invalid_vts",
"%d)\" % (','.join(target.id for target in self.targets), 1 if self.valid else 0) class",
"the targets in this order, to ensure correctness if invalidate_dependents=True, # since we",
"targets that don't correspond to VersionedTargets themselves. versioned_target_deps_by_target = {} def get_versioned_target_deps_for_target(target): #",
"a VersionedTarget corresponding to @target. versioned_target = VersionedTarget(self, target, cache_key) # Add the",
"combination of [vt4, vt5] and VT3 is [vt6]. The new versioned targets are",
"# This will be a list of VersionedTargets that correspond to @targets. versioned_targets",
"in versioned_targets: versioned_target.dependencies = get_versioned_target_deps_for_target(versioned_target.target) return versioned_targets def needs_update(self, cache_key): return self._invalidator.needs_update(cache_key) def",
"is None: # It may have been processed in a prior round, and",
"pickle.dumps(extra_data) # extra_data may be None. self._sources = NO_SOURCES if only_externaldeps else TARGET_SOURCES",
"that fprint may be None here, indicating that the dependency will not be",
"topological order, so when handling a target, this will already contain all its",
"invalidate_dependents self._extra_data = pickle.dumps(extra_data) # extra_data may be None. self._sources = NO_SOURCES if",
"applicable VersionedTargets, now we build the VersionedTarget dependency # graph, looking through targets",
"0 current_group = VtGroup() def add_to_current_group(vt): current_group.vts.append(vt) current_group.total_sources += vt.num_sources def close_current_group(): if",
"cache_key): if not isinstance(target, TargetWithSources): raise ValueError(\"The target %s must support sources and",
"dependency will not be # processed until a later phase. For example, if",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"together into a single artifact. \"\"\" @classmethod def from_versioned_targets(cls, versioned_targets): first_target = versioned_targets[0]",
"of VersionedTarget objects [vt1, vt2, vt3, vt4, vt5, vt6, ...]. Returns a list",
"target, dependency_keys): def fingerprint_extra(sha): sha.update(self._extra_data) for key in sorted(dependency_keys): # Sort to ensure",
"when handling a target, this will already contain all its deps (in #",
"to current fingerprint of the target with that id. We update this as",
"VersionedTarget __init__ method. self.cache_key = CacheKeyGenerator.combine_cache_keys([vt.cache_key for vt in versioned_targets]) self.num_sources = self.cache_key.num_sources",
"topologically, from least to most dependent.\"\"\" targets = set(filter(has_sources, targets)) return filter(targets.__contains__, reversed(InternalTarget.sort_targets(targets)))",
"checking the artifact cache, this can also be used to represent a list",
"these, depending on how they # are implemented. class InvalidationCheck(object): @classmethod def _partition_versioned_targets(cls,",
"later cache keys in this case. ordered_targets = self._order_target_list(targets) # This will be",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"Map from id to current fingerprint of the target with that id. We",
"is a list of VersionedTarget objects [vt1, vt2, vt3, vt4, vt5, vt6, ...].",
"indicating that the dependency will not be # processed until a later phase.",
"the same number of sources. versioned_targets is a list of VersionedTarget objects [vt1,",
"Hack around the python outer scope problem. class VtGroup(object): def __init__(self): self.vts =",
"those will already # reflect changes in their own deps. for dep in",
"a list of VersionedTarget objects [vt1, vt2, vt3, vt4, vt5, vt6, ...]. Returns",
"VersionedTargets store their own links to a single CacheManager instance # feels hacky;",
"Note that fprint may be None here, indicating that the dependency will not",
"not use this work except in compliance with the License. # You may",
"versioned_targets is a list of VersionedTarget objects [vt1, vt2, vt3, vt4, vt5, vt6,",
"vt in versioned_targets] # The following line is a no-op if cache_key was",
"Must come after the assignments above, as they are used in the parent's",
"# Hack around the python outer scope problem. class VtGroup(object): def __init__(self): self.vts",
"= 0 current_group = VtGroup() def add_to_current_group(vt): current_group.vts.append(vt) current_group.total_sources += vt.num_sources def close_current_group():",
"to this dependency's # dependencies, cache and use the computed result. versioned_target_deps_by_target[dependency] =",
"versioned_target_deps = set([]) if hasattr(target, 'dependencies'): for dep in target.dependencies: for dependency in",
"import has_sources from twitter.pants.base.build_invalidator import ( BuildInvalidator, CacheKeyGenerator, NO_SOURCES, TARGET_SOURCES) from twitter.pants.base.target import",
"if so requested. self.invalid_vts_partitioned = self._partition_versioned_targets( invalid_vts, partition_size_hint) if partition_size_hint else invalid_vts class",
"task can choose instead to build one group at a time. \"\"\" res",
"Sort to ensure hashing in a consistent order. sha.update(key) return self._cache_key_generator.key_for_target( target, sources=self._sources,",
"to VersionedTargets themselves. versioned_target_deps_by_target = {} def get_versioned_target_deps_for_target(target): # For every dependency of",
"VersionedTargets that correspond to this dependency's # dependencies, cache and use the computed",
"VersionedTargetSet.from_versioned_targets(current_group.vts) res.append(new_vt) current_group.vts = [] current_group.total_sources = 0 for vt in versioned_targets: add_to_current_group(vt)",
"dependency # wrappers), we will resolve their actual dependencies and find VersionedTargets for",
"we build the VersionedTarget dependency # graph, looking through targets that don't correspond",
"of a VersionedTargetSet.\"\"\" for vt in vts.versioned_targets: self._invalidator.force_invalidate(vt.cache_key) vt.valid = False self._invalidator.force_invalidate(vts.cache_key) vts.valid",
"versioned_target in versioned_targets: if versioned_target._cache_manager != cache_manager: raise ValueError(\"Attempting to combine versioned targets",
"instead to build one group at a time. \"\"\" res = [] #",
"law or agreed to in writing, software # distributed under the License is",
"partition_size_hint: close_current_group() close_current_group() # Close the last group, if any. return res def",
"This is useful as a compromise between flat mode, where we build all",
"a VersionedTarget corresponding to this Target, store it and # continue. versioned_target_deps.add(versioned_targets_by_target[dependency]) elif",
"invocation, and non-flat mode, where we invoke a compiler for each target, which",
"because those will already # reflect changes in their own deps. for dep",
"versioned_target_deps.update(versioned_target_deps_by_target[dependency]) else: # Otherwise, compute the VersionedTargets that correspond to this dependency's #",
"get_versioned_target_deps_for_target(versioned_target.target) return versioned_targets def needs_update(self, cache_key): return self._invalidator.needs_update(cache_key) def _order_target_list(self, targets): \"\"\"Orders the",
"flag determining whether the list of targets is currently valid. When invalidating a",
"and # continue. versioned_target_deps.add(versioned_targets_by_target[dependency]) elif dependency in versioned_target_deps_by_target: # Otherwise, see if we've",
"VersionedTargets, for use in hooking up VersionedTarget # dependencies below. versioned_targets_by_target[target] = versioned_target",
"in topological order, so when handling a target, this will already contain all",
"have the same cache manager. # TODO(ryan): the way VersionedTargets store their own",
"will not be # processed until a later phase. For example, if a",
"use in hooking up VersionedTarget # dependencies below. versioned_targets_by_target[target] = versioned_target # Having",
"if fprint is not None: dependency_keys.add(fprint) else: raise ValueError('Cannot calculate a cache_key for",
"= versioned_targets[0] cache_manager = first_target._cache_manager # Quick sanity check; all the versioned targets",
"are chosen to have roughly partition_size_hint sources. This is useful as a compromise",
"InvalidationCheck(all_vts, invalid_vts, partition_size_hint) def _sort_and_validate_targets(self, targets): \"\"\"Validate each target. Returns a topologically ordered",
"= self._invalidator.existing_hash(dep.id) # Note that fprint may be None here, indicating that the",
"the assignments above, as they are used in the parent's __init__. VersionedTargetSet.__init__(self, cache_manager,",
"the same underlying targets. E.g., VT1 is the combination of [vt1, vt2, vt3],",
"the computed result. versioned_target_deps_by_target[dependency] = get_versioned_target_deps_for_target( dependency) versioned_target_deps.update(versioned_target_deps_by_target[dependency]) # Return the VersionedTarget dependencies",
"in compliance with the License. # You may obtain a copy of the",
"that don't correspond to VersionedTargets themselves. versioned_target_deps_by_target = {} def get_versioned_target_deps_for_target(target): # For",
"def force_invalidate(self): self._cache_manager.force_invalidate(self) def __repr__(self): return \"VTS(%s. %d)\" % (','.join(target.id for target in",
"targets so that each group has roughly the same number of sources. versioned_targets",
"versioned_targets] # The following line is a no-op if cache_key was set in",
"to combine versioned targets %s and %s with different\" \" CacheManager instances: %s",
"of targets that are built together into a single artifact. \"\"\" @classmethod def",
"implemented. class InvalidationCheck(object): @classmethod def _partition_versioned_targets(cls, versioned_targets, partition_size_hint): \"\"\"Groups versioned targets so that",
"a cache_key for a dependency: %s' % dep) cache_key = self._key_for(target, dependency_keys) id_to_hash[target.id]",
"an earlier # round or because they came first in ordered_targets. if isinstance(dep,",
"of the CacheManager. for versioned_target in versioned_targets: if versioned_target._cache_manager != cache_manager: raise ValueError(\"Attempting",
"%s must support sources and does not.\" % target.id) self.target = target self.cache_key",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"1: # Too big. Close the current group without this vt and add",
"that target as a singleton. When checking the artifact cache, this can also",
"= [] self.total_sources = 0 current_group = VtGroup() def add_to_current_group(vt): current_group.vts.append(vt) current_group.total_sources +=",
"target, this can be used to represent that target as a singleton. When",
"if versioned_target._cache_manager != cache_manager: raise ValueError(\"Attempting to combine versioned targets %s and %s",
"= invalid_vts # Just the invalid targets, partitioned if so requested. self.invalid_vts_partitioned =",
"( BuildInvalidator, CacheKeyGenerator, NO_SOURCES, TARGET_SOURCES) from twitter.pants.base.target import Target from twitter.pants.targets import TargetWithSources",
"set() if self._invalidate_dependents and hasattr(target, 'dependencies'): # Note that we only need to",
"singleton VersionedTargetSet, and has links to VersionedTargets that the wrapped target depends on",
"1.5 * partition_size_hint and len(current_group.vts) > 1: # Too big. Close the current",
"_partition_versioned_targets(cls, versioned_targets, partition_size_hint): \"\"\"Groups versioned targets so that each group has roughly the",
"as pickle except ImportError: import pickle from twitter.pants import has_sources from twitter.pants.base.build_invalidator import",
"on either of these, depending on how they # are implemented. class InvalidationCheck(object):",
"order and, e.g., rebuild the invalid ones. \"\"\" all_vts = self._sort_and_validate_targets(targets) invalid_vts =",
"don't correspond to VersionedTargets themselves. versioned_target_deps_by_target = {} def get_versioned_target_deps_for_target(target): # For every",
"single artifact. \"\"\" @classmethod def from_versioned_targets(cls, versioned_targets): first_target = versioned_targets[0] cache_manager = first_target._cache_manager",
"cache_manager, versioned_targets): self._cache_manager = cache_manager self.versioned_targets = versioned_targets self.targets = [vt.target for vt",
"will store its corresponding VersionedTarget here. For # dependencies that don't correspond to",
"list of targets is currently valid. When invalidating a single target, this can",
"it # depends on, and use those. versioned_target_deps.update(versioned_target_deps_by_target[dependency]) else: # Otherwise, compute the",
"def _partition_versioned_targets(cls, versioned_targets, partition_size_hint): \"\"\"Groups versioned targets so that each group has roughly",
"the targets has changed and invalidates it if so. Returns a list of",
"to represent a list of targets that are built together into a single",
"def __init__(self, all_vts, invalid_vts, partition_size_hint=None): # All the targets, valid and invalid. self.all_vts",
"target, cache_key) # Add the new VersionedTarget to the list of computed VersionedTargets.",
"versioned targets should have the same cache manager. # TODO(ryan): the way VersionedTargets",
"a later phase. For example, if a codegen target depends on a #",
"the same cache manager. # TODO(ryan): the way VersionedTargets store their own links",
"targets)) return filter(targets.__contains__, reversed(InternalTarget.sort_targets(targets))) def _key_for(self, target, dependency_keys): def fingerprint_extra(sha): sha.update(self._extra_data) for key",
"first_target = versioned_targets[0] cache_manager = first_target._cache_manager # Quick sanity check; all the versioned",
"CacheManager instances: %s and %s\" % (first_target, versioned_target, cache_manager, versioned_target._cache_manager)) return cls(cache_manager, versioned_targets)",
"# dependencies below. versioned_targets_by_target[target] = versioned_target # Having created all applicable VersionedTargets, now",
"= versioned_targets self.targets = [vt.target for vt in versioned_targets] # The following line",
"{} # Map from id to current fingerprint of the target with that",
"cache_manager = first_target._cache_manager # Quick sanity check; all the versioned targets should have",
"no, some or all operations on either of these, depending on how they",
"@target. versioned_target = VersionedTarget(self, target, cache_key) # Add the new VersionedTarget to the",
"and invalid. self.all_vts = all_vts # All the targets, partitioned if so requested.",
"has_sources from twitter.pants.base.build_invalidator import ( BuildInvalidator, CacheKeyGenerator, NO_SOURCES, TARGET_SOURCES) from twitter.pants.base.target import Target",
"specific language governing permissions and # limitations under the License. # ================================================================================================== try:",
"objects (either valid or invalid). The returned sets 'cover' the input targets, possibly",
"round or because they came first in ordered_targets. if isinstance(dep, ExternalDependency): dependency_keys.add(dep.cache_key()) elif",
"def add_to_current_group(vt): current_group.vts.append(vt) current_group.total_sources += vt.num_sources def close_current_group(): if len(current_group.vts) > 0: new_vt",
"VersionedTarget here. For # dependencies that don't correspond to a VersionedTarget (e.g. pass-through",
"of computed VersionedTargets. versioned_targets.append(versioned_target) # Add to the mapping from Targets to VersionedTargets,",
"from twitter.pants import has_sources from twitter.pants.base.build_invalidator import ( BuildInvalidator, CacheKeyGenerator, NO_SOURCES, TARGET_SOURCES) from",
"TargetWithSources): raise ValueError(\"The target %s must support sources and does not.\" % target.id)",
"targets, partition_size_hint=None): \"\"\"Checks whether each of the targets has changed and invalidates it",
"single target, this can be used to represent that target as a singleton.",
"# dependencies that don't correspond to a VersionedTarget (e.g. pass-through dependency # wrappers),",
"self._cache_key_generator = cache_key_generator self._invalidate_dependents = invalidate_dependents self._extra_data = pickle.dumps(extra_data) # extra_data may be",
"raise ValueError(\"Attempting to combine versioned targets %s and %s with different\" \" CacheManager",
"a mapping from each target to its corresponding VersionedTarget. versioned_targets_by_target = {} #",
"if partition_size_hint else invalid_vts class CacheManager(object): \"\"\"Manages cache checks, updates and invalidation keeping",
"= 0 for vt in versioned_targets: add_to_current_group(vt) if current_group.total_sources > 1.5 * partition_size_hint",
"# Return the VersionedTarget dependencies that this target's VersionedTarget should depend on. return",
"# have been written out by the invalidator. fprint = self._invalidator.existing_hash(dep.id) # Note",
"depends on (after having resolved through any \"alias\" targets. \"\"\" def __init__(self, cache_manager,",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"cls(cache_manager, versioned_targets) def __init__(self, cache_manager, versioned_targets): self._cache_manager = cache_manager self.versioned_targets = versioned_targets self.targets",
"isinstance(dep, Target): fprint = id_to_hash.get(dep.id, None) if fprint is None: # It may",
"so that each group has roughly the same number of sources. versioned_targets is",
"do this for the immediate deps, because those will already # reflect changes",
"target depends on (after having resolved through any \"alias\" targets. \"\"\" def __init__(self,",
"import ExternalDependency from twitter.pants.targets.internal import InternalTarget class VersionedTargetSet(object): \"\"\"Represents a list of targets,",
"no-op if cache_key was set in the VersionedTarget __init__ method. self.cache_key = CacheKeyGenerator.combine_cache_keys([vt.cache_key",
"# -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"the License. # You may obtain a copy of the License in the",
"list of VersionedTargets that correspond to @targets. versioned_targets = [] # This will",
"close_current_group() add_to_current_group(vt) elif current_group.total_sources > partition_size_hint: close_current_group() close_current_group() # Close the last group,",
"current_group.vts = [] current_group.total_sources = 0 for vt in versioned_targets: add_to_current_group(vt) if current_group.total_sources",
"current_group.total_sources > 1.5 * partition_size_hint and len(current_group.vts) > 1: # Too big. Close",
"# Sort to ensure hashing in a consistent order. sha.update(key) return self._cache_key_generator.key_for_target( target,",
"invalidation statistics. Note that this is distinct from the ArtifactCache concept, and should",
"fingerprint_extra(sha): sha.update(self._extra_data) for key in sorted(dependency_keys): # Sort to ensure hashing in a",
"around the python outer scope problem. class VtGroup(object): def __init__(self): self.vts = []",
"we will store its corresponding VersionedTarget here. For # dependencies that don't correspond",
"partition_size_hint) if partition_size_hint else all_vts # Just the invalid targets. self.invalid_vts = invalid_vts",
"any \"alias\" targets. \"\"\" def __init__(self, cache_manager, target, cache_key): if not isinstance(target, TargetWithSources):",
"a dependency: %s' % dep) cache_key = self._key_for(target, dependency_keys) id_to_hash[target.id] = cache_key.hash #",
"in ordered_targets. if isinstance(dep, ExternalDependency): dependency_keys.add(dep.cache_key()) elif isinstance(dep, Target): fprint = id_to_hash.get(dep.id, None)",
"to lots of compiler startup overhead. A task can choose instead to build",
"def get_versioned_target_deps_for_target(target): # For every dependency of @target, we will store its corresponding",
"self.targets = [vt.target for vt in versioned_targets] # The following line is a",
"current_group.vts.pop() close_current_group() add_to_current_group(vt) elif current_group.total_sources > partition_size_hint: close_current_group() close_current_group() # Close the last",
"targets in this order, to ensure correctness if invalidate_dependents=True, # since we use",
"been processed, either in an earlier # round or because they came first",
"if a codegen target depends on a # library target (because the generated",
"into a single artifact. \"\"\" @classmethod def from_versioned_targets(cls, versioned_targets): first_target = versioned_targets[0] cache_manager",
"target in ordered_targets: dependency_keys = set() if self._invalidate_dependents and hasattr(target, 'dependencies'): # Note",
"dependency_keys.add(fprint) else: raise ValueError('Cannot calculate a cache_key for a dependency: %s' % dep)",
"sources. This is useful as a compromise between flat mode, where we build",
"new_vt = VersionedTargetSet.from_versioned_targets(current_group.vts) res.append(new_vt) current_group.vts = [] current_group.total_sources = 0 for vt in",
"all VersionedTargets to point to the VersionedTargets they depend on. for versioned_target in",
"dependency of @target, we will store its corresponding VersionedTarget here. For # dependencies",
"list of targets that are built together into a single artifact. \"\"\" @classmethod",
"vt: not vt.valid, all_vts) return InvalidationCheck(all_vts, invalid_vts, partition_size_hint) def _sort_and_validate_targets(self, targets): \"\"\"Validate each",
"VersionedTargetSet.\"\"\" for vt in vts.versioned_targets: self._invalidator.force_invalidate(vt.cache_key) vt.valid = False self._invalidator.force_invalidate(vts.cache_key) vts.valid = False",
"(first_target, versioned_target, cache_manager, versioned_target._cache_manager)) return cls(cache_manager, versioned_targets) def __init__(self, cache_manager, versioned_targets): self._cache_manager =",
"compute later cache keys in this case. ordered_targets = self._order_target_list(targets) # This will",
"add it to the next one. current_group.vts.pop() close_current_group() add_to_current_group(vt) elif current_group.total_sources > partition_size_hint:",
"ValueError(\"Attempting to combine versioned targets %s and %s with different\" \" CacheManager instances:",
"for dependency in dep.resolve(): if dependency in versioned_targets_by_target: # If there exists a",
"= {} def get_versioned_target_deps_for_target(target): # For every dependency of @target, we will store",
"each target. Returns a topologically ordered set of VersionedTargets, each representing one input",
"its deps (in # this round). id_to_hash = {} for target in ordered_targets:",
"only_externaldeps): self._cache_key_generator = cache_key_generator self._invalidate_dependents = invalidate_dependents self._extra_data = pickle.dumps(extra_data) # extra_data may",
"# this round). id_to_hash = {} for target in ordered_targets: dependency_keys = set()",
"return self._invalidator.needs_update(cache_key) def _order_target_list(self, targets): \"\"\"Orders the targets topologically, from least to most",
"targets %s and %s with different\" \" CacheManager instances: %s and %s\" %",
"rebuild the invalid ones. \"\"\" all_vts = self._sort_and_validate_targets(targets) invalid_vts = filter(lambda vt: not",
"current_group.total_sources += vt.num_sources def close_current_group(): if len(current_group.vts) > 0: new_vt = VersionedTargetSet.from_versioned_targets(current_group.vts) res.append(new_vt)",
"VersionedTargets, now we build the VersionedTarget dependency # graph, looking through targets that",
"be None. self._sources = NO_SOURCES if only_externaldeps else TARGET_SOURCES self._invalidator = BuildInvalidator(build_invalidator_dir) def",
"a list of VersionedTargetSet objects (either valid or invalid). The returned sets 'cover'",
"self.total_sources = 0 current_group = VtGroup() def add_to_current_group(vt): current_group.vts.append(vt) current_group.total_sources += vt.num_sources def",
"self.cache_key = cache_key # Must come after the assignments above, as they are",
"-------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"own deps. for dep in target.dependencies: # We rely on the fact that",
"for them. versioned_target_deps = set([]) if hasattr(target, 'dependencies'): for dep in target.dependencies: for",
"and # limitations under the License. # ================================================================================================== try: import cPickle as pickle",
"deps, because those will already # reflect changes in their own deps. for",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"compiler invocation, and non-flat mode, where we invoke a compiler for each target,",
"vt4, vt5, vt6, ...]. Returns a list of VersionedTargetSet objects, e.g., [VT1, VT2,",
"versioned_targets: add_to_current_group(vt) if current_group.total_sources > 1.5 * partition_size_hint and len(current_group.vts) > 1: #",
"representing the same underlying targets. E.g., VT1 is the combination of [vt1, vt2,",
"close_current_group(): if len(current_group.vts) > 0: new_vt = VersionedTargetSet.from_versioned_targets(current_group.vts) res.append(new_vt) current_group.vts = [] current_group.total_sources",
"need to do this for the immediate deps, because those will already #",
"vt in versioned_targets: add_to_current_group(vt) if current_group.total_sources > 1.5 * partition_size_hint and len(current_group.vts) >",
"1 if self.valid else 0) class VersionedTarget(VersionedTargetSet): \"\"\"This class represents a singleton VersionedTargetSet,",
"current_group.total_sources = 0 for vt in versioned_targets: add_to_current_group(vt) if current_group.total_sources > 1.5 *",
"change and invalidation statistics. Note that this is distinct from the ArtifactCache concept,",
"deps. for dep in target.dependencies: # We rely on the fact that any",
"on. return versioned_target_deps # Initialize all VersionedTargets to point to the VersionedTargets they",
"ValueError(\"The target %s must support sources and does not.\" % target.id) self.target =",
"least to most dependent.\"\"\" targets = set(filter(has_sources, targets)) return filter(targets.__contains__, reversed(InternalTarget.sort_targets(targets))) def _key_for(self,",
"where we invoke a compiler for each target, which may lead to lots",
"[self]) self.id = target.id self.dependencies = set() # The result of calling check()",
"in an earlier # round or because they came first in ordered_targets. if",
"required by applicable law or agreed to in writing, software # distributed under",
"for each target, which may lead to lots of compiler startup overhead. A",
"that id. We update this as we iterate, # in topological order, so",
"first in ordered_targets. if isinstance(dep, ExternalDependency): dependency_keys.add(dep.cache_key()) elif isinstance(dep, Target): fprint = id_to_hash.get(dep.id,",
"track of basic change and invalidation statistics. Note that this is distinct from",
"round). id_to_hash = {} for target in ordered_targets: dependency_keys = set() if self._invalidate_dependents",
"used to represent that target as a singleton. When checking the artifact cache,",
"# Otherwise, see if we've already resolved this dependency to the VersionedTargets it",
"through any \"alias\" targets. \"\"\" def __init__(self, cache_manager, target, cache_key): if not isinstance(target,",
"cache, this can also be used to represent a list of targets that",
"the python outer scope problem. class VtGroup(object): def __init__(self): self.vts = [] self.total_sources",
"will already # reflect changes in their own deps. for dep in target.dependencies:",
"up VersionedTarget # dependencies below. versioned_targets_by_target[target] = versioned_target # Having created all applicable",
"line is a no-op if cache_key was set in the VersionedTarget __init__ method.",
"lots of compiler startup overhead. A task can choose instead to build one",
"Initialize all VersionedTargets to point to the VersionedTargets they depend on. for versioned_target",
"already resolved this dependency to the VersionedTargets it # depends on, and use",
"0) class VersionedTarget(VersionedTargetSet): \"\"\"This class represents a singleton VersionedTargetSet, and has links to",
"extra_data may be None. self._sources = NO_SOURCES if only_externaldeps else TARGET_SOURCES self._invalidator =",
"# Map from id to current fingerprint of the target with that id.",
"TargetWithSources from twitter.pants.targets.external_dependency import ExternalDependency from twitter.pants.targets.internal import InternalTarget class VersionedTargetSet(object): \"\"\"Represents a",
"the ArtifactCache concept, and should probably be renamed. \"\"\" def __init__(self, cache_key_generator, build_invalidator_dir,",
"__init__(self): self.vts = [] self.total_sources = 0 current_group = VtGroup() def add_to_current_group(vt): current_group.vts.append(vt)",
"versioned_targets[0] cache_manager = first_target._cache_manager # Quick sanity check; all the versioned targets should",
"VT2, VT3, ...] representing the same underlying targets. E.g., VT1 is the combination",
"number of sources. versioned_targets is a list of VersionedTarget objects [vt1, vt2, vt3,",
"fprint may be None here, indicating that the dependency will not be #",
"can choose instead to build one group at a time. \"\"\" res =",
"%s' % dep) cache_key = self._key_for(target, dependency_keys) id_to_hash[target.id] = cache_key.hash # Create a",
"so requested. self.all_vts_partitioned = self._partition_versioned_targets( all_vts, partition_size_hint) if partition_size_hint else all_vts # Just",
"as a singleton. When checking the artifact cache, this can also be used",
"processed until a later phase. For example, if a codegen target depends on",
"may have been processed in a prior round, and therefore the fprint should",
"their actual dependencies and find VersionedTargets for them. versioned_target_deps = set([]) if hasattr(target,",
"VersionedTargetSet(object): \"\"\"Represents a list of targets, a corresponding CacheKey, and a flag determining",
"from twitter.pants.targets.internal import InternalTarget class VersionedTargetSet(object): \"\"\"Represents a list of targets, a corresponding",
"BuildInvalidator(build_invalidator_dir) def update(self, vts): \"\"\"Mark a changed or invalidated VersionedTargetSet as successfully processed.\"\"\"",
"to its corresponding VersionedTarget. versioned_targets_by_target = {} # Map from id to current",
"twitter.pants.targets.internal import InternalTarget class VersionedTargetSet(object): \"\"\"Represents a list of targets, a corresponding CacheKey,",
"different\" \" CacheManager instances: %s and %s\" % (first_target, versioned_target, cache_manager, versioned_target._cache_manager)) return",
"corresponding to @target. versioned_target = VersionedTarget(self, target, cache_key) # Add the new VersionedTarget",
"CacheManager instance # feels hacky; see if there's a cleaner way for callers",
"= self.cache_key.num_sources self.valid = not cache_manager.needs_update(self.cache_key) def update(self): self._cache_manager.update(self) def force_invalidate(self): self._cache_manager.force_invalidate(self) def",
"in the parent's __init__. VersionedTargetSet.__init__(self, cache_manager, [self]) self.id = target.id self.dependencies = set()",
"must check the targets in this order, to ensure correctness if invalidate_dependents=True, #",
"order. The caller can inspect these in order and, e.g., rebuild the invalid",
"self._cache_manager.update(self) def force_invalidate(self): self._cache_manager.force_invalidate(self) def __repr__(self): return \"VTS(%s. %d)\" % (','.join(target.id for target",
"you may not use this work except in compliance with the License. #",
"that the dependency will not be # processed until a later phase. For",
"invalid_vts = filter(lambda vt: not vt.valid, all_vts) return InvalidationCheck(all_vts, invalid_vts, partition_size_hint) def _sort_and_validate_targets(self,",
"library target (because the generated code needs that library). if fprint is not",
"self.cache_key.num_sources self.valid = not cache_manager.needs_update(self.cache_key) def update(self): self._cache_manager.update(self) def force_invalidate(self): self._cache_manager.force_invalidate(self) def __repr__(self):",
"without this vt and add it to the next one. current_group.vts.pop() close_current_group() add_to_current_group(vt)",
"or at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"None: dependency_keys.add(fprint) else: raise ValueError('Cannot calculate a cache_key for a dependency: %s' %",
"partition_size_hint else all_vts # Just the invalid targets. self.invalid_vts = invalid_vts # Just",
"same underlying targets. E.g., VT1 is the combination of [vt1, vt2, vt3], VT2",
"and invalidates it if so. Returns a list of VersionedTargetSet objects (either valid",
"from id to current fingerprint of the target with that id. We update",
"All the targets, valid and invalid. self.all_vts = all_vts # All the targets,",
"depend on. for versioned_target in versioned_targets: versioned_target.dependencies = get_versioned_target_deps_for_target(versioned_target.target) return versioned_targets def needs_update(self,",
"vts.versioned_targets: self._invalidator.update(vt.cache_key) vt.valid = True self._invalidator.update(vts.cache_key) vts.valid = True def force_invalidate(self, vts): \"\"\"Force",
"return filter(targets.__contains__, reversed(InternalTarget.sort_targets(targets))) def _key_for(self, target, dependency_keys): def fingerprint_extra(sha): sha.update(self._extra_data) for key in",
"self._extra_data = pickle.dumps(extra_data) # extra_data may be None. self._sources = NO_SOURCES if only_externaldeps",
"is distinct from the ArtifactCache concept, and should probably be renamed. \"\"\" def",
"as they are used in the parent's __init__. VersionedTargetSet.__init__(self, cache_manager, [self]) self.id =",
"this work except in compliance with the License. # You may obtain a",
"self.targets), 1 if self.valid else 0) class VersionedTarget(VersionedTargetSet): \"\"\"This class represents a singleton",
"ExternalDependency from twitter.pants.targets.internal import InternalTarget class VersionedTargetSet(object): \"\"\"Represents a list of targets, a",
"Add to the mapping from Targets to VersionedTargets, for use in hooking up",
"and hasattr(target, 'dependencies'): # Note that we only need to do this for",
"When invalidating a single target, this can be used to represent that target",
"License for the specific language governing permissions and # limitations under the License.",
"__init__(self, cache_key_generator, build_invalidator_dir, invalidate_dependents, extra_data, only_externaldeps): self._cache_key_generator = cache_key_generator self._invalidate_dependents = invalidate_dependents self._extra_data",
"Returns a topologically ordered set of VersionedTargets, each representing one input target. \"\"\"",
"versioned_target._cache_manager != cache_manager: raise ValueError(\"Attempting to combine versioned targets %s and %s with",
"all_vts # Just the invalid targets. self.invalid_vts = invalid_vts # Just the invalid",
"a single compiler invocation, and non-flat mode, where we invoke a compiler for",
"\"\"\"This class represents a singleton VersionedTargetSet, and has links to VersionedTargets that the",
"probably be renamed. \"\"\" def __init__(self, cache_key_generator, build_invalidator_dir, invalidate_dependents, extra_data, only_externaldeps): self._cache_key_generator =",
"The result of calling check() on a CacheManager. # Each member is a",
"{} for target in ordered_targets: dependency_keys = set() if self._invalidate_dependents and hasattr(target, 'dependencies'):",
"in target.dependencies: for dependency in dep.resolve(): if dependency in versioned_targets_by_target: # If there",
"keys to compute later cache keys in this case. ordered_targets = self._order_target_list(targets) #",
"inspect these in order and, e.g., rebuild the invalid ones. \"\"\" all_vts =",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"the invalid ones. \"\"\" all_vts = self._sort_and_validate_targets(targets) invalid_vts = filter(lambda vt: not vt.valid,",
"in writing, software # distributed under the License is distributed on an \"AS",
"handle awareness of the CacheManager. for versioned_target in versioned_targets: if versioned_target._cache_manager != cache_manager:",
"partitioned if so requested. self.invalid_vts_partitioned = self._partition_versioned_targets( invalid_vts, partition_size_hint) if partition_size_hint else invalid_vts",
"update this as we iterate, # in topological order, so when handling a",
"mode, where we invoke a compiler for each target, which may lead to",
"fact that any deps have already been processed, either in an earlier #",
"may be None. self._sources = NO_SOURCES if only_externaldeps else TARGET_SOURCES self._invalidator = BuildInvalidator(build_invalidator_dir)",
"objects [vt1, vt2, vt3, vt4, vt5, vt6, ...]. Returns a list of VersionedTargetSet",
"in a single compiler invocation, and non-flat mode, where we invoke a compiler",
"current_group = VtGroup() def add_to_current_group(vt): current_group.vts.append(vt) current_group.total_sources += vt.num_sources def close_current_group(): if len(current_group.vts)",
"concept, and should probably be renamed. \"\"\" def __init__(self, cache_key_generator, build_invalidator_dir, invalidate_dependents, extra_data,",
"= self._key_for(target, dependency_keys) id_to_hash[target.id] = cache_key.hash # Create a VersionedTarget corresponding to @target.",
"this can also be used to represent a list of targets that are",
"cache_key = self._key_for(target, dependency_keys) id_to_hash[target.id] = cache_key.hash # Create a VersionedTarget corresponding to",
"on, and use those. versioned_target_deps.update(versioned_target_deps_by_target[dependency]) else: # Otherwise, compute the VersionedTargets that correspond",
"only need to do this for the immediate deps, because those will already",
"partition_size_hint=None): # All the targets, valid and invalid. self.all_vts = all_vts # All",
"a time. \"\"\" res = [] # Hack around the python outer scope",
"came first in ordered_targets. if isinstance(dep, ExternalDependency): dependency_keys.add(dep.cache_key()) elif isinstance(dep, Target): fprint =",
"target.id) self.target = target self.cache_key = cache_key # Must come after the assignments",
"that any deps have already been processed, either in an earlier # round",
"current fingerprint of the target with that id. We update this as we",
"@classmethod def from_versioned_targets(cls, versioned_targets): first_target = versioned_targets[0] cache_manager = first_target._cache_manager # Quick sanity",
"# Add to the mapping from Targets to VersionedTargets, for use in hooking",
"\"\"\"Orders the targets topologically, from least to most dependent.\"\"\" targets = set(filter(has_sources, targets))",
"cache and use the computed result. versioned_target_deps_by_target[dependency] = get_versioned_target_deps_for_target( dependency) versioned_target_deps.update(versioned_target_deps_by_target[dependency]) # Return",
"This will be a list of VersionedTargets that correspond to @targets. versioned_targets =",
"partition_size_hint=None): \"\"\"Checks whether each of the targets has changed and invalidates it if",
"either of these, depending on how they # are implemented. class InvalidationCheck(object): @classmethod",
"# processed until a later phase. For example, if a codegen target depends",
"will resolve their actual dependencies and find VersionedTargets for them. versioned_target_deps = set([])",
"build the VersionedTarget dependency # graph, looking through targets that don't correspond to",
"group, if any. return res def __init__(self, all_vts, invalid_vts, partition_size_hint=None): # All the",
"first_target._cache_manager # Quick sanity check; all the versioned targets should have the same",
"correspond to a VersionedTarget (e.g. pass-through dependency # wrappers), we will resolve their",
"here, indicating that the dependency will not be # processed until a later",
"target, this will already contain all its deps (in # this round). id_to_hash",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"def __init__(self, cache_manager, target, cache_key): if not isinstance(target, TargetWithSources): raise ValueError(\"The target %s",
"versioned_targets): self._cache_manager = cache_manager self.versioned_targets = versioned_targets self.targets = [vt.target for vt in",
"the LICENSE file, or at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"# # Unless required by applicable law or agreed to in writing, software",
"(in # this round). id_to_hash = {} for target in ordered_targets: dependency_keys =",
"VersionedTargets that the wrapped target depends on (after having resolved through any \"alias\"",
"express or implied. # See the License for the specific language governing permissions",
"from each target to its corresponding VersionedTarget. versioned_targets_by_target = {} # Map from",
"flat mode, where we build all targets in a single compiler invocation, and",
"either express or implied. # See the License for the specific language governing",
"\"alias\" targets. \"\"\" def __init__(self, cache_manager, target, cache_key): if not isinstance(target, TargetWithSources): raise",
"2012 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0",
"if len(current_group.vts) > 0: new_vt = VersionedTargetSet.from_versioned_targets(current_group.vts) res.append(new_vt) current_group.vts = [] current_group.total_sources =",
"use earlier cache keys to compute later cache keys in this case. ordered_targets",
"in self.targets), 1 if self.valid else 0) class VersionedTarget(VersionedTargetSet): \"\"\"This class represents a",
"\"\"\" all_vts = self._sort_and_validate_targets(targets) invalid_vts = filter(lambda vt: not vt.valid, all_vts) return InvalidationCheck(all_vts,",
"ordered_targets = self._order_target_list(targets) # This will be a list of VersionedTargets that correspond",
"this vt and add it to the next one. current_group.vts.pop() close_current_group() add_to_current_group(vt) elif",
"built together into a single artifact. \"\"\" @classmethod def from_versioned_targets(cls, versioned_targets): first_target =",
"we've already resolved this dependency to the VersionedTargets it # depends on, and",
"should have the same cache manager. # TODO(ryan): the way VersionedTargets store their",
"invalid_vts, partition_size_hint) def _sort_and_validate_targets(self, targets): \"\"\"Validate each target. Returns a topologically ordered set",
"the last group, if any. return res def __init__(self, all_vts, invalid_vts, partition_size_hint=None): #",
"cache_manager, target, cache_key): if not isinstance(target, TargetWithSources): raise ValueError(\"The target %s must support",
"in a prior round, and therefore the fprint should # have been written",
"...] representing the same underlying targets. E.g., VT1 is the combination of [vt1,",
"versioned_target # Having created all applicable VersionedTargets, now we build the VersionedTarget dependency",
"to VersionedTargets that the wrapped target depends on (after having resolved through any",
"# dependencies, cache and use the computed result. versioned_target_deps_by_target[dependency] = get_versioned_target_deps_for_target( dependency) versioned_target_deps.update(versioned_target_deps_by_target[dependency])",
"dependencies, cache and use the computed result. versioned_target_deps_by_target[dependency] = get_versioned_target_deps_for_target( dependency) versioned_target_deps.update(versioned_target_deps_by_target[dependency]) #",
"invalidator. fprint = self._invalidator.existing_hash(dep.id) # Note that fprint may be None here, indicating",
"TARGET_SOURCES) from twitter.pants.base.target import Target from twitter.pants.targets import TargetWithSources from twitter.pants.targets.external_dependency import ExternalDependency",
"return InvalidationCheck(all_vts, invalid_vts, partition_size_hint) def _sort_and_validate_targets(self, targets): \"\"\"Validate each target. Returns a topologically",
"from twitter.pants.targets.external_dependency import ExternalDependency from twitter.pants.targets.internal import InternalTarget class VersionedTargetSet(object): \"\"\"Represents a list",
"this dependency to the VersionedTargets it # depends on, and use those. versioned_target_deps.update(versioned_target_deps_by_target[dependency])",
"VersionedTargets that correspond to @targets. versioned_targets = [] # This will be a",
"computed VersionedTargets. versioned_targets.append(versioned_target) # Add to the mapping from Targets to VersionedTargets, for",
"The new versioned targets are chosen to have roughly partition_size_hint sources. This is",
"partition_size_hint else invalid_vts class CacheManager(object): \"\"\"Manages cache checks, updates and invalidation keeping track",
"some or all operations on either of these, depending on how they #",
"and non-flat mode, where we invoke a compiler for each target, which may",
"VersionedTargetSet objects, e.g., [VT1, VT2, VT3, ...] representing the same underlying targets. E.g.,",
"set([]) if hasattr(target, 'dependencies'): for dep in target.dependencies: for dependency in dep.resolve(): if",
"successfully processed.\"\"\" for vt in vts.versioned_targets: self._invalidator.update(vt.cache_key) vt.valid = True self._invalidator.update(vts.cache_key) vts.valid =",
"to a VersionedTarget (e.g. pass-through dependency # wrappers), we will resolve their actual",
"pass-through dependency # wrappers), we will resolve their actual dependencies and find VersionedTargets",
"depending on how they # are implemented. class InvalidationCheck(object): @classmethod def _partition_versioned_targets(cls, versioned_targets,",
"\"VTS(%s. %d)\" % (','.join(target.id for target in self.targets), 1 if self.valid else 0)",
"in vts.versioned_targets: self._invalidator.update(vt.cache_key) vt.valid = True self._invalidator.update(vts.cache_key) vts.valid = True def force_invalidate(self, vts):",
"twitter.pants.targets.external_dependency import ExternalDependency from twitter.pants.targets.internal import InternalTarget class VersionedTargetSet(object): \"\"\"Represents a list of",
"is a no-op if cache_key was set in the VersionedTarget __init__ method. self.cache_key",
"a codegen target depends on a # library target (because the generated code",
"a corresponding CacheKey, and a flag determining whether the list of targets is",
"topological order. # Tasks may need to perform no, some or all operations",
"for the immediate deps, because those will already # reflect changes in their",
"= set([]) if hasattr(target, 'dependencies'): for dep in target.dependencies: for dependency in dep.resolve():",
"a flag determining whether the list of targets is currently valid. When invalidating",
"already # reflect changes in their own deps. for dep in target.dependencies: #",
"may lead to lots of compiler startup overhead. A task can choose instead",
"in this case. ordered_targets = self._order_target_list(targets) # This will be a list of",
"Target, store it and # continue. versioned_target_deps.add(versioned_targets_by_target[dependency]) elif dependency in versioned_target_deps_by_target: # Otherwise,",
"from Targets to VersionedTargets, for use in hooking up VersionedTarget # dependencies below.",
"\"\"\"Manages cache checks, updates and invalidation keeping track of basic change and invalidation",
"this is distinct from the ArtifactCache concept, and should probably be renamed. \"\"\"",
"versioned_targets.append(versioned_target) # Add to the mapping from Targets to VersionedTargets, for use in",
"a copy of the License in the LICENSE file, or at: # #",
"partition_size_hint sources. This is useful as a compromise between flat mode, where we",
"out by the invalidator. fprint = self._invalidator.existing_hash(dep.id) # Note that fprint may be",
"same number of sources. versioned_targets is a list of VersionedTarget objects [vt1, vt2,",
"return res def __init__(self, all_vts, invalid_vts, partition_size_hint=None): # All the targets, valid and",
"if any. return res def __init__(self, all_vts, invalid_vts, partition_size_hint=None): # All the targets,",
"class CacheManager(object): \"\"\"Manages cache checks, updates and invalidation keeping track of basic change",
"invalid_vts # Just the invalid targets, partitioned if so requested. self.invalid_vts_partitioned = self._partition_versioned_targets(",
"\"\"\"Validate each target. Returns a topologically ordered set of VersionedTargets, each representing one",
"!= cache_manager: raise ValueError(\"Attempting to combine versioned targets %s and %s with different\"",
"vt3], VT2 is the combination of [vt4, vt5] and VT3 is [vt6]. The",
"we invoke a compiler for each target, which may lead to lots of",
"also be used to represent a list of targets that are built together",
"processed, either in an earlier # round or because they came first in",
"must support sources and does not.\" % target.id) self.target = target self.cache_key =",
"in their own deps. for dep in target.dependencies: # We rely on the",
"may need to perform no, some or all operations on either of these,",
"\"\"\" # We must check the targets in this order, to ensure correctness",
"this Target, store it and # continue. versioned_target_deps.add(versioned_targets_by_target[dependency]) elif dependency in versioned_target_deps_by_target: #",
"target. \"\"\" # We must check the targets in this order, to ensure",
"links to VersionedTargets that the wrapped target depends on (after having resolved through",
"This will be a mapping from each target to its corresponding VersionedTarget. versioned_targets_by_target",
"to a single CacheManager instance # feels hacky; see if there's a cleaner",
"combine versioned targets %s and %s with different\" \" CacheManager instances: %s and",
"fprint = id_to_hash.get(dep.id, None) if fprint is None: # It may have been",
"for a dependency: %s' % dep) cache_key = self._key_for(target, dependency_keys) id_to_hash[target.id] = cache_key.hash",
"= invalidate_dependents self._extra_data = pickle.dumps(extra_data) # extra_data may be None. self._sources = NO_SOURCES",
"mode, where we build all targets in a single compiler invocation, and non-flat",
"since we use earlier cache keys to compute later cache keys in this",
"[] self.total_sources = 0 current_group = VtGroup() def add_to_current_group(vt): current_group.vts.append(vt) current_group.total_sources += vt.num_sources",
"between flat mode, where we build all targets in a single compiler invocation,",
"elif isinstance(dep, Target): fprint = id_to_hash.get(dep.id, None) if fprint is None: # It",
"of @target, we will store its corresponding VersionedTarget here. For # dependencies that",
"for dep in target.dependencies: for dependency in dep.resolve(): if dependency in versioned_targets_by_target: #",
"= VersionedTarget(self, target, cache_key) # Add the new VersionedTarget to the list of",
"depends on a # library target (because the generated code needs that library).",
"versioned_targets def needs_update(self, cache_key): return self._invalidator.needs_update(cache_key) def _order_target_list(self, targets): \"\"\"Orders the targets topologically,",
"Returns a list of VersionedTargetSet objects, e.g., [VT1, VT2, VT3, ...] representing the",
"corresponding VersionedTarget here. For # dependencies that don't correspond to a VersionedTarget (e.g.",
"a list of VersionedTargets that correspond to @targets. versioned_targets = [] # This",
"else invalid_vts class CacheManager(object): \"\"\"Manages cache checks, updates and invalidation keeping track of",
"None: # It may have been processed in a prior round, and therefore",
"Having created all applicable VersionedTargets, now we build the VersionedTarget dependency # graph,",
"NO_SOURCES if only_externaldeps else TARGET_SOURCES self._invalidator = BuildInvalidator(build_invalidator_dir) def update(self, vts): \"\"\"Mark a",
"\" CacheManager instances: %s and %s\" % (first_target, versioned_target, cache_manager, versioned_target._cache_manager)) return cls(cache_manager,",
"deps (in # this round). id_to_hash = {} for target in ordered_targets: dependency_keys",
"except in compliance with the License. # You may obtain a copy of",
"a list of targets that are built together into a single artifact. \"\"\"",
"that correspond to this dependency's # dependencies, cache and use the computed result.",
"Target from twitter.pants.targets import TargetWithSources from twitter.pants.targets.external_dependency import ExternalDependency from twitter.pants.targets.internal import InternalTarget",
"the new VersionedTarget to the list of computed VersionedTargets. versioned_targets.append(versioned_target) # Add to",
"= cache_key # Must come after the assignments above, as they are used",
"dependency's # dependencies, cache and use the computed result. versioned_target_deps_by_target[dependency] = get_versioned_target_deps_for_target( dependency)",
"\"\"\" @classmethod def from_versioned_targets(cls, versioned_targets): first_target = versioned_targets[0] cache_manager = first_target._cache_manager # Quick",
"self._order_target_list(targets) # This will be a list of VersionedTargets that correspond to @targets.",
"vt2, vt3, vt4, vt5, vt6, ...]. Returns a list of VersionedTargetSet objects, e.g.,",
"NO_SOURCES, TARGET_SOURCES) from twitter.pants.base.target import Target from twitter.pants.targets import TargetWithSources from twitter.pants.targets.external_dependency import",
"one group at a time. \"\"\" res = [] # Hack around the",
"False self._invalidator.force_invalidate(vts.cache_key) vts.valid = False def check(self, targets, partition_size_hint=None): \"\"\"Checks whether each of",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"target, which may lead to lots of compiler startup overhead. A task can",
"new versioned targets are chosen to have roughly partition_size_hint sources. This is useful",
"def fingerprint_extra(sha): sha.update(self._extra_data) for key in sorted(dependency_keys): # Sort to ensure hashing in",
"= id_to_hash.get(dep.id, None) if fprint is None: # It may have been processed",
"% (','.join(target.id for target in self.targets), 1 if self.valid else 0) class VersionedTarget(VersionedTargetSet):",
"ones. \"\"\" all_vts = self._sort_and_validate_targets(targets) invalid_vts = filter(lambda vt: not vt.valid, all_vts) return",
"in ordered_targets: dependency_keys = set() if self._invalidate_dependents and hasattr(target, 'dependencies'): # Note that",
"exists a VersionedTarget corresponding to this Target, store it and # continue. versioned_target_deps.add(versioned_targets_by_target[dependency])",
"is the combination of [vt1, vt2, vt3], VT2 is the combination of [vt4,",
"= first_target._cache_manager # Quick sanity check; all the versioned targets should have the",
"= True def force_invalidate(self, vts): \"\"\"Force invalidation of a VersionedTargetSet.\"\"\" for vt in",
"= target self.cache_key = cache_key # Must come after the assignments above, as",
"# Tasks may need to perform no, some or all operations on either",
"= CacheKeyGenerator.combine_cache_keys([vt.cache_key for vt in versioned_targets]) self.num_sources = self.cache_key.num_sources self.valid = not cache_manager.needs_update(self.cache_key)",
"themselves. versioned_target_deps_by_target = {} def get_versioned_target_deps_for_target(target): # For every dependency of @target, we",
"if not isinstance(target, TargetWithSources): raise ValueError(\"The target %s must support sources and does",
"[] # Hack around the python outer scope problem. class VtGroup(object): def __init__(self):",
"def check(self, targets, partition_size_hint=None): \"\"\"Checks whether each of the targets has changed and",
"perform no, some or all operations on either of these, depending on how",
"targets, partitioned if so requested. self.all_vts_partitioned = self._partition_versioned_targets( all_vts, partition_size_hint) if partition_size_hint else",
"the artifact cache, this can also be used to represent a list of",
"phase. For example, if a codegen target depends on a # library target",
"# For every dependency of @target, we will store its corresponding VersionedTarget here.",
"for vt in versioned_targets] # The following line is a no-op if cache_key",
"# All the targets, partitioned if so requested. self.all_vts_partitioned = self._partition_versioned_targets( all_vts, partition_size_hint)",
"same cache manager. # TODO(ryan): the way VersionedTargets store their own links to",
"the wrapped target depends on (after having resolved through any \"alias\" targets. \"\"\"",
"VtGroup() def add_to_current_group(vt): current_group.vts.append(vt) current_group.total_sources += vt.num_sources def close_current_group(): if len(current_group.vts) > 0:",
"that are built together into a single artifact. \"\"\" @classmethod def from_versioned_targets(cls, versioned_targets):",
"of sources. versioned_targets is a list of VersionedTarget objects [vt1, vt2, vt3, vt4,",
"computed result. versioned_target_deps_by_target[dependency] = get_versioned_target_deps_for_target( dependency) versioned_target_deps.update(versioned_target_deps_by_target[dependency]) # Return the VersionedTarget dependencies that",
"all operations on either of these, depending on how they # are implemented.",
"partition_size_hint and len(current_group.vts) > 1: # Too big. Close the current group without",
"__init__ method. self.cache_key = CacheKeyGenerator.combine_cache_keys([vt.cache_key for vt in versioned_targets]) self.num_sources = self.cache_key.num_sources self.valid",
"get_versioned_target_deps_for_target(target): # For every dependency of @target, we will store its corresponding VersionedTarget",
"dependency: %s' % dep) cache_key = self._key_for(target, dependency_keys) id_to_hash[target.id] = cache_key.hash # Create",
"compiler startup overhead. A task can choose instead to build one group at",
"VT3, ...] representing the same underlying targets. E.g., VT1 is the combination of",
"Close the last group, if any. return res def __init__(self, all_vts, invalid_vts, partition_size_hint=None):",
"VersionedTarget should depend on. return versioned_target_deps # Initialize all VersionedTargets to point to",
"= cache_key_generator self._invalidate_dependents = invalidate_dependents self._extra_data = pickle.dumps(extra_data) # extra_data may be None."
] |
[
"StringIO() ValueSource.write(value_iter, output_stream=s) received = s.getvalue() s.close() jrec = json.loads(received) expect_to_find = {",
"case the provisions of the GPL or the LGPL are applicable instead #",
"suffix='.json', delete=False) name = '/tmp/test.json' import functools opener = functools.partial(open, name, 'w') c1",
"use_admin_controls=True, use_auto_help=False, app_name='/tmp/test', app_version='0', app_description='', argv_source=[]) c1.write_conf('json', opener) d1 = {'bbb': 88} d2",
"GPL or the LGPL are applicable instead # of those above. If you",
"opener) d1 = {'bbb': 88} d2 = {'bbb': '-99'} try: with open(name) as",
"the specific language governing rights and limitations under the # License. # #",
"file under # the terms of any one of the MPL, the GPL",
"to the Mozilla Public License Version # 1.1 (the \"License\"); you may not",
"config_manager.ConfigurationManager((j,), (d1, d2), use_admin_controls=True, use_auto_help=False, argv_source=[]) config = c2.get_config() self.assertEqual(config.aaa, expected_date) self.assertEqual(config.bbb, -99)",
"of the Original Code is # Mozilla Foundation # Portions created by the",
"to allow others to # use your version of this file under the",
"n.add_aggregation('bbb_minus_one', bbb_minus_one) #t = tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) name = '/tmp/test.json' import functools opener",
"***** END LICENSE BLOCK ***** import unittest import os import json import tempfile",
"this file are subject to the Mozilla Public License Version # 1.1 (the",
"app_description='', argv_source=[]) c1.write_conf('json', opener) d1 = {'bbb': 88} d2 = {'bbb': '-99'} try:",
"configman.value_sources.for_json import ValueSource #from ..value_sources.for_json import ValueSource def bbb_minus_one(config, local_config, args): return config.bbb",
"of those above. If you wish to allow use of your version of",
"use_auto_help=False, app_name='/tmp/test', app_version='0', app_description='', argv_source=[]) c1.write_conf('json', opener) d1 = {'bbb': 88} d2 =",
"def test_for_json_basics(self): tmp_filename = os.path.join(tempfile.gettempdir(), 'test.json') j = {'fred': 'wilma', 'number': 23, }",
"the # License. # # The Original Code is configman # # The",
"bbb_minus_one) #t = tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) name = '/tmp/test.json' import functools opener =",
"a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) def value_iter(): yield 'aaa', 'aaa', n.aaa s = StringIO()",
"} for key, value in expect_to_find.items(): self.assertEqual(jrec['aaa'][key], value) def test_json_round_trip(self): n = config_manager.Namespace(doc='top')",
"Code is # Mozilla Foundation # Portions created by the Initial Developer are",
"terms of # either the GNU General Public License Version 2 or later",
"jvs = ValueSource(tmp_filename) vals = jvs.get_values(None, True) self.assertEqual(vals['fred'], 'wilma') self.assertEqual(vals['number'], 23) finally: if",
"the terms of the MPL, indicate your # decision by deleting the provisions",
"n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) def value_iter(): yield 'aaa', 'aaa', n.aaa",
"s.close() jrec = json.loads(received) expect_to_find = { \"short_form\": \"a\", \"default\": \"2011-05-04T15:10:00\", \"doc\": \"the",
"is configman # # The Initial Developer of the Original Code is #",
"\"AS IS\" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied.",
"LGPL, and not to allow others to # use your version of this",
"def bbb_minus_one(config, local_config, args): return config.bbb - 1 class TestCase(unittest.TestCase): def test_for_json_basics(self): tmp_filename",
"of the GPL or the LGPL are applicable instead # of those above.",
"# for the specific language governing rights and limitations under the # License.",
"delete=False) name = '/tmp/test.json' import functools opener = functools.partial(open, name, 'w') c1 =",
"2.1 # # The contents of this file are subject to the Mozilla",
"= {'bbb': 88} d2 = {'bbb': '-99'} try: with open(name) as jfp: j",
"StringIO import configman.config_manager as config_manager import configman.datetime_util as dtu from configman.value_sources.for_json import ValueSource",
"use your version of this file under the terms of the MPL, indicate",
"88} d2 = {'bbb': '-99'} try: with open(name) as jfp: j = json.load(jfp)",
"c2 = config_manager.ConfigurationManager((j,), (d1, d2), use_admin_controls=True, use_auto_help=False, argv_source=[]) config = c2.get_config() self.assertEqual(config.aaa, expected_date)",
"in expect_to_find.items(): self.assertEqual(jrec['aaa'][key], value) def test_json_round_trip(self): n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a',",
"yield 'aaa', 'aaa', n.aaa s = StringIO() ValueSource.write(value_iter, output_stream=s) received = s.getvalue() s.close()",
"others to # use your version of this file under the terms of",
"the GNU General Public License Version 2 or later (the \"GPL\"), or #",
"tmp_filename = os.path.join(tempfile.gettempdir(), 'test.json') j = {'fred': 'wilma', 'number': 23, } with open(tmp_filename,",
"BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of",
"Copyright (C) 2011 # the Initial Developer. All Rights Reserved. # # Contributor(s):",
"Original Code is # Mozilla Foundation # Portions created by the Initial Developer",
"License. # # The Original Code is configman # # The Initial Developer",
"License Version # 1.1 (the \"License\"); you may not use this file except",
"under the License is distributed on an \"AS IS\" basis, # WITHOUT WARRANTY",
"your version of this file under # the terms of any one of",
"import configman.config_manager as config_manager import configman.datetime_util as dtu from configman.value_sources.for_json import ValueSource #from",
"OF ANY KIND, either express or implied. See the License # for the",
"the provisions of the GPL or the LGPL are applicable instead # of",
"a copy of the License at # http://www.mozilla.org/MPL/ # # Software distributed under",
"Initial Developer are Copyright (C) 2011 # the Initial Developer. All Rights Reserved.",
"allow use of your version of this file only # under the terms",
"the Initial Developer are Copyright (C) 2011 # the Initial Developer. All Rights",
"self.assertEqual(jrec['aaa'][key], value) def test_json_round_trip(self): n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string",
"config_manager.ConfigurationManager([n], [], use_admin_controls=True, use_auto_help=False, app_name='/tmp/test', app_version='0', app_description='', argv_source=[]) c1.write_conf('json', opener) d1 = {'bbb':",
"\"short_form\": \"a\", \"default\": \"2011-05-04T15:10:00\", \"doc\": \"the a\", \"value\": \"2011-05-04T15:10:00\", \"from_string_converter\": \"configman.datetime_util.datetime_from_ISO_string\", \"name\": \"aaa\"",
"by the Initial Developer are Copyright (C) 2011 # the Initial Developer. All",
"functools.partial(open, name, 'w') c1 = config_manager.ConfigurationManager([n], [], use_admin_controls=True, use_auto_help=False, app_name='/tmp/test', app_version='0', app_description='', argv_source=[])",
"output_stream=s) received = s.getvalue() s.close() jrec = json.loads(received) expect_to_find = { \"short_form\": \"a\",",
"LGPL are applicable instead # of those above. If you wish to allow",
"\"default\": \"2011-05-04T15:10:00\", \"doc\": \"the a\", \"value\": \"2011-05-04T15:10:00\", \"from_string_converter\": \"configman.datetime_util.datetime_from_ISO_string\", \"name\": \"aaa\" } for",
"2 or later (the \"GPL\"), or # the GNU Lesser General Public License",
"Original Code is configman # # The Initial Developer of the Original Code",
"contents of this file may be used under the terms of # either",
"Mozilla Public License Version # 1.1 (the \"License\"); you may not use this",
"# # The contents of this file are subject to the Mozilla Public",
"governing rights and limitations under the # License. # # The Original Code",
"the terms of any one of the MPL, the GPL or the LGPL.",
"def test_json_round_trip(self): n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) expected_date",
"vals = jvs.get_values(None, True) self.assertEqual(vals['fred'], 'wilma') self.assertEqual(vals['number'], 23) finally: if os.path.isfile(tmp_filename): os.remove(tmp_filename) def",
"subject to the Mozilla Public License Version # 1.1 (the \"License\"); you may",
"created by the Initial Developer are Copyright (C) 2011 # the Initial Developer.",
"(C) 2011 # the Initial Developer. All Rights Reserved. # # Contributor(s): #",
"Lesser General Public License Version 2.1 or later (the \"LGPL\"), # in which",
"expect_to_find = { \"short_form\": \"a\", \"default\": \"2011-05-04T15:10:00\", \"doc\": \"the a\", \"value\": \"2011-05-04T15:10:00\", \"from_string_converter\":",
"***** import unittest import os import json import tempfile from cStringIO import StringIO",
"= os.path.join(tempfile.gettempdir(), 'test.json') j = {'fred': 'wilma', 'number': 23, } with open(tmp_filename, 'w')",
"jfp: j = json.load(jfp) c2 = config_manager.ConfigurationManager((j,), (d1, d2), use_admin_controls=True, use_auto_help=False, argv_source=[]) config",
"or later (the \"GPL\"), or # the GNU Lesser General Public License Version",
"= StringIO() ValueSource.write(value_iter, output_stream=s) received = s.getvalue() s.close() jrec = json.loads(received) expect_to_find =",
"the LGPL. If you do not delete # the provisions above, a recipient",
"json.dump(j, f) try: jvs = ValueSource(tmp_filename) vals = jvs.get_values(None, True) self.assertEqual(vals['fred'], 'wilma') self.assertEqual(vals['number'],",
"IS\" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See",
"Portions created by the Initial Developer are Copyright (C) 2011 # the Initial",
"above and replace them with the notice # and other provisions required by",
"notice # and other provisions required by the GPL or the LGPL. If",
"License Version 2 or later (the \"GPL\"), or # the GNU Lesser General",
"= {'bbb': '-99'} try: with open(name) as jfp: j = json.load(jfp) c2 =",
"only # under the terms of either the GPL or the LGPL, and",
"LGPL. # # ***** END LICENSE BLOCK ***** import unittest import os import",
"you wish to allow use of your version of this file only #",
"n.aaa s = StringIO() ValueSource.write(value_iter, output_stream=s) received = s.getvalue() s.close() jrec = json.loads(received)",
"BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The",
"deleting the provisions above and replace them with the notice # and other",
"express or implied. See the License # for the specific language governing rights",
"open(tmp_filename, 'w') as f: json.dump(j, f) try: jvs = ValueSource(tmp_filename) vals = jvs.get_values(None,",
"MPL, indicate your # decision by deleting the provisions above and replace them",
"this file except in compliance with # the License. You may obtain a",
"rights and limitations under the # License. # # The Original Code is",
"import configman.datetime_util as dtu from configman.value_sources.for_json import ValueSource #from ..value_sources.for_json import ValueSource def",
"c1 = config_manager.ConfigurationManager([n], [], use_admin_controls=True, use_auto_help=False, app_name='/tmp/test', app_version='0', app_description='', argv_source=[]) c1.write_conf('json', opener) d1",
"\"2011-05-04T15:10:00\", \"doc\": \"the a\", \"value\": \"2011-05-04T15:10:00\", \"from_string_converter\": \"configman.datetime_util.datetime_from_ISO_string\", \"name\": \"aaa\" } for key,",
"under the # License. # # The Original Code is configman # #",
"under the terms of either the GPL or the LGPL, and not to",
"opener = functools.partial(open, name, 'w') c1 = config_manager.ConfigurationManager([n], [], use_admin_controls=True, use_auto_help=False, app_name='/tmp/test', app_version='0',",
"Public License Version # 1.1 (the \"License\"); you may not use this file",
"are Copyright (C) 2011 # the Initial Developer. All Rights Reserved. # #",
"your version of this file under the terms of the MPL, indicate your",
"the LGPL are applicable instead # of those above. If you wish to",
"obtain a copy of the License at # http://www.mozilla.org/MPL/ # # Software distributed",
"of the MPL, indicate your # decision by deleting the provisions above and",
"Foundation # Portions created by the Initial Developer are Copyright (C) 2011 #",
"[], use_admin_controls=True, use_auto_help=False, app_name='/tmp/test', app_version='0', app_description='', argv_source=[]) c1.write_conf('json', opener) d1 = {'bbb': 88}",
"MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject",
"n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) expected_date = dtu.datetime_from_ISO_string('2011-05-04T15:10:00')",
"the License at # http://www.mozilla.org/MPL/ # # Software distributed under the License is",
"either the GNU General Public License Version 2 or later (the \"GPL\"), or",
"a\", \"value\": \"2011-05-04T15:10:00\", \"from_string_converter\": \"configman.datetime_util.datetime_from_ISO_string\", \"name\": \"aaa\" } for key, value in expect_to_find.items():",
"Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are",
"configman.datetime_util as dtu from configman.value_sources.for_json import ValueSource #from ..value_sources.for_json import ValueSource def bbb_minus_one(config,",
"self.assertEqual(vals['fred'], 'wilma') self.assertEqual(vals['number'], 23) finally: if os.path.isfile(tmp_filename): os.remove(tmp_filename) def test_write_json(self): n = config_manager.Namespace(doc='top')",
"expect_to_find.items(): self.assertEqual(jrec['aaa'][key], value) def test_json_round_trip(self): n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a',",
"test_write_json(self): n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) def value_iter():",
"You may obtain a copy of the License at # http://www.mozilla.org/MPL/ # #",
"the LGPL. # # ***** END LICENSE BLOCK ***** import unittest import os",
"All Rights Reserved. # # Contributor(s): # <NAME>, <EMAIL> # <NAME>, <EMAIL> #",
"os.remove(tmp_filename) def test_write_json(self): n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string )",
"{ \"short_form\": \"a\", \"default\": \"2011-05-04T15:10:00\", \"doc\": \"the a\", \"value\": \"2011-05-04T15:10:00\", \"from_string_converter\": \"configman.datetime_util.datetime_from_ISO_string\", \"name\":",
"2011 # the Initial Developer. All Rights Reserved. # # Contributor(s): # <NAME>,",
"Alternatively, the contents of this file may be used under the terms of",
"# decision by deleting the provisions above and replace them with the notice",
"'aaa', 'aaa', n.aaa s = StringIO() ValueSource.write(value_iter, output_stream=s) received = s.getvalue() s.close() jrec",
"unittest import os import json import tempfile from cStringIO import StringIO import configman.config_manager",
"compliance with # the License. You may obtain a copy of the License",
"Version 2.1 or later (the \"LGPL\"), # in which case the provisions of",
"Developer of the Original Code is # Mozilla Foundation # Portions created by",
"'number': 23, } with open(tmp_filename, 'w') as f: json.dump(j, f) try: jvs =",
"os.path.join(tempfile.gettempdir(), 'test.json') j = {'fred': 'wilma', 'number': 23, } with open(tmp_filename, 'w') as",
"Version # 1.1 (the \"License\"); you may not use this file except in",
"later (the \"LGPL\"), # in which case the provisions of the GPL or",
"use of your version of this file only # under the terms of",
"'-99'} try: with open(name) as jfp: j = json.load(jfp) c2 = config_manager.ConfigurationManager((j,), (d1,",
"distributed on an \"AS IS\" basis, # WITHOUT WARRANTY OF ANY KIND, either",
"the GPL or the LGPL are applicable instead # of those above. If",
"bbb_minus_one(config, local_config, args): return config.bbb - 1 class TestCase(unittest.TestCase): def test_for_json_basics(self): tmp_filename =",
"# # Software distributed under the License is distributed on an \"AS IS\"",
"may obtain a copy of the License at # http://www.mozilla.org/MPL/ # # Software",
"License # for the specific language governing rights and limitations under the #",
"by the GPL or the LGPL. If you do not delete # the",
"(the \"LGPL\"), # in which case the provisions of the GPL or the",
"json.loads(received) expect_to_find = { \"short_form\": \"a\", \"default\": \"2011-05-04T15:10:00\", \"doc\": \"the a\", \"value\": \"2011-05-04T15:10:00\",",
"instead # of those above. If you wish to allow use of your",
"not delete # the provisions above, a recipient may use your version of",
"dtu.datetime_from_ISO_string('2011-05-04T15:10:00') n.add_option('bbb', '37', 'the a', short_form='a', from_string_converter=int ) n.add_option('write', 'json') n.add_aggregation('bbb_minus_one', bbb_minus_one) #t",
"of any one of the MPL, the GPL or the LGPL. # #",
"value in expect_to_find.items(): self.assertEqual(jrec['aaa'][key], value) def test_json_round_trip(self): n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the",
"are applicable instead # of those above. If you wish to allow use",
"Public License Version 2 or later (the \"GPL\"), or # the GNU Lesser",
"The Original Code is configman # # The Initial Developer of the Original",
"# Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file",
"configman.config_manager as config_manager import configman.datetime_util as dtu from configman.value_sources.for_json import ValueSource #from ..value_sources.for_json",
"use_auto_help=False, argv_source=[]) config = c2.get_config() self.assertEqual(config.aaa, expected_date) self.assertEqual(config.bbb, -99) self.assertEqual(config.bbb_minus_one, -100) finally: os.unlink(name)",
"app_name='/tmp/test', app_version='0', app_description='', argv_source=[]) c1.write_conf('json', opener) d1 = {'bbb': 88} d2 = {'bbb':",
"language governing rights and limitations under the # License. # # The Original",
"= config_manager.ConfigurationManager((j,), (d1, d2), use_admin_controls=True, use_auto_help=False, argv_source=[]) config = c2.get_config() self.assertEqual(config.aaa, expected_date) self.assertEqual(config.bbb,",
"may use your version of this file under # the terms of any",
"2.1 or later (the \"LGPL\"), # in which case the provisions of the",
"# Contributor(s): # <NAME>, <EMAIL> # <NAME>, <EMAIL> # # Alternatively, the contents",
"General Public License Version 2 or later (the \"GPL\"), or # the GNU",
"'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) def value_iter(): yield 'aaa', 'aaa', n.aaa s =",
"= config_manager.ConfigurationManager([n], [], use_admin_controls=True, use_auto_help=False, app_name='/tmp/test', app_version='0', app_description='', argv_source=[]) c1.write_conf('json', opener) d1 =",
"the License is distributed on an \"AS IS\" basis, # WITHOUT WARRANTY OF",
"(the \"GPL\"), or # the GNU Lesser General Public License Version 2.1 or",
"which case the provisions of the GPL or the LGPL are applicable instead",
"in compliance with # the License. You may obtain a copy of the",
"recipient may use your version of this file under # the terms of",
"# ***** END LICENSE BLOCK ***** import unittest import os import json import",
"'37', 'the a', short_form='a', from_string_converter=int ) n.add_option('write', 'json') n.add_aggregation('bbb_minus_one', bbb_minus_one) #t = tempfile.NamedTemporaryFile('w',",
"Contributor(s): # <NAME>, <EMAIL> # <NAME>, <EMAIL> # # Alternatively, the contents of",
"at # http://www.mozilla.org/MPL/ # # Software distributed under the License is distributed on",
"The Initial Developer of the Original Code is # Mozilla Foundation # Portions",
"GPL or the LGPL. # # ***** END LICENSE BLOCK ***** import unittest",
"are subject to the Mozilla Public License Version # 1.1 (the \"License\"); you",
"License at # http://www.mozilla.org/MPL/ # # Software distributed under the License is distributed",
"replace them with the notice # and other provisions required by the GPL",
"or the LGPL, and not to allow others to # use your version",
"Developer are Copyright (C) 2011 # the Initial Developer. All Rights Reserved. #",
"may not use this file except in compliance with # the License. You",
"dtu from configman.value_sources.for_json import ValueSource #from ..value_sources.for_json import ValueSource def bbb_minus_one(config, local_config, args):",
"class TestCase(unittest.TestCase): def test_for_json_basics(self): tmp_filename = os.path.join(tempfile.gettempdir(), 'test.json') j = {'fred': 'wilma', 'number':",
"the notice # and other provisions required by the GPL or the LGPL.",
"tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) name = '/tmp/test.json' import functools opener = functools.partial(open, name, 'w')",
"version of this file under the terms of the MPL, indicate your #",
"1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to",
"of this file only # under the terms of either the GPL or",
"# # ***** END LICENSE BLOCK ***** import unittest import os import json",
"n.add_option('bbb', '37', 'the a', short_form='a', from_string_converter=int ) n.add_option('write', 'json') n.add_aggregation('bbb_minus_one', bbb_minus_one) #t =",
"{'bbb': 88} d2 = {'bbb': '-99'} try: with open(name) as jfp: j =",
"See the License # for the specific language governing rights and limitations under",
"the GPL or the LGPL. If you do not delete # the provisions",
"one of the MPL, the GPL or the LGPL. # # ***** END",
"file are subject to the Mozilla Public License Version # 1.1 (the \"License\");",
"limitations under the # License. # # The Original Code is configman #",
"above. If you wish to allow use of your version of this file",
"under the terms of the MPL, indicate your # decision by deleting the",
"= json.loads(received) expect_to_find = { \"short_form\": \"a\", \"default\": \"2011-05-04T15:10:00\", \"doc\": \"the a\", \"value\":",
"# http://www.mozilla.org/MPL/ # # Software distributed under the License is distributed on an",
"# the terms of any one of the MPL, the GPL or the",
"config.bbb - 1 class TestCase(unittest.TestCase): def test_for_json_basics(self): tmp_filename = os.path.join(tempfile.gettempdir(), 'test.json') j =",
"either the GPL or the LGPL, and not to allow others to #",
"'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) expected_date = dtu.datetime_from_ISO_string('2011-05-04T15:10:00') n.add_option('bbb', '37', 'the a', short_form='a',",
"for the specific language governing rights and limitations under the # License. #",
"jvs.get_values(None, True) self.assertEqual(vals['fred'], 'wilma') self.assertEqual(vals['number'], 23) finally: if os.path.isfile(tmp_filename): os.remove(tmp_filename) def test_write_json(self): n",
"n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) expected_date = dtu.datetime_from_ISO_string('2011-05-04T15:10:00') n.add_option('bbb', '37', 'the",
"args): return config.bbb - 1 class TestCase(unittest.TestCase): def test_for_json_basics(self): tmp_filename = os.path.join(tempfile.gettempdir(), 'test.json')",
"json import tempfile from cStringIO import StringIO import configman.config_manager as config_manager import configman.datetime_util",
"License Version 2.1 or later (the \"LGPL\"), # in which case the provisions",
"a recipient may use your version of this file under # the terms",
"***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this",
"short_form='a', from_string_converter=int ) n.add_option('write', 'json') n.add_aggregation('bbb_minus_one', bbb_minus_one) #t = tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) name",
"any one of the MPL, the GPL or the LGPL. # # *****",
"jrec = json.loads(received) expect_to_find = { \"short_form\": \"a\", \"default\": \"2011-05-04T15:10:00\", \"doc\": \"the a\",",
"The contents of this file are subject to the Mozilla Public License Version",
"# License. # # The Original Code is configman # # The Initial",
"\"License\"); you may not use this file except in compliance with # the",
"the Original Code is # Mozilla Foundation # Portions created by the Initial",
"#t = tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) name = '/tmp/test.json' import functools opener = functools.partial(open,",
"WARRANTY OF ANY KIND, either express or implied. See the License # for",
"If you do not delete # the provisions above, a recipient may use",
"KIND, either express or implied. See the License # for the specific language",
"Mozilla Foundation # Portions created by the Initial Developer are Copyright (C) 2011",
"Reserved. # # Contributor(s): # <NAME>, <EMAIL> # <NAME>, <EMAIL> # # Alternatively,",
"TestCase(unittest.TestCase): def test_for_json_basics(self): tmp_filename = os.path.join(tempfile.gettempdir(), 'test.json') j = {'fred': 'wilma', 'number': 23,",
"the GPL or the LGPL, and not to allow others to # use",
"os import json import tempfile from cStringIO import StringIO import configman.config_manager as config_manager",
"the License. You may obtain a copy of the License at # http://www.mozilla.org/MPL/",
"d2), use_admin_controls=True, use_auto_help=False, argv_source=[]) config = c2.get_config() self.assertEqual(config.aaa, expected_date) self.assertEqual(config.bbb, -99) self.assertEqual(config.bbb_minus_one, -100)",
"of your version of this file only # under the terms of either",
"open(name) as jfp: j = json.load(jfp) c2 = config_manager.ConfigurationManager((j,), (d1, d2), use_admin_controls=True, use_auto_help=False,",
"of this file may be used under the terms of # either the",
"# the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"),",
"# use your version of this file under the terms of the MPL,",
"or the LGPL. If you do not delete # the provisions above, a",
"use your version of this file under # the terms of any one",
"2.0/LGPL 2.1 # # The contents of this file are subject to the",
"\"value\": \"2011-05-04T15:10:00\", \"from_string_converter\": \"configman.datetime_util.datetime_from_ISO_string\", \"name\": \"aaa\" } for key, value in expect_to_find.items(): self.assertEqual(jrec['aaa'][key],",
"f) try: jvs = ValueSource(tmp_filename) vals = jvs.get_values(None, True) self.assertEqual(vals['fred'], 'wilma') self.assertEqual(vals['number'], 23)",
"version of this file only # under the terms of either the GPL",
"# Mozilla Foundation # Portions created by the Initial Developer are Copyright (C)",
"of # either the GNU General Public License Version 2 or later (the",
"{'bbb': '-99'} try: with open(name) as jfp: j = json.load(jfp) c2 = config_manager.ConfigurationManager((j,),",
"# under the terms of either the GPL or the LGPL, and not",
"Initial Developer. All Rights Reserved. # # Contributor(s): # <NAME>, <EMAIL> # <NAME>,",
"to # use your version of this file under the terms of the",
"http://www.mozilla.org/MPL/ # # Software distributed under the License is distributed on an \"AS",
"later (the \"GPL\"), or # the GNU Lesser General Public License Version 2.1",
"decision by deleting the provisions above and replace them with the notice #",
"value) def test_json_round_trip(self): n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string )",
"you may not use this file except in compliance with # the License.",
"ValueSource(tmp_filename) vals = jvs.get_values(None, True) self.assertEqual(vals['fred'], 'wilma') self.assertEqual(vals['number'], 23) finally: if os.path.isfile(tmp_filename): os.remove(tmp_filename)",
"or later (the \"LGPL\"), # in which case the provisions of the GPL",
"return config.bbb - 1 class TestCase(unittest.TestCase): def test_for_json_basics(self): tmp_filename = os.path.join(tempfile.gettempdir(), 'test.json') j",
"ANY KIND, either express or implied. See the License # for the specific",
"= json.load(jfp) c2 = config_manager.ConfigurationManager((j,), (d1, d2), use_admin_controls=True, use_auto_help=False, argv_source=[]) config = c2.get_config()",
"use this file except in compliance with # the License. You may obtain",
"def test_write_json(self): n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) def",
"an \"AS IS\" basis, # WITHOUT WARRANTY OF ANY KIND, either express or",
"import ValueSource def bbb_minus_one(config, local_config, args): return config.bbb - 1 class TestCase(unittest.TestCase): def",
"you do not delete # the provisions above, a recipient may use your",
"= ValueSource(tmp_filename) vals = jvs.get_values(None, True) self.assertEqual(vals['fred'], 'wilma') self.assertEqual(vals['number'], 23) finally: if os.path.isfile(tmp_filename):",
"if os.path.isfile(tmp_filename): os.remove(tmp_filename) def test_write_json(self): n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a',",
"local_config, args): return config.bbb - 1 class TestCase(unittest.TestCase): def test_for_json_basics(self): tmp_filename = os.path.join(tempfile.gettempdir(),",
"with the notice # and other provisions required by the GPL or the",
"version of this file under # the terms of any one of the",
"implied. See the License # for the specific language governing rights and limitations",
"LICENSE BLOCK ***** import unittest import os import json import tempfile from cStringIO",
"file only # under the terms of either the GPL or the LGPL,",
"d1 = {'bbb': 88} d2 = {'bbb': '-99'} try: with open(name) as jfp:",
"<NAME>, <EMAIL> # # Alternatively, the contents of this file may be used",
"1 class TestCase(unittest.TestCase): def test_for_json_basics(self): tmp_filename = os.path.join(tempfile.gettempdir(), 'test.json') j = {'fred': 'wilma',",
"ValueSource.write(value_iter, output_stream=s) received = s.getvalue() s.close() jrec = json.loads(received) expect_to_find = { \"short_form\":",
"# the Initial Developer. All Rights Reserved. # # Contributor(s): # <NAME>, <EMAIL>",
"ValueSource def bbb_minus_one(config, local_config, args): return config.bbb - 1 class TestCase(unittest.TestCase): def test_for_json_basics(self):",
"your version of this file only # under the terms of either the",
"allow others to # use your version of this file under the terms",
"cStringIO import StringIO import configman.config_manager as config_manager import configman.datetime_util as dtu from configman.value_sources.for_json",
"j = {'fred': 'wilma', 'number': 23, } with open(tmp_filename, 'w') as f: json.dump(j,",
"expected_date = dtu.datetime_from_ISO_string('2011-05-04T15:10:00') n.add_option('bbb', '37', 'the a', short_form='a', from_string_converter=int ) n.add_option('write', 'json') n.add_aggregation('bbb_minus_one',",
"of this file under the terms of the MPL, indicate your # decision",
"specific language governing rights and limitations under the # License. # # The",
"terms of either the GPL or the LGPL, and not to allow others",
"\"the a\", \"value\": \"2011-05-04T15:10:00\", \"from_string_converter\": \"configman.datetime_util.datetime_from_ISO_string\", \"name\": \"aaa\" } for key, value in",
"required by the GPL or the LGPL. If you do not delete #",
"this file under # the terms of any one of the MPL, the",
"indicate your # decision by deleting the provisions above and replace them with",
"\"GPL\"), or # the GNU Lesser General Public License Version 2.1 or later",
"functools opener = functools.partial(open, name, 'w') c1 = config_manager.ConfigurationManager([n], [], use_admin_controls=True, use_auto_help=False, app_name='/tmp/test',",
"and not to allow others to # use your version of this file",
"of this file under # the terms of any one of the MPL,",
"and replace them with the notice # and other provisions required by the",
"be used under the terms of # either the GNU General Public License",
"'wilma', 'number': 23, } with open(tmp_filename, 'w') as f: json.dump(j, f) try: jvs",
"copy of the License at # http://www.mozilla.org/MPL/ # # Software distributed under the",
"#from ..value_sources.for_json import ValueSource def bbb_minus_one(config, local_config, args): return config.bbb - 1 class",
"test_json_round_trip(self): n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) expected_date =",
"except in compliance with # the License. You may obtain a copy of",
"s.getvalue() s.close() jrec = json.loads(received) expect_to_find = { \"short_form\": \"a\", \"default\": \"2011-05-04T15:10:00\", \"doc\":",
"# in which case the provisions of the GPL or the LGPL are",
"23) finally: if os.path.isfile(tmp_filename): os.remove(tmp_filename) def test_write_json(self): n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the",
"value_iter(): yield 'aaa', 'aaa', n.aaa s = StringIO() ValueSource.write(value_iter, output_stream=s) received = s.getvalue()",
"import functools opener = functools.partial(open, name, 'w') c1 = config_manager.ConfigurationManager([n], [], use_admin_controls=True, use_auto_help=False,",
"app_version='0', app_description='', argv_source=[]) c1.write_conf('json', opener) d1 = {'bbb': 88} d2 = {'bbb': '-99'}",
"(d1, d2), use_admin_controls=True, use_auto_help=False, argv_source=[]) config = c2.get_config() self.assertEqual(config.aaa, expected_date) self.assertEqual(config.bbb, -99) self.assertEqual(config.bbb_minus_one,",
"short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) def value_iter(): yield 'aaa', 'aaa', n.aaa s = StringIO() ValueSource.write(value_iter,",
"23, } with open(tmp_filename, 'w') as f: json.dump(j, f) try: jvs = ValueSource(tmp_filename)",
"= {'fred': 'wilma', 'number': 23, } with open(tmp_filename, 'w') as f: json.dump(j, f)",
"config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) expected_date = dtu.datetime_from_ISO_string('2011-05-04T15:10:00') n.add_option('bbb', '37',",
"do not delete # the provisions above, a recipient may use your version",
"the License # for the specific language governing rights and limitations under the",
"wish to allow use of your version of this file only # under",
"terms of the MPL, indicate your # decision by deleting the provisions above",
"received = s.getvalue() s.close() jrec = json.loads(received) expect_to_find = { \"short_form\": \"a\", \"default\":",
"short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) expected_date = dtu.datetime_from_ISO_string('2011-05-04T15:10:00') n.add_option('bbb', '37', 'the a', short_form='a', from_string_converter=int )",
"= '/tmp/test.json' import functools opener = functools.partial(open, name, 'w') c1 = config_manager.ConfigurationManager([n], [],",
"of either the GPL or the LGPL, and not to allow others to",
"\"LGPL\"), # in which case the provisions of the GPL or the LGPL",
"not to allow others to # use your version of this file under",
"above, a recipient may use your version of this file under # the",
"= s.getvalue() s.close() jrec = json.loads(received) expect_to_find = { \"short_form\": \"a\", \"default\": \"2011-05-04T15:10:00\",",
"of the MPL, the GPL or the LGPL. # # ***** END LICENSE",
"applicable instead # of those above. If you wish to allow use of",
"the contents of this file may be used under the terms of #",
"# <NAME>, <EMAIL> # # Alternatively, the contents of this file may be",
"provisions of the GPL or the LGPL are applicable instead # of those",
"= functools.partial(open, name, 'w') c1 = config_manager.ConfigurationManager([n], [], use_admin_controls=True, use_auto_help=False, app_name='/tmp/test', app_version='0', app_description='',",
"= config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) expected_date = dtu.datetime_from_ISO_string('2011-05-04T15:10:00') n.add_option('bbb',",
"other provisions required by the GPL or the LGPL. If you do not",
"json.load(jfp) c2 = config_manager.ConfigurationManager((j,), (d1, d2), use_admin_controls=True, use_auto_help=False, argv_source=[]) config = c2.get_config() self.assertEqual(config.aaa,",
"END LICENSE BLOCK ***** import unittest import os import json import tempfile from",
"- 1 class TestCase(unittest.TestCase): def test_for_json_basics(self): tmp_filename = os.path.join(tempfile.gettempdir(), 'test.json') j = {'fred':",
"s = StringIO() ValueSource.write(value_iter, output_stream=s) received = s.getvalue() s.close() jrec = json.loads(received) expect_to_find",
"the Mozilla Public License Version # 1.1 (the \"License\"); you may not use",
"# The Initial Developer of the Original Code is # Mozilla Foundation #",
"import tempfile from cStringIO import StringIO import configman.config_manager as config_manager import configman.datetime_util as",
"those above. If you wish to allow use of your version of this",
"= tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) name = '/tmp/test.json' import functools opener = functools.partial(open, name,",
"as jfp: j = json.load(jfp) c2 = config_manager.ConfigurationManager((j,), (d1, d2), use_admin_controls=True, use_auto_help=False, argv_source=[])",
"# Software distributed under the License is distributed on an \"AS IS\" basis,",
"'json') n.add_aggregation('bbb_minus_one', bbb_minus_one) #t = tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) name = '/tmp/test.json' import functools",
"and limitations under the # License. # # The Original Code is configman",
"delete # the provisions above, a recipient may use your version of this",
"<EMAIL> # # Alternatively, the contents of this file may be used under",
"# # The Initial Developer of the Original Code is # Mozilla Foundation",
"from cStringIO import StringIO import configman.config_manager as config_manager import configman.datetime_util as dtu from",
"LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents",
"\"name\": \"aaa\" } for key, value in expect_to_find.items(): self.assertEqual(jrec['aaa'][key], value) def test_json_round_trip(self): n",
"import json import tempfile from cStringIO import StringIO import configman.config_manager as config_manager import",
"1.1 (the \"License\"); you may not use this file except in compliance with",
"for key, value in expect_to_find.items(): self.assertEqual(jrec['aaa'][key], value) def test_json_round_trip(self): n = config_manager.Namespace(doc='top') n.add_option('aaa',",
"GPL or the LGPL, and not to allow others to # use your",
"under # the terms of any one of the MPL, the GPL or",
"them with the notice # and other provisions required by the GPL or",
"\"2011-05-04T15:10:00\", \"from_string_converter\": \"configman.datetime_util.datetime_from_ISO_string\", \"name\": \"aaa\" } for key, value in expect_to_find.items(): self.assertEqual(jrec['aaa'][key], value)",
"name = '/tmp/test.json' import functools opener = functools.partial(open, name, 'w') c1 = config_manager.ConfigurationManager([n],",
"# The contents of this file are subject to the Mozilla Public License",
"<NAME>, <EMAIL> # <NAME>, <EMAIL> # # Alternatively, the contents of this file",
"basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the",
"= dtu.datetime_from_ISO_string('2011-05-04T15:10:00') n.add_option('bbb', '37', 'the a', short_form='a', from_string_converter=int ) n.add_option('write', 'json') n.add_aggregation('bbb_minus_one', bbb_minus_one)",
"with # the License. You may obtain a copy of the License at",
"{'fred': 'wilma', 'number': 23, } with open(tmp_filename, 'w') as f: json.dump(j, f) try:",
"***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # #",
"is # Mozilla Foundation # Portions created by the Initial Developer are Copyright",
"provisions required by the GPL or the LGPL. If you do not delete",
"Code is configman # # The Initial Developer of the Original Code is",
"GNU General Public License Version 2 or later (the \"GPL\"), or # the",
"either express or implied. See the License # for the specific language governing",
"import os import json import tempfile from cStringIO import StringIO import configman.config_manager as",
"c1.write_conf('json', opener) d1 = {'bbb': 88} d2 = {'bbb': '-99'} try: with open(name)",
"may be used under the terms of # either the GNU General Public",
"= { \"short_form\": \"a\", \"default\": \"2011-05-04T15:10:00\", \"doc\": \"the a\", \"value\": \"2011-05-04T15:10:00\", \"from_string_converter\": \"configman.datetime_util.datetime_from_ISO_string\",",
"# the License. You may obtain a copy of the License at #",
"or the LGPL. # # ***** END LICENSE BLOCK ***** import unittest import",
"from_string_converter=dtu.datetime_from_ISO_string ) expected_date = dtu.datetime_from_ISO_string('2011-05-04T15:10:00') n.add_option('bbb', '37', 'the a', short_form='a', from_string_converter=int ) n.add_option('write',",
"is distributed on an \"AS IS\" basis, # WITHOUT WARRANTY OF ANY KIND,",
"n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) def value_iter(): yield",
"the MPL, the GPL or the LGPL. # # ***** END LICENSE BLOCK",
"# of those above. If you wish to allow use of your version",
"'test.json') j = {'fred': 'wilma', 'number': 23, } with open(tmp_filename, 'w') as f:",
"not use this file except in compliance with # the License. You may",
"config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) def value_iter(): yield 'aaa', 'aaa',",
"f: json.dump(j, f) try: jvs = ValueSource(tmp_filename) vals = jvs.get_values(None, True) self.assertEqual(vals['fred'], 'wilma')",
"Public License Version 2.1 or later (the \"LGPL\"), # in which case the",
"= config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) def value_iter(): yield 'aaa',",
"Rights Reserved. # # Contributor(s): # <NAME>, <EMAIL> # <NAME>, <EMAIL> # #",
"this file only # under the terms of either the GPL or the",
"or implied. See the License # for the specific language governing rights and",
"'/tmp/test.json' import functools opener = functools.partial(open, name, 'w') c1 = config_manager.ConfigurationManager([n], [], use_admin_controls=True,",
") def value_iter(): yield 'aaa', 'aaa', n.aaa s = StringIO() ValueSource.write(value_iter, output_stream=s) received",
"on an \"AS IS\" basis, # WITHOUT WARRANTY OF ANY KIND, either express",
"ValueSource #from ..value_sources.for_json import ValueSource def bbb_minus_one(config, local_config, args): return config.bbb - 1",
") n.add_option('write', 'json') n.add_aggregation('bbb_minus_one', bbb_minus_one) #t = tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) name = '/tmp/test.json'",
"Software distributed under the License is distributed on an \"AS IS\" basis, #",
"j = json.load(jfp) c2 = config_manager.ConfigurationManager((j,), (d1, d2), use_admin_controls=True, use_auto_help=False, argv_source=[]) config =",
"or # the GNU Lesser General Public License Version 2.1 or later (the",
"= jvs.get_values(None, True) self.assertEqual(vals['fred'], 'wilma') self.assertEqual(vals['number'], 23) finally: if os.path.isfile(tmp_filename): os.remove(tmp_filename) def test_write_json(self):",
"'w') c1 = config_manager.ConfigurationManager([n], [], use_admin_controls=True, use_auto_help=False, app_name='/tmp/test', app_version='0', app_description='', argv_source=[]) c1.write_conf('json', opener)",
"from_string_converter=int ) n.add_option('write', 'json') n.add_aggregation('bbb_minus_one', bbb_minus_one) #t = tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) name =",
"the MPL, indicate your # decision by deleting the provisions above and replace",
"the GPL or the LGPL. # # ***** END LICENSE BLOCK ***** import",
"as dtu from configman.value_sources.for_json import ValueSource #from ..value_sources.for_json import ValueSource def bbb_minus_one(config, local_config,",
"self.assertEqual(vals['number'], 23) finally: if os.path.isfile(tmp_filename): os.remove(tmp_filename) def test_write_json(self): n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00',",
"used under the terms of # either the GNU General Public License Version",
"under the terms of # either the GNU General Public License Version 2",
"config_manager import configman.datetime_util as dtu from configman.value_sources.for_json import ValueSource #from ..value_sources.for_json import ValueSource",
"# The Original Code is configman # # The Initial Developer of the",
"the Initial Developer. All Rights Reserved. # # Contributor(s): # <NAME>, <EMAIL> #",
"# either the GNU General Public License Version 2 or later (the \"GPL\"),",
"# # The Original Code is configman # # The Initial Developer of",
"in which case the provisions of the GPL or the LGPL are applicable",
"MPL, the GPL or the LGPL. # # ***** END LICENSE BLOCK *****",
"os.path.isfile(tmp_filename): os.remove(tmp_filename) def test_write_json(self): n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string",
"to allow use of your version of this file only # under the",
"..value_sources.for_json import ValueSource def bbb_minus_one(config, local_config, args): return config.bbb - 1 class TestCase(unittest.TestCase):",
"try: jvs = ValueSource(tmp_filename) vals = jvs.get_values(None, True) self.assertEqual(vals['fred'], 'wilma') self.assertEqual(vals['number'], 23) finally:",
"with open(tmp_filename, 'w') as f: json.dump(j, f) try: jvs = ValueSource(tmp_filename) vals =",
"True) self.assertEqual(vals['fred'], 'wilma') self.assertEqual(vals['number'], 23) finally: if os.path.isfile(tmp_filename): os.remove(tmp_filename) def test_write_json(self): n =",
"<EMAIL> # <NAME>, <EMAIL> # # Alternatively, the contents of this file may",
"# the provisions above, a recipient may use your version of this file",
"\"from_string_converter\": \"configman.datetime_util.datetime_from_ISO_string\", \"name\": \"aaa\" } for key, value in expect_to_find.items(): self.assertEqual(jrec['aaa'][key], value) def",
"use_admin_controls=True, use_auto_help=False, argv_source=[]) config = c2.get_config() self.assertEqual(config.aaa, expected_date) self.assertEqual(config.bbb, -99) self.assertEqual(config.bbb_minus_one, -100) finally:",
"(the \"License\"); you may not use this file except in compliance with #",
"License. You may obtain a copy of the License at # http://www.mozilla.org/MPL/ #",
"from configman.value_sources.for_json import ValueSource #from ..value_sources.for_json import ValueSource def bbb_minus_one(config, local_config, args): return",
"this file under the terms of the MPL, indicate your # decision by",
"License is distributed on an \"AS IS\" basis, # WITHOUT WARRANTY OF ANY",
"terms of any one of the MPL, the GPL or the LGPL. #",
"GPL or the LGPL. If you do not delete # the provisions above,",
"from_string_converter=dtu.datetime_from_ISO_string ) def value_iter(): yield 'aaa', 'aaa', n.aaa s = StringIO() ValueSource.write(value_iter, output_stream=s)",
"import unittest import os import json import tempfile from cStringIO import StringIO import",
"the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"), #",
"configman # # The Initial Developer of the Original Code is # Mozilla",
"LGPL. If you do not delete # the provisions above, a recipient may",
"'the a', short_form='a', from_string_converter=int ) n.add_option('write', 'json') n.add_aggregation('bbb_minus_one', bbb_minus_one) #t = tempfile.NamedTemporaryFile('w', suffix='.json',",
") expected_date = dtu.datetime_from_ISO_string('2011-05-04T15:10:00') n.add_option('bbb', '37', 'the a', short_form='a', from_string_converter=int ) n.add_option('write', 'json')",
"a', short_form='a', from_string_converter=int ) n.add_option('write', 'json') n.add_aggregation('bbb_minus_one', bbb_minus_one) #t = tempfile.NamedTemporaryFile('w', suffix='.json', delete=False)",
"contents of this file are subject to the Mozilla Public License Version #",
"# 1.1 (the \"License\"); you may not use this file except in compliance",
"Developer. All Rights Reserved. # # Contributor(s): # <NAME>, <EMAIL> # <NAME>, <EMAIL>",
"# Alternatively, the contents of this file may be used under the terms",
"\"configman.datetime_util.datetime_from_ISO_string\", \"name\": \"aaa\" } for key, value in expect_to_find.items(): self.assertEqual(jrec['aaa'][key], value) def test_json_round_trip(self):",
"WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License #",
"'2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) expected_date = dtu.datetime_from_ISO_string('2011-05-04T15:10:00') n.add_option('bbb', '37', 'the a',",
"# <NAME>, <EMAIL> # <NAME>, <EMAIL> # # Alternatively, the contents of this",
"'w') as f: json.dump(j, f) try: jvs = ValueSource(tmp_filename) vals = jvs.get_values(None, True)",
"the provisions above and replace them with the notice # and other provisions",
"provisions above, a recipient may use your version of this file under #",
"# # Contributor(s): # <NAME>, <EMAIL> # <NAME>, <EMAIL> # # Alternatively, the",
"GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"), # in",
"import ValueSource #from ..value_sources.for_json import ValueSource def bbb_minus_one(config, local_config, args): return config.bbb -",
"file may be used under the terms of # either the GNU General",
"file under the terms of the MPL, indicate your # decision by deleting",
"the LGPL, and not to allow others to # use your version of",
"as config_manager import configman.datetime_util as dtu from configman.value_sources.for_json import ValueSource #from ..value_sources.for_json import",
"} with open(tmp_filename, 'w') as f: json.dump(j, f) try: jvs = ValueSource(tmp_filename) vals",
"\"doc\": \"the a\", \"value\": \"2011-05-04T15:10:00\", \"from_string_converter\": \"configman.datetime_util.datetime_from_ISO_string\", \"name\": \"aaa\" } for key, value",
"distributed under the License is distributed on an \"AS IS\" basis, # WITHOUT",
"\"a\", \"default\": \"2011-05-04T15:10:00\", \"doc\": \"the a\", \"value\": \"2011-05-04T15:10:00\", \"from_string_converter\": \"configman.datetime_util.datetime_from_ISO_string\", \"name\": \"aaa\" }",
"key, value in expect_to_find.items(): self.assertEqual(jrec['aaa'][key], value) def test_json_round_trip(self): n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00',",
"import StringIO import configman.config_manager as config_manager import configman.datetime_util as dtu from configman.value_sources.for_json import",
"\"aaa\" } for key, value in expect_to_find.items(): self.assertEqual(jrec['aaa'][key], value) def test_json_round_trip(self): n =",
"# ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 #",
"file except in compliance with # the License. You may obtain a copy",
"def value_iter(): yield 'aaa', 'aaa', n.aaa s = StringIO() ValueSource.write(value_iter, output_stream=s) received =",
"# and other provisions required by the GPL or the LGPL. If you",
"# # Alternatively, the contents of this file may be used under the",
"'2011-05-04T15:10:00', 'the a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) def value_iter(): yield 'aaa', 'aaa', n.aaa s",
"a', short_form='a', from_string_converter=dtu.datetime_from_ISO_string ) expected_date = dtu.datetime_from_ISO_string('2011-05-04T15:10:00') n.add_option('bbb', '37', 'the a', short_form='a', from_string_converter=int",
"d2 = {'bbb': '-99'} try: with open(name) as jfp: j = json.load(jfp) c2",
"the provisions above, a recipient may use your version of this file under",
"BLOCK ***** import unittest import os import json import tempfile from cStringIO import",
"as f: json.dump(j, f) try: jvs = ValueSource(tmp_filename) vals = jvs.get_values(None, True) self.assertEqual(vals['fred'],",
"by deleting the provisions above and replace them with the notice # and",
"this file may be used under the terms of # either the GNU",
"Initial Developer of the Original Code is # Mozilla Foundation # Portions created",
"name, 'w') c1 = config_manager.ConfigurationManager([n], [], use_admin_controls=True, use_auto_help=False, app_name='/tmp/test', app_version='0', app_description='', argv_source=[]) c1.write_conf('json',",
"'wilma') self.assertEqual(vals['number'], 23) finally: if os.path.isfile(tmp_filename): os.remove(tmp_filename) def test_write_json(self): n = config_manager.Namespace(doc='top') n.add_option('aaa',",
"the terms of # either the GNU General Public License Version 2 or",
"of this file are subject to the Mozilla Public License Version # 1.1",
"argv_source=[]) c1.write_conf('json', opener) d1 = {'bbb': 88} d2 = {'bbb': '-99'} try: with",
"try: with open(name) as jfp: j = json.load(jfp) c2 = config_manager.ConfigurationManager((j,), (d1, d2),",
"finally: if os.path.isfile(tmp_filename): os.remove(tmp_filename) def test_write_json(self): n = config_manager.Namespace(doc='top') n.add_option('aaa', '2011-05-04T15:10:00', 'the a',",
"Version 2 or later (the \"GPL\"), or # the GNU Lesser General Public",
"your # decision by deleting the provisions above and replace them with the",
"If you wish to allow use of your version of this file only",
"n.add_option('write', 'json') n.add_aggregation('bbb_minus_one', bbb_minus_one) #t = tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) name = '/tmp/test.json' import",
"with open(name) as jfp: j = json.load(jfp) c2 = config_manager.ConfigurationManager((j,), (d1, d2), use_admin_controls=True,",
"test_for_json_basics(self): tmp_filename = os.path.join(tempfile.gettempdir(), 'test.json') j = {'fred': 'wilma', 'number': 23, } with",
"'aaa', n.aaa s = StringIO() ValueSource.write(value_iter, output_stream=s) received = s.getvalue() s.close() jrec =",
"the terms of either the GPL or the LGPL, and not to allow",
"of the License at # http://www.mozilla.org/MPL/ # # Software distributed under the License",
"and other provisions required by the GPL or the LGPL. If you do",
"General Public License Version 2.1 or later (the \"LGPL\"), # in which case",
"# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License",
"# Portions created by the Initial Developer are Copyright (C) 2011 # the",
"or the LGPL are applicable instead # of those above. If you wish",
"tempfile from cStringIO import StringIO import configman.config_manager as config_manager import configman.datetime_util as dtu",
"provisions above and replace them with the notice # and other provisions required"
] |
[
"<gh_stars>0 a = input() b = '<PASSWORD>' if a == b: print('Welcome') else:",
"= input() b = '<PASSWORD>' if a == b: print('Welcome') else: print('Wrong password!')",
"a = input() b = '<PASSWORD>' if a == b: print('Welcome') else: print('Wrong"
] |
[
"bl_idname = 'uvpackmaster2.uv_similarity_detection_help' bl_description = \"Show help for similarity detection\" URL_SUFFIX = \"similarity-detection\"",
"after packing (check the selected islands). Consider increasing the 'Precision' parameter. Sometimes increasing",
"0: self.last_msg_time = curr_time self.hang_detected = False else: if self.curr_phase != UvPackingPhaseCode.RENDER_PRESENTATION and",
"raise OpAbortedException() if self.handle_event_spec(event): return # Generic event processing code if event.type ==",
"help for setting margin in pixels\" URL_SUFFIX = \"pixel-margin\" class UVP2_OT_IslandRotStepHelp(UVP2_OT_Help): bl_label =",
"\"uvp-setup\" class UVP2_OT_HeuristicSearchHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing Help' bl_idname = 'uvpackmaster2.uv_heuristic_search_help' bl_description =",
"os_uvp_creation_flags() popen_args = dict() if creation_flags is not None: popen_args['creationflags'] = creation_flags self.uvp_proc",
"= (False, False, True) else: self.p_context.context.tool_settings.uv_select_mode = 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) if invalid_face_count",
"result) ' else: end_str = '(press ESC to cancel) ' return header_str +",
"= self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None if active_dev is None: raise",
"elif msg_code == UvPackMessageCode.INVALID_ISLANDS: if self.invalid_islands_msg is not None: self.raiseUnexpectedOutputError() self.invalid_islands_msg = msg",
"= 'Packing done' if self.area is not None: op_status += ', packed islands",
"each other' def process_result(self): if self.island_flags_msg is None: self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg) overlap_detected,",
"'INFO' op_status = self.op_status if len(self.op_warnings) > 0: if op_status_type == 'INFO': op_status_type",
"force_read_int(msg) stats.total_time = force_read_int(msg) stats.avg_time = force_read_int(msg) return True return False def handle_event_spec(self,",
"LICENSE BLOCK ##### # # This program is free software; you can redistribute",
"= None self.op_status_type = None self.op_status = None self.op_warnings = [] try: if",
"False @classmethod def poll(cls, context): prefs = get_prefs() return prefs.uvp_initialized and context.active_object is",
"progress monitor thread self.progress_queue = queue.Queue() self.connection_thread = threading.Thread(target=connection_thread_func, args=(self.uvp_proc.stdout, self.progress_queue)) self.connection_thread.daemon =",
"abort)' if self.curr_phase is None: return False progress_msg_spec = self.get_progress_msg_spec() if progress_msg_spec: return",
"str(tile_count)] if self.prefs.tiles_enabled(self.scene_props): uvp_args += ['-C', str(tiles_in_row)] if self.grouping_enabled(): if to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.SIMILARITY:",
"UvPackMessageCode.INVALID_ISLANDS: if self.invalid_islands_msg is not None: self.raiseUnexpectedOutputError() self.invalid_islands_msg = msg elif msg_code ==",
"elif msg_code == UvPackMessageCode.ISLAND_FLAGS: if self.island_flags_msg is not None: self.raiseUnexpectedOutputError() self.island_flags_msg = msg",
"if self.prefs.FEATURE_advanced_heuristic and self.scene_props.advanced_heuristic: uvp_args.append('-H') uvp_args += ['-g', self.scene_props.pack_mode] tile_count, tiles_in_row = self.prefs.tile_grid_config(self.scene_props,",
"packing to a non-square texture. For for info regarding non-square packing click the",
"event.type == 'TIMER': self.handle_communication() def modal(self, context, event): cancel = False finish =",
"invalid_face_count > 0: # Switch to the face selection mode if self.p_context.context.tool_settings.use_uv_select_sync: self.p_context.context.tool_settings.mesh_select_mode",
"return False def get_group_method(self): raise RuntimeError('Unexpected grouping requested') def send_rot_step(self): return False def",
"'%, ' percent_progress_str = percent_progress_str[:-2] progress_str = 'Pack progress: {} '.format(percent_progress_str) if self.area",
"help button\" def get_confirmation_msg(self): if self.prefs.FEATURE_demo: return 'WARNING: in the demo mode only",
"= self.progress_queue.get_nowait() except queue.Empty as ex: break if isinstance(item, str): raise RuntimeError(item) elif",
"uvp_args_final += ['-S', str(self.prefs.seed)] if self.prefs.wait_for_debugger: uvp_args_final.append('-G') uvp_args_final += ['-T', str(self.prefs.test_param)] print('Pakcer args:",
"device is not supported in this engine edition') # Validate pack mode pack_mode",
"reported, islands will not be selected. Click OK to continue' return '' def",
"RuntimeError(\"'Pre-Rotation Disable' option must be off in order to group by similarity\") if",
"UvPackMessageCode.PACK_SOLUTION: pack_solution = read_pack_solution(msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) return True elif msg_code == UvPackMessageCode.BENCHMARK: stats",
"invalid faces found is reported, invalid faces will not be selected. Click OK",
"def send_rot_step(self): return False def lock_groups_enabled(self): return False def send_verts_3d(self): return False def",
"= 'TIMER' self.value = 'NOTHING' self.ctrl = False while True: event = FakeTimerEvent()",
"== UvPackingPhaseCode.RENDER_PRESENTATION: return 'Close the demo window to finish' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_VALIDATION:",
"= self.get_progress_msg() if not new_progress_msg: return now = time.time() if now - self.progress_last_update_time",
"UVP2_OT_UndoIslandsAdjustemntToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_undo_islands_adjustment_to_texture' bl_label = 'Undo Islands Adjustment' bl_description = \"Undo adjustment",
"= UvPackingPhaseCode.INITIALIZATION self.invalid_islands_msg = None self.island_flags_msg = None self.pack_solution_msg = None self.area_msg =",
"if invalid_face_count > 0: # Switch to the face selection mode if self.p_context.context.tool_settings.use_uv_select_sync:",
"should have received a copy of the GNU General Public License # along",
"progress_size > len(self.progress_array): self.progress_array = [0] * (progress_size) for i in range(progress_size): self.progress_array[i]",
"dict() if creation_flags is not None: popen_args['creationflags'] = creation_flags self.uvp_proc = subprocess.Popen(uvp_args_final, stdin=subprocess.PIPE,",
"def get_scale_factors(self): return (1.0, 1.0) class UVP2_OT_AdjustIslandsToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_adjust_islands_to_texture' bl_label = 'Adjust",
"either version 2 # of the License, or (at your option) any later",
"BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you",
"URL_SUFFIX = \"island-rotation-step\" class UVP2_OT_UdimSupportHelp(UVP2_OT_Help): bl_label = 'UDIM Support Help' bl_idname = 'uvpackmaster2.uv_udim_support_help'",
"selected') else: if selected_cnt + unselected_cnt == 0: raise NoUvFaceError('No UV face visible')",
"UvPackingPhaseCode.VALIDATION: return \"Per-face overlap check: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) raise RuntimeError('Unexpected packing",
"uvp_args = ['-o', str(self.get_uvp_opcode()), '-I', str(self.scene_props.similarity_threshold)] uvp_args += ['-i', str(self.scene_props.precision)] uvp_args += ['-r',",
"self.report({'ERROR'}, str(ex)) except Exception as ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, 'Unexpected error') self.p_context.update_meshes()",
"self._timer = wm.event_timer_add(self.MODAL_INTERVAL_S, window=context.window) wm.modal_handler_add(self) return {'RUNNING_MODAL'} class FakeTimerEvent: def __init__(self): self.type =",
"by similarity\") if self.scene_props.prerot_disable: raise RuntimeError(\"'Pre-Rotation Disable' option must be off in order",
"ratio, 1.0) class UVP2_OT_UndoIslandsAdjustemntToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_undo_islands_adjustment_to_texture' bl_label = 'Undo Islands Adjustment' bl_description",
"uvp_args class UVP2_OT_ProcessSimilar(UVP2_OT_PackOperatorGeneric): def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(self.get_uvp_opcode()), '-I',",
"self.set_status('WARNING', 'Pre-validation failed. Number of invalid faces found: ' + str(invalid_face_count) + '.",
"'wb') out_file.write(self.p_context.serialized_maps) out_file.close() uvp_args_final = [get_uvp_execpath(), '-E', '-e', str(UvTopoAnalysisLevel.FORCE_EXTENDED), '-t', str(self.prefs.thread_count)] + self.get_uvp_args()",
"= curr_time self.hang_detected = False else: if self.curr_phase != UvPackingPhaseCode.RENDER_PRESENTATION and curr_time -",
"read_int_array(self.invalid_faces_msg) if not self.prefs.FEATURE_demo: if len(invalid_faces) != invalid_face_count: self.raiseUnexpectedOutputError() if invalid_face_count > 0:",
"self.op_done: return msg_refresh_interval = 2.0 new_progress_msg = self.get_progress_msg() if not new_progress_msg: return now",
"if ret.intersection({'FINISHED', 'CANCELLED'}): return ret time.sleep(self.MODAL_INTERVAL_S) def invoke(self, context, event): self.interactive = True",
"try: self.uvp_proc.wait(5) except: raise RuntimeError('The UVP process wait timeout reached') self.connection_thread.join() self.check_uvp_retcode(self.uvp_proc.returncode) if",
"aligned') class UVP2_OT_ScaleIslands(bpy.types.Operator): bl_options = {'UNDO'} @classmethod def poll(cls, context): return context.active_object is",
"Help' bl_idname = 'uvpackmaster2.uv_heuristic_search_help' bl_description = \"Show help for heuristic search\" URL_SUFFIX =",
"return '' def send_unselected_islands(self): return self.prefs.pack_to_others_enabled(self.scene_props) def grouping_enabled(self): return self.prefs.grouping_enabled(self.scene_props) def get_group_method(self): return",
"'Island Rotation Step Help' bl_idname = 'uvpackmaster2.uv_island_rot_step_help' bl_description = \"Show help for setting",
"thread') msg_received += 1 curr_time = time.time() if msg_received > 0: self.last_msg_time =",
"if self.interactive: wm = self.p_context.context.window_manager wm.event_timer_remove(self._timer) self.p_context.update_meshes() self.report_status() if in_debug_mode(): print('UVP operation time:",
"pack process') def set_status(self, status_type, status): self.op_status_type = status_type self.op_status = status def",
"None: self.raiseUnexpectedOutputError() self.island_flags_msg = msg elif msg_code == UvPackMessageCode.PACK_SOLUTION: if self.pack_solution_msg is not",
"['-y', str(self.prefs.pixel_margin_tex_size(self.scene_props, self.p_context.context))] if self.prefs.pixel_padding_enabled(self.scene_props): uvp_args += ['-N', str(self.scene_props.pixel_padding)] uvp_args += ['-W', self.scene_props.pixel_margin_method]",
"and active_dev.id.startswith('cuda'): return UvpLabels.CUDA_MACOS_CONFIRM_MSG if self.prefs.pack_groups_together(self.scene_props) and not self.prefs.heuristic_enabled(self.scene_props): return UvpLabels.GROUPS_TOGETHER_CONFIRM_MSG return ''",
"else: iter_str = '' if self.progress_sec_left >= 0: time_left_str = \"Time left: {}",
"islands were detected after packing (check the selected islands). Consider increasing the 'Precision'",
"self.raiseUnexpectedOutputError() self.invalid_islands_msg = msg elif msg_code == UvPackMessageCode.ISLAND_FLAGS: if self.island_flags_msg is not None:",
"* from .island_params import * from .labels import UvpLabels from .register import check_uvp,",
"'. Packing aborted') return if not self.prefs.FEATURE_demo: if self.island_flags_msg is None: self.raiseUnexpectedOutputError() island_flags",
"self.p_context.context.tool_settings.uv_select_mode = 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) if invalid_face_count > 0: self.set_status('WARNING', 'Pre-validation failed.",
"else: end_str = '(press ESC to cancel) ' return header_str + iter_str +",
"if self.curr_phase == UvPackingPhaseCode.SIMILAR_ALIGNING: return 'Similar islands aligning (press ESC to cancel)' if",
"== 'ESC': raise OpAbortedException() if self.handle_event_spec(event): return # Generic event processing code if",
"try: if not check_uvp(): unregister_uvp() redraw_ui(context) raise RuntimeError(\"UVP engine broken\") reset_stats(self.prefs) self.p_context =",
"only when packing to a non-square texture. For for info regarding non-square packing",
"uvp process is alive if not self.op_done and self.uvp_proc.poll() is not None: #",
"the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA",
"to a small value and the 'Adjustment Time' is not long enough.\") def",
"len(similar_islands) != similar_island_count: self.raiseUnexpectedOutputError() for island_idx in similar_islands: self.p_context.select_island_faces(island_idx, self.p_context.uv_island_faces_list[island_idx], True) else: if",
"will not be selected. Click OK to continue' return '' def process_result(self): if",
"= read_int_array(self.island_flags_msg) overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags) if self.area is not None: self.prefs.stats_area =",
"check: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) raise RuntimeError('Unexpected packing phase encountered') def handle_uvp_msg_spec(self,",
"Check whether the uvp process is alive if not self.op_done and self.uvp_proc.poll() is",
"str(invalid_face_count) + '. Packing aborted') return if not self.prefs.FEATURE_demo: if self.island_flags_msg is None:",
"+= ['-Q'] if in_debug_mode(): if self.prefs.seed > 0: uvp_args_final += ['-S', str(self.prefs.seed)] if",
"bl_description = \"Selects all islands which have similar shape to islands which are",
"is not None: end_str = '(press ESC to apply result) ' else: end_str",
"Packing aborted') return if not self.prefs.FEATURE_demo: if self.island_flags_msg is None: self.raiseUnexpectedOutputError() island_flags =",
"+ str(time.time() - self.start_time)) def read_islands(self, islands_msg): islands = [] island_cnt = force_read_int(islands_msg)",
"process unconditionally if a hang was detected if self.hang_detected and event.type == 'ESC':",
"percent_progress_str = percent_progress_str[:-2] progress_str = 'Pack progress: {} '.format(percent_progress_str) if self.area is not",
"+ 50 return wm.invoke_props_dialog(self, width=dialog_width) return self.execute(context) def draw(self, context): layout = self.layout",
"str(self.pack_ratio)] return uvp_args class UVP2_OT_SelectSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_select_similar' bl_label = 'Select Similar' bl_description",
"ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.RENDER_PRESENTATION: return 'Close the demo window to",
"UvPackingPhaseCode.RENDER_PRESENTATION: return 'Close the demo window to finish' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_VALIDATION: return",
"\".format(self.progress_sec_left) else: time_left_str = '' percent_progress_str = '' for prog in self.progress_array: percent_progress_str",
"10.0 # Start progress monitor thread self.progress_queue = queue.Queue() self.connection_thread = threading.Thread(target=connection_thread_func, args=(self.uvp_proc.stdout,",
"import queue import threading import signal import webbrowser from .utils import * from",
"retcode == UvPackerErrorCode.MAX_GROUP_COUNT_EXCEEDED: raise RuntimeError(\"Maximal group count exceeded\") if retcode == UvPackerErrorCode.DEVICE_NOT_SUPPORTED: raise",
"overlap_detected = False outside_detected = False if self.invalid_faces_msg is not None: invalid_face_count =",
"= 'uvpackmaster2.uv_overlap_check' bl_label = 'Overlap Check' bl_description = 'Check wheter selected UV islands",
"0: self.set_status('WARNING', 'Number of invalid faces found: ' + str(invalid_face_count)) else: self.set_status('INFO', 'No",
"process_result(self): if self.prefs.FEATURE_demo: return if self.pack_solution_msg is None: self.raiseUnexpectedOutputError() pack_solution = read_pack_solution(self.pack_solution_msg) self.p_context.apply_pack_solution(self.pack_ratio,",
"self.add_warning(\"Some islands are outside their packing box after packing (check the selected islands).",
"get_active_image_ratio(self.p_context.context) uvp_args += ['-q', str(self.pack_ratio)] return uvp_args class UVP2_OT_SelectSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_select_similar' bl_label",
"pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.OVERLAP_CHECK)] return uvp_args class UVP2_OT_MeasureAreaOperator(UVP2_OT_PackOperatorGeneric): bl_idname =",
"['-w'] else: rot_step_value = -1 uvp_args += ['-r', str(rot_step_value)] if self.prefs.heuristic_enabled(self.scene_props): uvp_args +=",
"= ['-o', str(UvPackerOpcode.OVERLAP_CHECK)] return uvp_args class UVP2_OT_MeasureAreaOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_measure_area' bl_label = 'Measure",
"found is reported, invalid faces will not be selected. Click OK to continue'",
"get_prefs() return prefs.uvp_initialized and context.active_object is not None and context.active_object.mode == 'EDIT' def",
"InvalidIslandsError as err: self.set_status('ERROR', str(err)) cancel = True except RuntimeError as ex: if",
"OpFinishedException() def finish(self, context): self.exit_common() return {'FINISHED', 'PASS_THROUGH'} def cancel(self, context): self.uvp_proc.terminate() #",
"+ str(area)) def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.MEASURE_AREA)] return uvp_args",
"self.prefs.seed > 0: uvp_args_final += ['-S', str(self.prefs.seed)] if self.prefs.wait_for_debugger: uvp_args_final.append('-G') uvp_args_final += ['-T',",
"None self.pack_ratio = 1.0 self.target_box = None self.op_status_type = None self.op_status = None",
"msg elif msg_code == UvPackMessageCode.ISLANDS: self.read_islands(msg) elif msg_code == UvPackMessageCode.ISLANDS_METADATA: if self.islands_metadata_msg is",
"event): return False def handle_progress_msg(self): if self.op_done: return msg_refresh_interval = 2.0 new_progress_msg =",
"UvPackerErrorCode.INVALID_ISLANDS, UvPackerErrorCode.NO_SPACE, UvPackerErrorCode.PRE_VALIDATION_FAILED}: return if retcode == UvPackerErrorCode.CANCELLED: raise OpCancelledException() if retcode ==",
"OpAbortedException: self.set_status('INFO', 'Packer process killed') cancel = True except OpCancelledException: self.set_status('INFO', 'Operation cancelled",
"UvpLabels.CUDA_MACOS_CONFIRM_MSG if self.prefs.pack_groups_together(self.scene_props) and not self.prefs.heuristic_enabled(self.scene_props): return UvpLabels.GROUPS_TOGETHER_CONFIRM_MSG return '' def send_unselected_islands(self): return",
"class UVP2_OT_ValidateOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_validate' bl_label = 'Validate UVs' bl_description = 'Validate selected",
"# You should have received a copy of the GNU General Public License",
"= read_int_array(self.invalid_islands_msg) if len(invalid_islands) == 0: self.raiseUnexpectedOutputError() self.p_context.handle_invalid_islands(invalid_islands) if code == UvInvalidIslandCode.TOPOLOGY: error_msg",
"RuntimeError(\"Maximal group count exceeded\") if retcode == UvPackerErrorCode.DEVICE_NOT_SUPPORTED: raise RuntimeError(\"Selected device is not",
"args: ' + ' '.join(x for x in uvp_args_final)) creation_flags = os_uvp_creation_flags() popen_args",
"raise RuntimeError('The UVP process wait timeout reached') self.connection_thread.join() self.check_uvp_retcode(self.uvp_proc.returncode) if not self.p_context.islands_received(): self.raiseUnexpectedOutputError()",
"increasing the 'Precision' parameter. Sometimes increasing the 'Adjustment Time' may solve the problem",
"bl_label = 'Similarity Detection Help' bl_idname = 'uvpackmaster2.uv_similarity_detection_help' bl_description = \"Show help for",
"== 0: raise NoUvFaceError('No UV face visible') self.validate_pack_params() if self.prefs.write_to_file: out_filepath = os.path.join(tempfile.gettempdir(),",
"not new_progress_msg: return now = time.time() if now - self.progress_last_update_time > msg_refresh_interval or",
"# Validate pack mode pack_mode = UvPackingMode.get_mode(self.scene_props.pack_mode) if pack_mode.req_feature != '' and not",
"bl_label = 'Align Similar' bl_description = \"Align selected islands, so islands which are",
"is None: self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg) overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags) if self.area is",
"'Invalid Topology Help' bl_idname = 'uvpackmaster2.uv_invalid_topology_help' bl_description = \"Show help for handling invalid",
"bl_idname = 'uvpackmaster2.uv_heuristic_search_help' bl_description = \"Show help for heuristic search\" URL_SUFFIX = \"heuristic-search\"",
"ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_ALIGNING: return 'Similar islands aligning (press ESC",
"round(target_box[0].y, prec), round(target_box[1].x, prec), round(target_box[1].y, prec)) def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.PACK), '-i',",
"non-square texture. For for info regarding non-square packing click the help icon\" def",
"'Check wheter selected UV islands overlap each other' def process_result(self): if self.island_flags_msg is",
"return UvpLabels.GROUPS_TOGETHER_CONFIRM_MSG return '' def send_unselected_islands(self): return self.prefs.pack_to_others_enabled(self.scene_props) def grouping_enabled(self): return self.prefs.grouping_enabled(self.scene_props) def",
"self.set_status('WARNING', 'Overlapping islands detected') else: self.set_status('INFO', 'No overlapping islands detected') def validate_pack_params(self): pass",
"reached') self.connection_thread.join() self.check_uvp_retcode(self.uvp_proc.returncode) if not self.p_context.islands_received(): self.raiseUnexpectedOutputError() self.process_invalid_islands() self.process_result() if self.finish_after_op_done(): raise OpFinishedException()",
"died unexpectedly') self.handle_progress_msg() except OpFinishedException: finish = True except: raise if finish: return",
"= force_read_int(self.similar_islands_msg) similar_islands = read_int_array(self.similar_islands_msg) if not self.prefs.FEATURE_demo: if len(similar_islands) != similar_island_count: self.raiseUnexpectedOutputError()",
"(press ESC to cancel)\".format(self.progress_array[0]) raise RuntimeError('Unexpected packing phase encountered') def handle_uvp_msg_spec(self, msg_code, msg):",
"get_active_image_ratio(self.p_context.context) return (ratio, 1.0) class UVP2_OT_Help(bpy.types.Operator): bl_label = 'Help' def execute(self, context): webbrowser.open(UvpLabels.HELP_BASEURL",
"1.0) class UVP2_OT_UndoIslandsAdjustemntToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_undo_islands_adjustment_to_texture' bl_label = 'Undo Islands Adjustment' bl_description =",
"UvPackMessageCode.AREA: self.area = self.read_area(msg) return True elif msg_code == UvPackMessageCode.PACK_SOLUTION: pack_solution = read_pack_solution(msg)",
"self.prefs.FEATURE_target_box and self.prefs.target_box_enable: validate_target_box(self.scene_props) def get_target_box_string(self, target_box): prec = 4 return \"{}:{}:{}:{}\".format( round(target_box[0].x,",
"Margin Help' bl_idname = 'uvpackmaster2.uv_pixel_margin_help' bl_description = \"Show help for setting margin in",
"RuntimeError(\"UVP engine broken\") reset_stats(self.prefs) self.p_context = PackContext(context) self.pre_op_initialize() send_unselected = self.send_unselected_islands() send_rot_step =",
"= force_read_int(msg) stats.total_time = force_read_int(msg) stats.avg_time = force_read_int(msg) return True return False def",
"(press ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.OVERLAP_CHECK: return 'Overlap check in progress",
"return False progress_msg_spec = self.get_progress_msg_spec() if progress_msg_spec: return progress_msg_spec if self.curr_phase == UvPackingPhaseCode.INITIALIZATION:",
"if self.progress_iter_done >= 0: iter_str = 'Iter. done: {}. '.format(self.progress_iter_done) else: iter_str =",
"= self.send_rot_step() send_groups = self.grouping_enabled() and (to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.EXTERNAL) send_lock_groups = self.lock_groups_enabled() send_verts_3d",
"except InvalidIslandsError as err: self.set_status('ERROR', str(err)) cancel = True except RuntimeError as ex:",
"= force_read_int(self.invalid_faces_msg) invalid_faces = read_int_array(self.invalid_faces_msg) if not self.prefs.FEATURE_demo: if len(invalid_faces) != invalid_face_count: self.raiseUnexpectedOutputError()",
"The validation procedure looks for invalid UV faces i.e. faces with area close",
"msg): if msg_code == UvPackMessageCode.AREA: self.area = self.read_area(msg) return True elif msg_code ==",
"the help button\" def get_uvp_opcode(self): return UvPackerOpcode.ALIGN_SIMILAR def process_result(self): if self.prefs.FEATURE_demo: return if",
"str(self.get_uvp_opcode()), '-I', str(self.scene_props.similarity_threshold)] uvp_args += ['-i', str(self.scene_props.precision)] uvp_args += ['-r', str(90)] if self.prefs.pack_ratio_enabled(self.scene_props):",
"in self.progress_array: percent_progress_str += str(prog).rjust(3, ' ') + '%, ' percent_progress_str = percent_progress_str[:-2]",
"= context.scene.uvp2_props self.p_context = None self.pack_ratio = 1.0 self.target_box = None self.op_status_type =",
"self.p_context.set_islands(selected_cnt, islands) def process_invalid_islands(self): if self.uvp_proc.returncode != UvPackerErrorCode.INVALID_ISLANDS: return if self.invalid_islands_msg is None:",
"None: raise RuntimeError('Could not find a packing device') if not active_dev.supported: raise RuntimeError('Selected",
"check was performed only on the islands which were packed\") else: op_status =",
"if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_ANALYSIS: return \"Topology analysis: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) if",
"not self.cancel_sig_sent: self.uvp_proc.send_signal(os_cancel_sig()) self.cancel_sig_sent = True return True return False def process_result(self): overlap_detected",
"UV face selected') else: if selected_cnt + unselected_cnt == 0: raise NoUvFaceError('No UV",
"software; you can redistribute it and/or # modify it under the terms of",
"of selected UV islands' def process_result(self): if self.area_msg is None: self.raiseUnexpectedOutputError() area =",
"return {'RUNNING_MODAL'} if not self.op_done else {'PASS_THROUGH'} def pre_op_initialize(self): pass def execute(self, context):",
"uvp_args_final += ['-Q'] if in_debug_mode(): if self.prefs.seed > 0: uvp_args_final += ['-S', str(self.prefs.seed)]",
"['-T', str(self.prefs.test_param)] print('Pakcer args: ' + ' '.join(x for x in uvp_args_final)) creation_flags",
"stats.iter_count = force_read_int(msg) stats.total_time = force_read_int(msg) stats.avg_time = force_read_int(msg) return True return False",
"['-F', self.scene_props.fixed_scale_strategy] if self.prefs.FEATURE_island_rotation: if self.scene_props.rot_enable: rot_step_value = self.scene_props.rot_step if self.scene_props.prerot_disable: uvp_args +=",
"+= ['-w'] else: rot_step_value = -1 uvp_args += ['-r', str(rot_step_value)] if self.prefs.heuristic_enabled(self.scene_props): uvp_args",
"# Special value indicating a crash self.prefs.uvp_retcode = -1 raise RuntimeError('Packer process died",
"if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: self.target_box = self.prefs.target_box(self.scene_props) if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) if",
"is not None: invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces = read_int_array(self.invalid_faces_msg) if not self.prefs.FEATURE_demo: if",
"so they are suitable for packing into the active texture. CAUTION: this operator",
"continue' return '' def send_unselected_islands(self): return True def get_uvp_opcode(self): return UvPackerOpcode.SELECT_SIMILAR def process_result(self):",
"self.op_status_type is not None else 'INFO' op_status = self.op_status if len(self.op_warnings) > 0:",
"device') if not active_dev.supported: raise RuntimeError('Selected packing device is not supported in this",
"cancel(self, context): self.uvp_proc.terminate() # self.progress_thread.terminate() self.exit_common() return {'FINISHED'} def get_progress_msg_spec(self): return False def",
"bl_label = 'Overlap Check' bl_description = 'Check wheter selected UV islands overlap each",
"True except: raise if finish: return self.finish(context) except OpAbortedException: self.set_status('INFO', 'Packer process killed')",
"0: self.raiseUnexpectedOutputError() self.set_status('INFO', 'Similar islands found: ' + str(similar_island_count)) class UVP2_OT_AlignSimilar(UVP2_OT_ProcessSimilar): bl_idname =",
"self.grouping_enabled() and (to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.EXTERNAL) send_lock_groups = self.lock_groups_enabled() send_verts_3d = self.send_verts_3d() selected_cnt, unselected_cnt",
"so islands are again suitable for packing into a square texture. For for",
"the number of similar islands found is reported, islands will not be selected.",
"self.layout col = layout.column() col.label(text=self.confirmation_msg) def get_confirmation_msg(self): return '' def send_unselected_islands(self): return False",
"'Operation cancelled by the user') cancel = True except InvalidIslandsError as err: self.set_status('ERROR',",
"the Help panel to learn more\" elif code == UvInvalidIslandCode.INT_PARAM: param_array = IslandParamInfo.get_param_info_array()",
"self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) if self.pack_ratio != 1.0: uvp_args += ['-q', str(self.pack_ratio)] if",
"not None: popen_args['creationflags'] = creation_flags self.uvp_proc = subprocess.Popen(uvp_args_final, stdin=subprocess.PIPE, stdout=subprocess.PIPE, **popen_args) out_stream =",
"for UVP setup\" URL_SUFFIX = \"uvp-setup\" class UVP2_OT_HeuristicSearchHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing Help'",
"UVP2_OT_PixelMarginHelp(UVP2_OT_Help): bl_label = 'Pixel Margin Help' bl_idname = 'uvpackmaster2.uv_pixel_margin_help' bl_description = \"Show help",
"return 'Close the demo window to finish' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_VALIDATION: return \"Topology",
"' return header_str + iter_str + time_left_str + progress_str + end_str return False",
"= 'Check wheter selected UV islands overlap each other' def process_result(self): if self.island_flags_msg",
"self.p_context.handle_island_flags(island_flags) if overlap_detected: self.set_status('WARNING', 'Overlapping islands detected') else: self.set_status('INFO', 'No overlapping islands detected')",
"\"Show help for setting rotation step on per-island level\" URL_SUFFIX = \"island-rotation-step\" class",
"import signal import webbrowser from .utils import * from .pack_context import * from",
"str(prog).rjust(3, ' ') + '%, ' percent_progress_str = percent_progress_str[:-2] progress_str = 'Pack progress:",
"self.prefs.FEATURE_advanced_heuristic and self.scene_props.advanced_heuristic: uvp_args.append('-H') uvp_args += ['-g', self.scene_props.pack_mode] tile_count, tiles_in_row = self.prefs.tile_grid_config(self.scene_props, self.p_context.context)",
"= 'Undo Islands Adjustment' bl_description = \"Undo adjustment performed by the 'Adjust Islands",
"if platform.system() == 'Darwin': active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None",
"if self.prefs.FEATURE_demo: return if self.pack_solution_msg is None: self.raiseUnexpectedOutputError() pack_solution = read_pack_solution(self.pack_solution_msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution)",
"help for UDIM support\" URL_SUFFIX = \"udim-support\" class UVP2_OT_ManualGroupingHelp(UVP2_OT_Help): bl_label = 'Manual Grouping",
"ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.AREA_MEASUREMENT: return 'Area measurement in progress (press",
"if in_debug_mode(): print('UVP operation time: ' + str(time.time() - self.start_time)) def read_islands(self, islands_msg):",
"packing box\") if retcode == UvPackerErrorCode.MAX_GROUP_COUNT_EXCEEDED: raise RuntimeError(\"Maximal group count exceeded\") if retcode",
"def handle_event_spec(self, event): return False def handle_progress_msg(self): if self.op_done: return msg_refresh_interval = 2.0",
"all islands which have similar shape to islands which are already selected. For",
"str(ex)) except Exception as ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, 'Unexpected error') self.p_context.update_meshes() return",
"context): self.exit_common() return {'FINISHED', 'PASS_THROUGH'} def cancel(self, context): self.uvp_proc.terminate() # self.progress_thread.terminate() self.exit_common() return",
"RuntimeError(\"Selected device doesn't support packing groups together\") raise RuntimeError('Pack process returned an error')",
"# # This program is free software; you can redistribute it and/or #",
"not getattr(self.prefs, 'FEATURE_' + pack_mode.req_feature): raise RuntimeError('Selected packing mode is not supported in",
"self.prefs.pixel_margin_enabled(self.scene_props): uvp_args += ['-M', str(self.scene_props.pixel_margin)] uvp_args += ['-y', str(self.prefs.pixel_margin_tex_size(self.scene_props, self.p_context.context))] if self.prefs.pixel_padding_enabled(self.scene_props): uvp_args",
"return {'FINISHED'} class UVP2_OT_UvpSetupHelp(UVP2_OT_Help): bl_label = 'UVP Setup Help' bl_idname = 'uvpackmaster2.uv_uvp_setup_help' bl_description",
"None self.area_msg = None self.invalid_faces_msg = None self.similar_islands_msg = None self.islands_metadata_msg = None",
"UV face visible') self.validate_pack_params() if self.prefs.write_to_file: out_filepath = os.path.join(tempfile.gettempdir(), 'uv_islands.data') out_file = open(out_filepath,",
"= 'uvpackmaster2.uv_measure_area' bl_label = 'Measure Area' bl_description = 'Measure area of selected UV",
"'Current area: {}. '.format(self.area if self.area is not None else 'none') else: header_str",
"not find a packing device') if not active_dev.supported: raise RuntimeError('Selected packing device is",
"\"Adjust scale of selected islands so they are suitable for packing into the",
"== UvPackMessageCode.ISLAND_FLAGS: if self.island_flags_msg is not None: self.raiseUnexpectedOutputError() self.island_flags_msg = msg elif msg_code",
"uvp_args = ['-o', str(UvPackerOpcode.MEASURE_AREA)] return uvp_args class UVP2_OT_ValidateOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_validate' bl_label =",
"send_groups else None) if self.require_selection(): if selected_cnt == 0: raise NoUvFaceError('No UV face",
"# Switch to the face selection mode if self.p_context.context.tool_settings.use_uv_select_sync: self.p_context.context.tool_settings.mesh_select_mode = (False, False,",
"packing mode is not supported in this engine edition') if self.grouping_enabled(): if self.get_group_method()",
"self.pack_solution_msg is not None: self.raiseUnexpectedOutputError() self.pack_solution_msg = msg elif msg_code == UvPackMessageCode.AREA: if",
"not supported\") if retcode == UvPackerErrorCode.DEVICE_DOESNT_SUPPORT_GROUPS_TOGETHER: raise RuntimeError(\"Selected device doesn't support packing groups",
"for handling invalid topology errors\" URL_SUFFIX = \"invalid-topology-issues\" class UVP2_OT_PixelMarginHelp(UVP2_OT_Help): bl_label = 'Pixel",
"uvp_args_final.append('-G') uvp_args_final += ['-T', str(self.prefs.test_param)] print('Pakcer args: ' + ' '.join(x for x",
"if self.islands_metadata_msg is not None: self.raiseUnexpectedOutputError() self.islands_metadata_msg = msg else: self.raiseUnexpectedOutputError() def handle_communication(self):",
"self.pack_ratio = 1.0 self.target_box = None self.op_status_type = None self.op_status = None self.op_warnings",
"self.confirmation_msg = self.get_confirmation_msg() wm = context.window_manager if self.confirmation_msg != '': pix_per_char = 5",
"= queue.Queue() self.connection_thread = threading.Thread(target=connection_thread_func, args=(self.uvp_proc.stdout, self.progress_queue)) self.connection_thread.daemon = True self.connection_thread.start() self.progress_array =",
"the selected islands). Consider increasing the 'Precision' parameter. Sometimes increasing the 'Adjustment Time'",
"= 'NOTHING' self.ctrl = False while True: event = FakeTimerEvent() ret = self.modal(context,",
"== UvPackerErrorCode.DEVICE_NOT_SUPPORTED: raise RuntimeError(\"Selected device is not supported\") if retcode == UvPackerErrorCode.DEVICE_DOESNT_SUPPORT_GROUPS_TOGETHER: raise",
"layer wheter it should finish if self.curr_phase == UvPackingPhaseCode.DONE: self.handle_op_done() elif msg_code ==",
"self.raiseUnexpectedOutputError() invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces = read_int_array(self.invalid_faces_msg) if not self.prefs.FEATURE_demo: if len(invalid_faces) !=",
"'Similar islands aligning (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.RENDER_PRESENTATION: return 'Close",
"return uvp_args class UVP2_OT_ValidateOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_validate' bl_label = 'Validate UVs' bl_description =",
"self.start_time)) def read_islands(self, islands_msg): islands = [] island_cnt = force_read_int(islands_msg) selected_cnt = force_read_int(islands_msg)",
"detection click the help button\" def get_confirmation_msg(self): if self.prefs.FEATURE_demo: return 'WARNING: in the",
"== 'ESC': raise OpCancelledException() elif event.type == 'TIMER': self.handle_communication() def modal(self, context, event):",
"> 0: self.set_status('WARNING', 'Number of invalid faces found: ' + str(invalid_face_count)) else: self.set_status('INFO',",
"if not self.op_done else {'PASS_THROUGH'} def pre_op_initialize(self): pass def execute(self, context): cancel =",
"texture. For for info regarding non-square packing read the documentation\" def get_scale_factors(self): ratio",
"Public License # as published by the Free Software Foundation; either version 2",
"warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #",
"self.curr_phase == UvPackingPhaseCode.SIMILAR_SELECTION: return 'Searching for similar islands (press ESC to cancel)' if",
"' + str(area)) def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.MEASURE_AREA)] return",
"each other. For more info regarding similarity detection click the help button\" def",
"not self.prefs.heuristic_enabled(self.scene_props): return UvpLabels.GROUPS_TOGETHER_CONFIRM_MSG return '' def send_unselected_islands(self): return self.prefs.pack_to_others_enabled(self.scene_props) def grouping_enabled(self): return",
"as ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, str(ex)) except Exception as ex: if in_debug_mode():",
"['-B', self.get_target_box_string(self.target_box)] uvp_args.append('-b') return uvp_args class UVP2_OT_OverlapCheckOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_overlap_check' bl_label = 'Overlap",
"== UvPackerErrorCode.MAX_GROUP_COUNT_EXCEEDED: raise RuntimeError(\"Maximal group count exceeded\") if retcode == UvPackerErrorCode.DEVICE_NOT_SUPPORTED: raise RuntimeError(\"Selected",
"= 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) else: if len(invalid_faces) > 0: self.raiseUnexpectedOutputError() if invalid_face_count",
"in this engine edition') # Validate pack mode pack_mode = UvPackingMode.get_mode(self.scene_props.pack_mode) if pack_mode.req_feature",
"class UVP2_OT_ProcessSimilar(UVP2_OT_PackOperatorGeneric): def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(self.get_uvp_opcode()), '-I', str(self.scene_props.similarity_threshold)]",
"= \"Show help for UVP setup\" URL_SUFFIX = \"uvp-setup\" class UVP2_OT_HeuristicSearchHelp(UVP2_OT_Help): bl_label =",
"False def read_area(self, area_msg): return round(force_read_float(area_msg) / self.pack_ratio, 3) class UVP2_OT_PackOperator(UVP2_OT_PackOperatorGeneric): bl_idname =",
"= 'Measure area of selected UV islands' def process_result(self): if self.area_msg is None:",
"packing (check the selected islands). Consider increasing the 'Precision' parameter. Sometimes increasing the",
"self.scene_props.lock_overlapping_mode] if self.prefs.pack_to_others_enabled(self.scene_props): uvp_args += ['-x'] if self.prefs.FEATURE_validation and self.scene_props.pre_validate: uvp_args.append('-v') if self.prefs.normalize_islands_enabled(self.scene_props):",
"failed. Number of invalid faces found: ' + str(invalid_face_count) + '. Packing aborted')",
"str(ex)) cancel = True except Exception as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', 'Unexpected",
"== UvPackMessageCode.PACK_SOLUTION: if self.pack_solution_msg is not None: self.raiseUnexpectedOutputError() self.pack_solution_msg = msg elif msg_code",
"print('Pakcer args: ' + ' '.join(x for x in uvp_args_final)) creation_flags = os_uvp_creation_flags()",
"return if self.invalid_islands_msg is None: self.raiseUnexpectedOutputError() code = force_read_int(self.invalid_islands_msg) subcode = force_read_int(self.invalid_islands_msg) invalid_islands",
"if self.curr_phase is None: return False progress_msg_spec = self.get_progress_msg_spec() if progress_msg_spec: return progress_msg_spec",
"event processing code if event.type == 'ESC': raise OpCancelledException() elif event.type == 'TIMER':",
"selected islands so they are suitable for packing into the active texture. CAUTION:",
"for setting margin in pixels\" URL_SUFFIX = \"pixel-margin\" class UVP2_OT_IslandRotStepHelp(UVP2_OT_Help): bl_label = 'Island",
"ESC to cancel) ' return header_str + iter_str + time_left_str + progress_str +",
"False self.hang_timeout = 10.0 # Start progress monitor thread self.progress_queue = queue.Queue() self.connection_thread",
"in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, str(ex)) except Exception as ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, 'Unexpected",
"class UVP2_OT_PackOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_pack' bl_label = 'Pack' bl_description = 'Pack selected UV",
"- self.progress_last_update_time > msg_refresh_interval or new_progress_msg != self.progress_msg: self.progress_last_update_time = now self.progress_msg =",
"if self.prefs.FEATURE_demo: return 'WARNING: in the demo mode only the number of similar",
"context, event): cancel = False finish = False try: try: self.handle_event(event) # Check",
"self.op_status_type = None self.op_status = None self.op_warnings = [] try: if not check_uvp():",
"= force_read_int(islands_msg) for i in range(island_cnt): islands.append(read_int_array(islands_msg)) self.p_context.set_islands(selected_cnt, islands) def process_invalid_islands(self): if self.uvp_proc.returncode",
"area of selected UV islands' def process_result(self): if self.area_msg is None: self.raiseUnexpectedOutputError() area",
"packed islands area: ' + str(self.area) self.set_status('INFO', op_status) if overlap_detected: self.add_warning(\"Overlapping islands were",
"Consider increasing the 'Precision' parameter. Sometimes increasing the 'Adjustment Time' may solve the",
"> len(self.progress_array): self.progress_array = [0] * (progress_size) for i in range(progress_size): self.progress_array[i] =",
"+= ['-h', str(self.scene_props.heuristic_search_time), '-j', str(self.scene_props.heuristic_max_wait_time)] if self.prefs.FEATURE_advanced_heuristic and self.scene_props.advanced_heuristic: uvp_args.append('-H') uvp_args += ['-g',",
"= self.start_time self.hang_detected = False self.hang_timeout = 10.0 # Start progress monitor thread",
"= [get_uvp_execpath(), '-E', '-e', str(UvTopoAnalysisLevel.FORCE_EXTENDED), '-t', str(self.prefs.thread_count)] + self.get_uvp_args() if send_unselected: uvp_args_final.append('-s') if",
"self.uvp_proc.returncode == UvPackerErrorCode.NO_SPACE: op_status = 'Packing stopped - no space to pack all",
"along with this program; if not, write to the Free Software Foundation, #",
"\"invalid-topology-issues\" class UVP2_OT_PixelMarginHelp(UVP2_OT_Help): bl_label = 'Pixel Margin Help' bl_idname = 'uvpackmaster2.uv_pixel_margin_help' bl_description =",
"are similar are placed on top of each other. For more info regarding",
"self.handle_uvp_msg(item) else: raise RuntimeError('Unexpected output from the connection thread') msg_received += 1 curr_time",
"For more info regarding similarity detection click the help button\" def get_uvp_opcode(self): return",
"progress_str = 'Pack progress: {} '.format(percent_progress_str) if self.area is not None: end_str =",
"None if active_dev is None: raise RuntimeError('Could not find a packing device') if",
"not check_uvp(): unregister_uvp() redraw_ui(context) raise RuntimeError(\"UVP engine broken\") reset_stats(self.prefs) self.p_context = PackContext(context) self.pre_op_initialize()",
"' + str(invalid_face_count)) else: self.set_status('INFO', 'No invalid faces found') def validate_pack_params(self): pass def",
"break if isinstance(item, str): raise RuntimeError(item) elif isinstance(item, io.BytesIO): self.handle_uvp_msg(item) else: raise RuntimeError('Unexpected",
"version 2 # of the License, or (at your option) any later version.",
"error') cancel = True if self.p_context is not None: self.p_context.update_meshes() if cancel: if",
"validation: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.VALIDATION: return \"Per-face overlap",
"if self.invalid_faces_msg is None: self.raiseUnexpectedOutputError() invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces = read_int_array(self.invalid_faces_msg) if not",
"together\") raise RuntimeError('Pack process returned an error') def raiseUnexpectedOutputError(self): raise RuntimeError('Unexpected output from",
"shape to islands which are already selected. For more info regarding similarity detection",
"cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.VALIDATION: return \"Per-face overlap check: {:3}% (press ESC to",
"def exit_common(self): if self.interactive: wm = self.p_context.context.window_manager wm.event_timer_remove(self._timer) self.p_context.update_meshes() self.report_status() if in_debug_mode(): print('UVP",
"'ESC': raise OpAbortedException() if self.handle_event_spec(event): return # Generic event processing code if event.type",
"= retcode if retcode in {UvPackerErrorCode.SUCCESS, UvPackerErrorCode.INVALID_ISLANDS, UvPackerErrorCode.NO_SPACE, UvPackerErrorCode.PRE_VALIDATION_FAILED}: return if retcode ==",
"except queue.Empty as ex: break if isinstance(item, str): raise RuntimeError(item) elif isinstance(item, io.BytesIO):",
"from .os_iface import * from .island_params import * from .labels import UvpLabels from",
"set to a small value and the 'Adjustment Time' is not long enough.\")",
"Islands To Texture' operator so islands are again suitable for packing into a",
"# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # #",
"required to but check once again to be on the safe side self.handle_communication()",
"round(target_box[0].x, prec), round(target_box[0].y, prec), round(target_box[1].x, prec), round(target_box[1].y, prec)) def get_uvp_args(self): uvp_args = ['-o',",
"def finish_after_op_done(self): return True def handle_op_done(self): self.op_done = True send_finish_confirmation(self.uvp_proc) try: self.uvp_proc.wait(5) except:",
"return self.prefs.FEATURE_lock_overlapping and self.scene_props.lock_groups_enable def send_verts_3d(self): return self.scene_props.normalize_islands def get_progress_msg_spec(self): if self.curr_phase in",
"uvp_args.append('-b') return uvp_args class UVP2_OT_OverlapCheckOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_overlap_check' bl_label = 'Overlap Check' bl_description",
"are suitable for packing into the active texture. CAUTION: this operator should be",
"return '' def send_unselected_islands(self): return True def get_uvp_opcode(self): return UvPackerOpcode.SELECT_SIMILAR def process_result(self): if",
"= True except RuntimeError as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', str(ex)) cancel =",
"None else 'INFO' op_status = self.op_status if len(self.op_warnings) > 0: if op_status_type ==",
"processing code if event.type == 'ESC': raise OpCancelledException() elif event.type == 'TIMER': self.handle_communication()",
"self.target_box = self.prefs.target_box(self.scene_props) if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) if self.pack_ratio != 1.0: uvp_args",
"context.active_object.mode == 'EDIT' def execute(self, context): try: self.p_context = PackContext(context) ratio = get_active_image_ratio(self.p_context.context)",
"pack_solution) self.set_status('INFO', 'Islands aligned') class UVP2_OT_ScaleIslands(bpy.types.Operator): bl_options = {'UNDO'} @classmethod def poll(cls, context):",
"(1.0, 1.0) class UVP2_OT_AdjustIslandsToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_adjust_islands_to_texture' bl_label = 'Adjust Islands To Texture'",
"= PackContext(context) self.pre_op_initialize() send_unselected = self.send_unselected_islands() send_rot_step = self.send_rot_step() send_groups = self.grouping_enabled() and",
"self.set_status('ERROR', 'Unexpected error') cancel = True if self.p_context is not None: self.p_context.update_meshes() if",
"threading import signal import webbrowser from .utils import * from .pack_context import *",
"print('UVP operation time: ' + str(time.time() - self.start_time)) def read_islands(self, islands_msg): islands =",
"class UVP2_OT_AdjustIslandsToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_adjust_islands_to_texture' bl_label = 'Adjust Islands To Texture' bl_description =",
"if self.prefs.pixel_padding_enabled(self.scene_props): uvp_args += ['-N', str(self.scene_props.pixel_padding)] uvp_args += ['-W', self.scene_props.pixel_margin_method] uvp_args += ['-Y',",
"set_status(self, status_type, status): self.op_status_type = status_type self.op_status = status def add_warning(self, warn_msg): self.op_warnings.append(warn_msg)",
".os_iface import * from .island_params import * from .labels import UvpLabels from .register",
"UvPackerErrorCode.MAX_GROUP_COUNT_EXCEEDED: raise RuntimeError(\"Maximal group count exceeded\") if retcode == UvPackerErrorCode.DEVICE_NOT_SUPPORTED: raise RuntimeError(\"Selected device",
"False while True: event = FakeTimerEvent() ret = self.modal(context, event) if ret.intersection({'FINISHED', 'CANCELLED'}):",
"now self.progress_msg = new_progress_msg self.report({'INFO'}, self.progress_msg) def handle_uvp_msg(self, msg): msg_code = force_read_int(msg) if",
"in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', str(ex)) cancel = True except Exception as ex: if in_debug_mode():",
"> 0: # Switch to the face selection mode if self.p_context.context.tool_settings.use_uv_select_sync: self.p_context.context.tool_settings.mesh_select_mode =",
"not active_dev.supported: raise RuntimeError('Selected packing device is not supported in this engine edition')",
"self.prefs['op_warnings'] = self.op_warnings # self.prefs.stats_op_warnings.add(warning_msg) def exit_common(self): if self.interactive: wm = self.p_context.context.window_manager wm.event_timer_remove(self._timer)",
"for more details. # # You should have received a copy of the",
"= 'uvpackmaster2.uv_pack' bl_label = 'Pack' bl_description = 'Pack selected UV islands' def __init__(self):",
"['-V', str(tile_count)] if self.prefs.tiles_enabled(self.scene_props): uvp_args += ['-C', str(tiles_in_row)] if self.grouping_enabled(): if to_uvp_group_method(self.get_group_method()) ==",
"None: self.p_context.update_meshes() if cancel: if self.uvp_proc is not None: self.uvp_proc.terminate() self.report_status() return {'FINISHED'}",
"square texture. For for info regarding non-square packing read the documentation\" def get_scale_factors(self):",
"this operator should be used only when packing to a non-square texture. For",
"= {'UNDO'} MODAL_INTERVAL_S = 0.1 interactive = False @classmethod def poll(cls, context): prefs",
"return UvpLabels.CUDA_MACOS_CONFIRM_MSG if self.prefs.pack_groups_together(self.scene_props) and not self.prefs.heuristic_enabled(self.scene_props): return UvpLabels.GROUPS_TOGETHER_CONFIRM_MSG return '' def send_unselected_islands(self):",
"event) if ret.intersection({'FINISHED', 'CANCELLED'}): return ret time.sleep(self.MODAL_INTERVAL_S) def invoke(self, context, event): self.interactive =",
"class UVP2_OT_AlignSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_align_similar' bl_label = 'Align Similar' bl_description = \"Align selected",
"UvPackerErrorCode.NO_SPACE, UvPackerErrorCode.PRE_VALIDATION_FAILED}: return if retcode == UvPackerErrorCode.CANCELLED: raise OpCancelledException() if retcode == UvPackerErrorCode.NO_VALID_STATIC_ISLAND:",
"None: uvp_args += ['-B', self.get_target_box_string(self.target_box)] uvp_args.append('-b') return uvp_args class UVP2_OT_OverlapCheckOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_overlap_check'",
"Detection Help' bl_idname = 'uvpackmaster2.uv_similarity_detection_help' bl_description = \"Show help for similarity detection\" URL_SUFFIX",
"It should not be required to but check once again to be on",
"uvp_args.append('-L') if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: self.target_box = self.prefs.target_box(self.scene_props) if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context)",
"else: self.target_box = (Vector((0.0, 0.0)), Vector((self.pack_ratio, 1.0))) if self.target_box is not None: uvp_args",
"self.curr_phase == UvPackingPhaseCode.TOPOLOGY_VALIDATION: return \"Topology validation: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase",
"'TIMER': self.handle_communication() def modal(self, context, event): cancel = False finish = False try:",
"found is reported, islands will not be selected. Click OK to continue' return",
"space to pack all islands' self.add_warning(\"Overlap check was performed only on the islands",
"faces, faces overlapping each other' def get_confirmation_msg(self): if self.prefs.FEATURE_demo: return 'WARNING: in the",
"True except Exception as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', 'Unexpected error') cancel =",
"# Generic event processing code if event.type == 'ESC': raise OpCancelledException() elif event.type",
"outside_detected = self.p_context.handle_island_flags(island_flags) if self.area is not None: self.prefs.stats_area = self.area if self.uvp_proc.returncode",
"of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU",
"found in the packing box\") if retcode == UvPackerErrorCode.MAX_GROUP_COUNT_EXCEEDED: raise RuntimeError(\"Maximal group count",
"= True except Exception as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', 'Unexpected error') cancel",
"['-O'] uvp_args += ['-F', self.scene_props.fixed_scale_strategy] if self.prefs.FEATURE_island_rotation: if self.scene_props.rot_enable: rot_step_value = self.scene_props.rot_step if",
"args=(self.uvp_proc.stdout, self.progress_queue)) self.connection_thread.daemon = True self.connection_thread.start() self.progress_array = [0] self.progress_msg = '' self.progress_sec_left",
"Grouping Help' bl_idname = 'uvpackmaster2.uv_manual_grouping_help' bl_description = \"Show help for manual grouping\" URL_SUFFIX",
"def handle_uvp_msg_spec(self, msg_code, msg): return False def handle_event_spec(self, event): return False def handle_progress_msg(self):",
"uvp_args.append('-H') uvp_args += ['-g', self.scene_props.pack_mode] tile_count, tiles_in_row = self.prefs.tile_grid_config(self.scene_props, self.p_context.context) if self.prefs.pack_to_tiles(self.scene_props): uvp_args",
"active_dev is None: raise RuntimeError('Could not find a packing device') if not active_dev.supported:",
"but check once again to be on the safe side self.handle_communication() if not",
"similarity detection click the help button\" def get_confirmation_msg(self): if self.prefs.FEATURE_demo: return 'WARNING: in",
"False def handle_event_spec(self, event): return False def handle_progress_msg(self): if self.op_done: return msg_refresh_interval =",
"False self.op_done = False self.uvp_proc = None self.prefs = get_prefs() self.scene_props = context.scene.uvp2_props",
"= force_read_int(islands_msg) selected_cnt = force_read_int(islands_msg) for i in range(island_cnt): islands.append(read_int_array(islands_msg)) self.p_context.set_islands(selected_cnt, islands) def",
"uvp_args += ['-r', str(90)] if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) uvp_args += ['-q', str(self.pack_ratio)]",
"== UvGroupingMethodUvp.SIMILARITY: uvp_args += ['-I', str(self.scene_props.similarity_threshold)] if self.prefs.pack_groups_together(self.scene_props): uvp_args += ['-U', str(self.scene_props.group_compactness)] if",
"= self.scene_props.rot_step if self.scene_props.prerot_disable: uvp_args += ['-w'] else: rot_step_value = -1 uvp_args +=",
"not None: op_status += ', packed islands area: ' + str(self.area) self.set_status('INFO', op_status)",
"str(to_uvp_group_method(self.get_group_method()))] if self.send_rot_step(): uvp_args_final += ['-R'] if self.lock_groups_enabled(): uvp_args_final += ['-Q'] if in_debug_mode():",
"which have similar shape to islands which are already selected. For more info",
"raise RuntimeError('Selected packing device is not supported in this engine edition') # Validate",
"self.handle_communication() def modal(self, context, event): cancel = False finish = False try: try:",
"'WARNING' op_status += '. (WARNINGS were reported - check the UVP tab for",
"self.prefs.FEATURE_island_rotation_step and self.scene_props.rot_enable and self.scene_props.island_rot_step_enable def lock_groups_enabled(self): return self.prefs.FEATURE_lock_overlapping and self.scene_props.lock_groups_enable def send_verts_3d(self):",
"small value and the 'Adjustment Time' is not long enough.\") def validate_pack_params(self): active_dev",
"Help' bl_idname = 'uvpackmaster2.uv_udim_support_help' bl_description = \"Show help for UDIM support\" URL_SUFFIX =",
"<gh_stars>1-10 # ##### BEGIN GPL LICENSE BLOCK ##### # # This program is",
"= ['-o', str(UvPackerOpcode.MEASURE_AREA)] return uvp_args class UVP2_OT_ValidateOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_validate' bl_label = 'Validate",
"io.BytesIO): self.handle_uvp_msg(item) else: raise RuntimeError('Unexpected output from the connection thread') msg_received += 1",
"def get_group_method(self): return self.scene_props.group_method def send_rot_step(self): return self.prefs.FEATURE_island_rotation_step and self.scene_props.rot_enable and self.scene_props.island_rot_step_enable def",
"if msg_code == UvPackMessageCode.PROGRESS_REPORT: self.curr_phase = force_read_int(msg) progress_size = force_read_int(msg) if progress_size >",
"NoUvFaceError as ex: self.set_status('WARNING', str(ex)) cancel = True except RuntimeError as ex: if",
"def require_selection(self): return True def finish_after_op_done(self): return True def handle_op_done(self): self.op_done = True",
"RuntimeError(\"'Pack To Others' is not supported with grouping by similarity\") if not self.scene_props.rot_enable:",
"is not None and context.active_object.mode == 'EDIT' def execute(self, context): try: self.p_context =",
"self.connection_thread.join() self.check_uvp_retcode(self.uvp_proc.returncode) if not self.p_context.islands_received(): self.raiseUnexpectedOutputError() self.process_invalid_islands() self.process_result() if self.finish_after_op_done(): raise OpFinishedException() def",
"process_result(self): if self.invalid_faces_msg is None: self.raiseUnexpectedOutputError() invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces = read_int_array(self.invalid_faces_msg) if",
"len(self.prefs.dev_array) else None if active_dev is None: raise RuntimeError('Could not find a packing",
"'WARNING: in the demo mode only the number of invalid faces found is",
"warn_msg): self.op_warnings.append(warn_msg) def report_status(self): if self.op_status is not None: self.prefs['op_status'] = self.op_status op_status_type",
"Kill the UVP process unconditionally if a hang was detected if self.hang_detected and",
"left: {} sec. \".format(self.progress_sec_left) else: time_left_str = '' percent_progress_str = '' for prog",
"'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) else: if len(invalid_faces) > 0: self.raiseUnexpectedOutputError() if invalid_face_count >",
"self.validate_pack_params() if self.prefs.write_to_file: out_filepath = os.path.join(tempfile.gettempdir(), 'uv_islands.data') out_file = open(out_filepath, 'wb') out_file.write(self.p_context.serialized_maps) out_file.close()",
"UvpLabels from .register import check_uvp, unregister_uvp import bmesh import bpy import mathutils import",
"'uvpackmaster2.uv_island_rot_step_help' bl_description = \"Show help for setting rotation step on per-island level\" URL_SUFFIX",
"= force_read_int(msg) stats.avg_time = force_read_int(msg) return True return False def handle_event_spec(self, event): if",
"documentation\" def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return (ratio, 1.0) class UVP2_OT_Help(bpy.types.Operator): bl_label =",
"not supported in this engine edition') # Validate pack mode pack_mode = UvPackingMode.get_mode(self.scene_props.pack_mode)",
"return \"Per-face overlap check: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) raise RuntimeError('Unexpected packing phase",
"self.cancel_sig_sent = True return True return False def process_result(self): overlap_detected = False outside_detected",
"if msg_code == UvPackMessageCode.AREA: self.area = self.read_area(msg) return True elif msg_code == UvPackMessageCode.PACK_SOLUTION:",
"UvPackerErrorCode.CANCELLED: raise OpCancelledException() if retcode == UvPackerErrorCode.NO_VALID_STATIC_ISLAND: raise RuntimeError(\"'Pack To Others' option enabled,",
"in progress (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.AREA_MEASUREMENT: return 'Area measurement",
"in uvp_args_final)) creation_flags = os_uvp_creation_flags() popen_args = dict() if creation_flags is not None:",
"Disable' option must be off in order to group by similarity\") if self.prefs.FEATURE_target_box",
"\"non-square-packing\" class UVP2_OT_SimilarityDetectionHelp(UVP2_OT_Help): bl_label = 'Similarity Detection Help' bl_idname = 'uvpackmaster2.uv_similarity_detection_help' bl_description =",
"['-x'] if self.prefs.FEATURE_validation and self.scene_props.pre_validate: uvp_args.append('-v') if self.prefs.normalize_islands_enabled(self.scene_props): uvp_args.append('-L') if self.prefs.FEATURE_target_box and self.prefs.target_box_enable:",
"= read_int_array(self.similar_islands_msg) if not self.prefs.FEATURE_demo: if len(similar_islands) != similar_island_count: self.raiseUnexpectedOutputError() for island_idx in",
"UvPackingPhaseCode.RENDER_PRESENTATION and curr_time - self.last_msg_time > self.hang_timeout: self.hang_detected = True def handle_event(self, event):",
"to continue' return '' def process_result(self): if self.invalid_faces_msg is None: self.raiseUnexpectedOutputError() invalid_face_count =",
"= [0] self.progress_msg = '' self.progress_sec_left = -1 self.progress_iter_done = -1 self.progress_last_update_time =",
"ret.intersection({'FINISHED', 'CANCELLED'}): return ret time.sleep(self.MODAL_INTERVAL_S) def invoke(self, context, event): self.interactive = True self.prefs",
"Time' is not long enough.\") def validate_pack_params(self): active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx <",
"margin adjustment. ' elif self.prefs.heuristic_enabled(self.scene_props): header_str = 'Current area: {}. '.format(self.area if self.area",
"elif msg_code == UvPackMessageCode.BENCHMARK: stats = self.prefs.stats_array.add() dev_name_len = force_read_int(msg) stats.dev_name = msg.read(dev_name_len).decode('ascii')",
"from .utils import * from .pack_context import * from .connection import * from",
"if finish: return self.finish(context) except OpAbortedException: self.set_status('INFO', 'Packer process killed') cancel = True",
"{'UNDO'} @classmethod def poll(cls, context): return context.active_object is not None and context.active_object.mode ==",
"False def process_result(self): overlap_detected = False outside_detected = False if self.invalid_faces_msg is not",
"self.p_context.select_faces(list(invalid_faces), True) if invalid_face_count > 0: self.set_status('WARNING', 'Pre-validation failed. Number of invalid faces",
"import * from .connection import * from .prefs import * from .os_iface import",
"not be selected. Click OK to continue' return '' def process_result(self): if self.invalid_faces_msg",
"self.prefs.FEATURE_demo: return 'WARNING: in the demo mode only the number of similar islands",
"self.set_status('INFO', 'No invalid faces found') def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o',",
"if progress_msg_spec: return progress_msg_spec if self.curr_phase == UvPackingPhaseCode.INITIALIZATION: return 'Initialization (press ESC to",
"force_read_int(self.invalid_faces_msg) invalid_faces = read_int_array(self.invalid_faces_msg) if not self.prefs.FEATURE_demo: if len(invalid_faces) != invalid_face_count: self.raiseUnexpectedOutputError() if",
"4 return \"{}:{}:{}:{}\".format( round(target_box[0].x, prec), round(target_box[0].y, prec), round(target_box[1].x, prec), round(target_box[1].y, prec)) def get_uvp_args(self):",
"similar are placed on top of each other. For more info regarding similarity",
"killed') cancel = True except OpCancelledException: self.set_status('INFO', 'Operation cancelled by the user') cancel",
"if self.op_status is not None: self.prefs['op_status'] = self.op_status op_status_type = self.op_status_type if self.op_status_type",
"else: self.set_status('INFO', 'No invalid faces found') def validate_pack_params(self): pass def get_uvp_args(self): uvp_args =",
"invalid faces found: ' + str(invalid_face_count) + '. Packing aborted') return if not",
"enabled in order to group by similarity\") if self.scene_props.prerot_disable: raise RuntimeError(\"'Pre-Rotation Disable' option",
"+ unselected_cnt == 0: raise NoUvFaceError('No UV face visible') self.validate_pack_params() if self.prefs.write_to_file: out_filepath",
"try: self.p_context = PackContext(context) ratio = get_active_image_ratio(self.p_context.context) self.p_context.scale_selected_faces(self.get_scale_factors()) except RuntimeError as ex: if",
"'Packing done' if self.area is not None: op_status += ', packed islands area:",
"analysis: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.OVERLAP_CHECK: return 'Overlap check",
"This program is distributed in the hope that it will be useful, #",
"not self.scene_props.rot_enable: raise RuntimeError(\"Island rotations must be enabled in order to group by",
"Others' option enabled, but no unselected island found in the packing box\") if",
"help icon\" def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return (1.0 / ratio, 1.0) class",
"'Initialization (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_ANALYSIS: return \"Topology analysis: {:3}%",
"True elif msg_code == UvPackMessageCode.BENCHMARK: stats = self.prefs.stats_array.add() dev_name_len = force_read_int(msg) stats.dev_name =",
"' else: end_str = '(press ESC to cancel) ' return header_str + iter_str",
"received a copy of the GNU General Public License # along with this",
"operation).\") if outside_detected: self.add_warning(\"Some islands are outside their packing box after packing (check",
"raise RuntimeError(\"'Pack To Others' option enabled, but no unselected island found in the",
"wait timeout reached') self.connection_thread.join() self.check_uvp_retcode(self.uvp_proc.returncode) if not self.p_context.islands_received(): self.raiseUnexpectedOutputError() self.process_invalid_islands() self.process_result() if self.finish_after_op_done():",
"def process_result(self): if self.area_msg is None: self.raiseUnexpectedOutputError() area = self.read_area(self.area_msg) self.prefs.stats_area = area",
"= 'Pixel margin adjustment. ' elif self.prefs.heuristic_enabled(self.scene_props): header_str = 'Current area: {}. '.format(self.area",
"handle_uvp_msg_spec(self, msg_code, msg): if msg_code == UvPackMessageCode.AREA: self.area = self.read_area(msg) return True elif",
"import threading import signal import webbrowser from .utils import * from .pack_context import",
"as ex: break if isinstance(item, str): raise RuntimeError(item) elif isinstance(item, io.BytesIO): self.handle_uvp_msg(item) else:",
"performed by the 'Adjust Islands To Texture' operator so islands are again suitable",
"def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.PACK), '-i', str(self.scene_props.precision), '-m', str(self.scene_props.margin)] uvp_args += ['-d',",
"send_lock_groups, send_verts_3d, self.get_group_method() if send_groups else None) if self.require_selection(): if selected_cnt == 0:",
"execute(self, context): cancel = False self.op_done = False self.uvp_proc = None self.prefs =",
"import webbrowser from .utils import * from .pack_context import * from .connection import",
"self.execute(context) def draw(self, context): layout = self.layout col = layout.column() col.label(text=self.confirmation_msg) def get_confirmation_msg(self):",
"__init__(self): self.type = 'TIMER' self.value = 'NOTHING' self.ctrl = False while True: event",
"{'FINISHED'} def get_progress_msg_spec(self): return False def get_progress_msg(self): if self.hang_detected: return 'Packer process not",
"+= ', packed islands area: ' + str(self.area) self.set_status('INFO', op_status) if overlap_detected: self.add_warning(\"Overlapping",
"the 'Adjustment Time' may solve the problem (if used in the operation).\") if",
"= \"udim-support\" class UVP2_OT_ManualGroupingHelp(UVP2_OT_Help): bl_label = 'Manual Grouping Help' bl_idname = 'uvpackmaster2.uv_manual_grouping_help' bl_description",
"UV islands' def __init__(self): self.cancel_sig_sent = False self.area = None def get_confirmation_msg(self): if",
"for similar islands (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_ALIGNING: return 'Similar",
"self.scene_props.prerot_disable: uvp_args += ['-w'] else: rot_step_value = -1 uvp_args += ['-r', str(rot_step_value)] if",
"but no unselected island found in the packing box\") if retcode == UvPackerErrorCode.MAX_GROUP_COUNT_EXCEEDED:",
"force_read_int(msg) self.progress_sec_left = force_read_int(msg) self.progress_iter_done = force_read_int(msg) # Inform the upper layer wheter",
"if isinstance(item, str): raise RuntimeError(item) elif isinstance(item, io.BytesIO): self.handle_uvp_msg(item) else: raise RuntimeError('Unexpected output",
"as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', 'Unexpected error') cancel = True if self.p_context",
"class UVP2_OT_IslandRotStepHelp(UVP2_OT_Help): bl_label = 'Island Rotation Step Help' bl_idname = 'uvpackmaster2.uv_island_rot_step_help' bl_description =",
"def read_area(self, area_msg): return round(force_read_float(area_msg) / self.pack_ratio, 3) class UVP2_OT_PackOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_pack'",
"get_scale_factors(self): return (1.0, 1.0) class UVP2_OT_AdjustIslandsToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_adjust_islands_to_texture' bl_label = 'Adjust Islands",
"== UvPackMessageCode.INVALID_FACES: if self.invalid_faces_msg is not None: self.raiseUnexpectedOutputError() self.invalid_faces_msg = msg elif msg_code",
"validate_pack_params(self): active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None if active_dev is",
"which are similar are placed on top of each other. For more info",
"if self.target_box is not None: self.target_box[0].x *= self.pack_ratio self.target_box[1].x *= self.pack_ratio else: self.target_box",
"UVP2_OT_SelectSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_select_similar' bl_label = 'Select Similar' bl_description = \"Selects all islands",
"is distributed in the hope that it will be useful, # but WITHOUT",
"' ') + '%, ' percent_progress_str = percent_progress_str[:-2] progress_str = 'Pack progress: {}",
"self.p_context = PackContext(context) self.pre_op_initialize() send_unselected = self.send_unselected_islands() send_rot_step = self.send_rot_step() send_groups = self.grouping_enabled()",
"packing (check the selected islands). This usually happens when 'Pixel Padding' is set",
"self.read_area(self.area_msg) self.prefs.stats_area = area self.set_status('INFO', 'Islands area: ' + str(area)) def validate_pack_params(self): pass",
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public",
"read the documentation\" def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return (ratio, 1.0) class UVP2_OT_Help(bpy.types.Operator):",
"def send_rot_step(self): return self.prefs.FEATURE_island_rotation_step and self.scene_props.rot_enable and self.scene_props.island_rot_step_enable def lock_groups_enabled(self): return self.prefs.FEATURE_lock_overlapping and",
"check_uvp(): unregister_uvp() redraw_ui(context) raise RuntimeError(\"UVP engine broken\") reset_stats(self.prefs) self.p_context = PackContext(context) self.pre_op_initialize() send_unselected",
"in the hope that it will be useful, # but WITHOUT ANY WARRANTY;",
"raise RuntimeError('Unexpected packing phase encountered') def handle_uvp_msg_spec(self, msg_code, msg): return False def handle_event_spec(self,",
"str(err)) cancel = True except RuntimeError as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', str(ex))",
"detection click the help button\" def get_uvp_opcode(self): return UvPackerOpcode.ALIGN_SIMILAR def process_result(self): if self.prefs.FEATURE_demo:",
"< len(self.prefs.dev_array) else None if active_dev is None: raise RuntimeError('Could not find a",
"FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for",
"import mathutils import tempfile class InvalidIslandsError(Exception): pass class NoUvFaceError(Exception): pass class UVP2_OT_PackOperatorGeneric(bpy.types.Operator): bl_options",
"0: # Switch to the face selection mode if self.p_context.context.tool_settings.use_uv_select_sync: self.p_context.context.tool_settings.mesh_select_mode = (False,",
"overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags) if overlap_detected: self.set_status('WARNING', 'Overlapping islands detected') else: self.set_status('INFO', 'No",
"help for setting rotation step on per-island level\" URL_SUFFIX = \"island-rotation-step\" class UVP2_OT_UdimSupportHelp(UVP2_OT_Help):",
"return False def get_progress_msg(self): if self.hang_detected: return 'Packer process not responding for a",
"for setting rotation step on per-island level\" URL_SUFFIX = \"island-rotation-step\" class UVP2_OT_UdimSupportHelp(UVP2_OT_Help): bl_label",
"topology encountered in the selected islands. Check the Help panel to learn more\"",
"def execute(self, context): try: self.p_context = PackContext(context) ratio = get_active_image_ratio(self.p_context.context) self.p_context.scale_selected_faces(self.get_scale_factors()) except RuntimeError",
"# Inform the upper layer wheter it should finish if self.curr_phase == UvPackingPhaseCode.DONE:",
"raise OpCancelledException() elif event.type == 'TIMER': self.handle_communication() def modal(self, context, event): cancel =",
"engine broken\") reset_stats(self.prefs) self.p_context = PackContext(context) self.pre_op_initialize() send_unselected = self.send_unselected_islands() send_rot_step = self.send_rot_step()",
"+= ['-y', str(self.prefs.pixel_margin_tex_size(self.scene_props, self.p_context.context))] if self.prefs.pixel_padding_enabled(self.scene_props): uvp_args += ['-N', str(self.scene_props.pixel_padding)] uvp_args += ['-W',",
"they are suitable for packing into the active texture. CAUTION: this operator should",
"the GNU General Public License # along with this program; if not, write",
"self.report({op_status_type}, op_status) self.prefs['op_warnings'] = self.op_warnings # self.prefs.stats_op_warnings.add(warning_msg) def exit_common(self): if self.interactive: wm =",
"range(island_cnt): islands.append(read_int_array(islands_msg)) self.p_context.set_islands(selected_cnt, islands) def process_invalid_islands(self): if self.uvp_proc.returncode != UvPackerErrorCode.INVALID_ISLANDS: return if self.invalid_islands_msg",
"if self.op_status_type is not None else 'INFO' op_status = self.op_status if len(self.op_warnings) >",
"uvp_args += ['-x'] if self.prefs.FEATURE_validation and self.scene_props.pre_validate: uvp_args.append('-v') if self.prefs.normalize_islands_enabled(self.scene_props): uvp_args.append('-L') if self.prefs.FEATURE_target_box",
"found') def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.VALIDATE_UVS)] return uvp_args class",
"self.raiseUnexpectedOutputError() code = force_read_int(self.invalid_islands_msg) subcode = force_read_int(self.invalid_islands_msg) invalid_islands = read_int_array(self.invalid_islands_msg) if len(invalid_islands) ==",
"UVP2_OT_MeasureAreaOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_measure_area' bl_label = 'Measure Area' bl_description = 'Measure area of",
"None else 'none') else: header_str = '' if self.progress_iter_done >= 0: iter_str =",
"= 'uvpackmaster2.uv_align_similar' bl_label = 'Align Similar' bl_description = \"Align selected islands, so islands",
"responding for a longer time (press ESC to abort)' if self.curr_phase is None:",
"= 'uvpackmaster2.uv_invalid_topology_help' bl_description = \"Show help for handling invalid topology errors\" URL_SUFFIX =",
"not None: self.raiseUnexpectedOutputError() self.area_msg = msg elif msg_code == UvPackMessageCode.INVALID_FACES: if self.invalid_faces_msg is",
"False def handle_event_spec(self, event): if event.type == 'ESC': if not self.cancel_sig_sent: self.uvp_proc.send_signal(os_cancel_sig()) self.cancel_sig_sent",
"self.islands_metadata_msg = msg else: self.raiseUnexpectedOutputError() def handle_communication(self): if self.op_done: return msg_received = 0",
"self.last_msg_time = curr_time self.hang_detected = False else: if self.curr_phase != UvPackingPhaseCode.RENDER_PRESENTATION and curr_time",
"is not None: self.raiseUnexpectedOutputError() self.area_msg = msg elif msg_code == UvPackMessageCode.INVALID_FACES: if self.invalid_faces_msg",
"= 0.0 self.curr_phase = UvPackingPhaseCode.INITIALIZATION self.invalid_islands_msg = None self.island_flags_msg = None self.pack_solution_msg =",
"cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_ALIGNING: return 'Similar islands aligning (press ESC to cancel)'",
"adjustment. ' elif self.prefs.heuristic_enabled(self.scene_props): header_str = 'Current area: {}. '.format(self.area if self.area is",
"= read_int_array(self.island_flags_msg) overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags) if overlap_detected: self.set_status('WARNING', 'Overlapping islands detected') else:",
"None and context.active_object.mode == 'EDIT' def execute(self, context): try: self.p_context = PackContext(context) ratio",
"bl_label = 'Adjust Islands To Texture' bl_description = \"Adjust scale of selected islands",
"# Start progress monitor thread self.progress_queue = queue.Queue() self.connection_thread = threading.Thread(target=connection_thread_func, args=(self.uvp_proc.stdout, self.progress_queue))",
"'none') else: header_str = '' if self.progress_iter_done >= 0: iter_str = 'Iter. done:",
"self.raiseUnexpectedOutputError() similar_island_count = force_read_int(self.similar_islands_msg) similar_islands = read_int_array(self.similar_islands_msg) if not self.prefs.FEATURE_demo: if len(similar_islands) !=",
"RuntimeError('Unexpected output from the pack process') def set_status(self, status_type, status): self.op_status_type = status_type",
"!= UvPackerErrorCode.INVALID_ISLANDS: return if self.invalid_islands_msg is None: self.raiseUnexpectedOutputError() code = force_read_int(self.invalid_islands_msg) subcode =",
"if not self.prefs.FEATURE_demo: if len(similar_islands) != similar_island_count: self.raiseUnexpectedOutputError() for island_idx in similar_islands: self.p_context.select_island_faces(island_idx,",
"is None: raise RuntimeError('Could not find a packing device') if not active_dev.supported: raise",
"= 'uvpackmaster2.uv_udim_support_help' bl_description = \"Show help for UDIM support\" URL_SUFFIX = \"udim-support\" class",
"elif msg_code == UvPackMessageCode.PACK_SOLUTION: pack_solution = read_pack_solution(msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) return True elif msg_code",
"self.prefs.pack_to_others_enabled(self.scene_props): raise RuntimeError(\"'Pack To Others' is not supported with grouping by similarity\") if",
"by the Free Software Foundation; either version 2 # of the License, or",
"NoUvFaceError(Exception): pass class UVP2_OT_PackOperatorGeneric(bpy.types.Operator): bl_options = {'UNDO'} MODAL_INTERVAL_S = 0.1 interactive = False",
"self.p_context.context.tool_settings.uv_select_mode = 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) else: if len(invalid_faces) > 0: self.raiseUnexpectedOutputError() if",
"context.scene.uvp2_props self.confirmation_msg = self.get_confirmation_msg() wm = context.window_manager if self.confirmation_msg != '': pix_per_char =",
"program; if not, write to the Free Software Foundation, # Inc., 51 Franklin",
"handle_uvp_msg(self, msg): msg_code = force_read_int(msg) if self.handle_uvp_msg_spec(msg_code, msg): return if msg_code == UvPackMessageCode.PROGRESS_REPORT:",
"Click OK to continue' return '' def process_result(self): if self.invalid_faces_msg is None: self.raiseUnexpectedOutputError()",
"header_str + iter_str + time_left_str + progress_str + end_str return False def handle_uvp_msg_spec(self,",
"self.scene_props.rot_enable: rot_step_value = self.scene_props.rot_step if self.scene_props.prerot_disable: uvp_args += ['-w'] else: rot_step_value = -1",
"edition') # Validate pack mode pack_mode = UvPackingMode.get_mode(self.scene_props.pack_mode) if pack_mode.req_feature != '' and",
"2 # of the License, or (at your option) any later version. #",
"None: self.raiseUnexpectedOutputError() self.similar_islands_msg = msg elif msg_code == UvPackMessageCode.ISLANDS: self.read_islands(msg) elif msg_code ==",
"self.p_context.serialize_uv_maps(send_unselected, send_groups, send_rot_step, send_lock_groups, send_verts_3d, self.get_group_method() if send_groups else None) if self.require_selection(): if",
"self.scene_props.rot_enable and self.scene_props.island_rot_step_enable def lock_groups_enabled(self): return self.prefs.FEATURE_lock_overlapping and self.scene_props.lock_groups_enable def send_verts_3d(self): return self.scene_props.normalize_islands",
"end_str = '(press ESC to apply result) ' else: end_str = '(press ESC",
"== UvPackingPhaseCode.SIMILAR_SELECTION: return 'Searching for similar islands (press ESC to cancel)' if self.curr_phase",
"if self.curr_phase != UvPackingPhaseCode.RENDER_PRESENTATION and curr_time - self.last_msg_time > self.hang_timeout: self.hang_detected = True",
"if self.prefs.FEATURE_island_rotation: if self.scene_props.rot_enable: rot_step_value = self.scene_props.rot_step if self.scene_props.prerot_disable: uvp_args += ['-w'] else:",
"mode only the number of similar islands found is reported, islands will not",
"is alive if not self.op_done and self.uvp_proc.poll() is not None: # It should",
"str(self.scene_props.heuristic_max_wait_time)] if self.prefs.FEATURE_advanced_heuristic and self.scene_props.advanced_heuristic: uvp_args.append('-H') uvp_args += ['-g', self.scene_props.pack_mode] tile_count, tiles_in_row =",
"self.target_box[0].x *= self.pack_ratio self.target_box[1].x *= self.pack_ratio else: self.target_box = (Vector((0.0, 0.0)), Vector((self.pack_ratio, 1.0)))",
"raise RuntimeError(\"Selected device is not supported\") if retcode == UvPackerErrorCode.DEVICE_DOESNT_SUPPORT_GROUPS_TOGETHER: raise RuntimeError(\"Selected device",
"group count exceeded\") if retcode == UvPackerErrorCode.DEVICE_NOT_SUPPORTED: raise RuntimeError(\"Selected device is not supported\")",
"> 0: self.raiseUnexpectedOutputError() if invalid_face_count > 0: self.set_status('WARNING', 'Number of invalid faces found:",
"License for more details. # # You should have received a copy of",
"'uvpackmaster2.uv_similarity_detection_help' bl_description = \"Show help for similarity detection\" URL_SUFFIX = \"similarity-detection\" class UVP2_OT_InvalidTopologyHelp(UVP2_OT_Help):",
"True except OpCancelledException: self.set_status('INFO', 'Operation cancelled by the user') cancel = True except",
"'Overlap Check' bl_description = 'Check wheter selected UV islands overlap each other' def",
"uvp_args += ['-F', self.scene_props.fixed_scale_strategy] if self.prefs.FEATURE_island_rotation: if self.scene_props.rot_enable: rot_step_value = self.scene_props.rot_step if self.scene_props.prerot_disable:",
"bl_label = 'Measure Area' bl_description = 'Measure area of selected UV islands' def",
"cancel: return self.cancel(context) return {'RUNNING_MODAL'} if not self.op_done else {'PASS_THROUGH'} def pre_op_initialize(self): pass",
"if self.require_selection(): if selected_cnt == 0: raise NoUvFaceError('No UV face selected') else: if",
"class UVP2_OT_SimilarityDetectionHelp(UVP2_OT_Help): bl_label = 'Similarity Detection Help' bl_idname = 'uvpackmaster2.uv_similarity_detection_help' bl_description = \"Show",
"happens when 'Pixel Padding' is set to a small value and the 'Adjustment",
"@classmethod def poll(cls, context): return context.active_object is not None and context.active_object.mode == 'EDIT'",
"UVs' bl_description = 'Validate selected UV faces. The validation procedure looks for invalid",
"layout.column() col.label(text=self.confirmation_msg) def get_confirmation_msg(self): return '' def send_unselected_islands(self): return False def grouping_enabled(self): return",
"def validate_pack_params(self): active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None if active_dev",
"faces will not be selected. Click OK to continue' return '' def process_result(self):",
"if self.curr_phase in { UvPackingPhaseCode.PACKING, UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT }: if self.curr_phase == UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT: header_str =",
"op_status_type == 'INFO': op_status_type = 'WARNING' op_status += '. (WARNINGS were reported -",
"value and the 'Adjustment Time' is not long enough.\") def validate_pack_params(self): active_dev =",
"self.scene_props.rot_step if self.scene_props.prerot_disable: uvp_args += ['-w'] else: rot_step_value = -1 uvp_args += ['-r',",
"progress: {} '.format(percent_progress_str) if self.area is not None: end_str = '(press ESC to",
"str(self.scene_props.precision)] uvp_args += ['-r', str(90)] if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) uvp_args += ['-q',",
"islands, so islands which are similar are placed on top of each other.",
"* (progress_size) for i in range(progress_size): self.progress_array[i] = force_read_int(msg) self.progress_sec_left = force_read_int(msg) self.progress_iter_done",
"raise OpCancelledException() if retcode == UvPackerErrorCode.NO_VALID_STATIC_ISLAND: raise RuntimeError(\"'Pack To Others' option enabled, but",
"retcode == UvPackerErrorCode.CANCELLED: raise OpCancelledException() if retcode == UvPackerErrorCode.NO_VALID_STATIC_ISLAND: raise RuntimeError(\"'Pack To Others'",
"0: raise NoUvFaceError('No UV face visible') self.validate_pack_params() if self.prefs.write_to_file: out_filepath = os.path.join(tempfile.gettempdir(), 'uv_islands.data')",
"**popen_args) out_stream = self.uvp_proc.stdin out_stream.write(self.p_context.serialized_maps) out_stream.flush() self.start_time = time.time() self.last_msg_time = self.start_time self.hang_detected",
"except NoUvFaceError as ex: self.set_status('WARNING', str(ex)) cancel = True except RuntimeError as ex:",
"supported in this engine edition') # Validate pack mode pack_mode = UvPackingMode.get_mode(self.scene_props.pack_mode) if",
"def send_unselected_islands(self): return self.prefs.pack_to_others_enabled(self.scene_props) def grouping_enabled(self): return self.prefs.grouping_enabled(self.scene_props) def get_group_method(self): return self.scene_props.group_method def",
"usually happens when 'Pixel Padding' is set to a small value and the",
"is free software; you can redistribute it and/or # modify it under the",
"reported - check the UVP tab for details)' self.report({op_status_type}, op_status) self.prefs['op_warnings'] = self.op_warnings",
"selected UV islands' def process_result(self): if self.area_msg is None: self.raiseUnexpectedOutputError() area = self.read_area(self.area_msg)",
"the demo mode only the number of invalid faces found is reported, invalid",
"+ iter_str + time_left_str + progress_str + end_str return False def handle_uvp_msg_spec(self, msg_code,",
"bl_idname = 'uvpackmaster2.uv_undo_islands_adjustment_to_texture' bl_label = 'Undo Islands Adjustment' bl_description = \"Undo adjustment performed",
"if self.pack_solution_msg is None: self.raiseUnexpectedOutputError() pack_solution = read_pack_solution(self.pack_solution_msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) self.set_status('INFO', 'Islands aligned')",
"{:3}% (press ESC to cancel)\".format(self.progress_array[0]) raise RuntimeError('Unexpected packing phase encountered') def handle_uvp_msg_spec(self, msg_code,",
"def grouping_enabled(self): return self.prefs.grouping_enabled(self.scene_props) def get_group_method(self): return self.scene_props.group_method def send_rot_step(self): return self.prefs.FEATURE_island_rotation_step and",
"islands are outside their packing box after packing (check the selected islands). This",
"get_group_method(self): return self.scene_props.group_method def send_rot_step(self): return self.prefs.FEATURE_island_rotation_step and self.scene_props.rot_enable and self.scene_props.island_rot_step_enable def lock_groups_enabled(self):",
"return False def grouping_enabled(self): return False def get_group_method(self): raise RuntimeError('Unexpected grouping requested') def",
"stdout=subprocess.PIPE, **popen_args) out_stream = self.uvp_proc.stdin out_stream.write(self.p_context.serialized_maps) out_stream.flush() self.start_time = time.time() self.last_msg_time = self.start_time",
"= 'Help' def execute(self, context): webbrowser.open(UvpLabels.HELP_BASEURL + self.URL_SUFFIX) return {'FINISHED'} class UVP2_OT_UvpSetupHelp(UVP2_OT_Help): bl_label",
"-1 raise RuntimeError('Packer process died unexpectedly') self.handle_progress_msg() except OpFinishedException: finish = True except:",
"+= ['-q', str(self.pack_ratio)] return uvp_args class UVP2_OT_SelectSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_select_similar' bl_label = 'Select",
"Free Software Foundation; either version 2 # of the License, or (at your",
"str(self.prefs.seed)] if self.prefs.wait_for_debugger: uvp_args_final.append('-G') uvp_args_final += ['-T', str(self.prefs.test_param)] print('Pakcer args: ' + '",
"= get_active_image_ratio(self.p_context.context) return (1.0 / ratio, 1.0) class UVP2_OT_UndoIslandsAdjustemntToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_undo_islands_adjustment_to_texture' bl_label",
"detected') else: self.set_status('INFO', 'No overlapping islands detected') def validate_pack_params(self): pass def get_uvp_args(self): uvp_args",
"= self.op_status_type if self.op_status_type is not None else 'INFO' op_status = self.op_status if",
"'Packing stopped - no space to pack all islands' self.add_warning(\"Overlap check was performed",
"islands_msg): islands = [] island_cnt = force_read_int(islands_msg) selected_cnt = force_read_int(islands_msg) for i in",
"== UvPackMessageCode.INVALID_ISLANDS: if self.invalid_islands_msg is not None: self.raiseUnexpectedOutputError() self.invalid_islands_msg = msg elif msg_code",
"if not self.cancel_sig_sent: self.uvp_proc.send_signal(os_cancel_sig()) self.cancel_sig_sent = True return True return False def process_result(self):",
"context.window_manager self._timer = wm.event_timer_add(self.MODAL_INTERVAL_S, window=context.window) wm.modal_handler_add(self) return {'RUNNING_MODAL'} class FakeTimerEvent: def __init__(self): self.type",
"\"Invalid topology encountered in the selected islands. Check the Help panel to learn",
"self.p_context = None self.pack_ratio = 1.0 self.target_box = None self.op_status_type = None self.op_status",
"to apply result) ' else: end_str = '(press ESC to cancel) ' return",
"return True def finish_after_op_done(self): return True def handle_op_done(self): self.op_done = True send_finish_confirmation(self.uvp_proc) try:",
"Step Help' bl_idname = 'uvpackmaster2.uv_island_rot_step_help' bl_description = \"Show help for setting rotation step",
"if not self.p_context.islands_received(): self.raiseUnexpectedOutputError() self.process_invalid_islands() self.process_result() if self.finish_after_op_done(): raise OpFinishedException() def finish(self, context):",
"Topology Help' bl_idname = 'uvpackmaster2.uv_invalid_topology_help' bl_description = \"Show help for handling invalid topology",
"str(UvTopoAnalysisLevel.FORCE_EXTENDED), '-t', str(self.prefs.thread_count)] + self.get_uvp_args() if send_unselected: uvp_args_final.append('-s') if self.grouping_enabled(): uvp_args_final += ['-a',",
"= self.prefs.tile_grid_config(self.scene_props, self.p_context.context) if self.prefs.pack_to_tiles(self.scene_props): uvp_args += ['-V', str(tile_count)] if self.prefs.tiles_enabled(self.scene_props): uvp_args +=",
"now - self.progress_last_update_time > msg_refresh_interval or new_progress_msg != self.progress_msg: self.progress_last_update_time = now self.progress_msg",
"self.op_done = False self.uvp_proc = None self.prefs = get_prefs() self.scene_props = context.scene.uvp2_props self.p_context",
"0: self.set_status('WARNING', 'Pre-validation failed. Number of invalid faces found: ' + str(invalid_face_count) +",
"not None and active_dev.id.startswith('cuda'): return UvpLabels.CUDA_MACOS_CONFIRM_MSG if self.prefs.pack_groups_together(self.scene_props) and not self.prefs.heuristic_enabled(self.scene_props): return UvpLabels.GROUPS_TOGETHER_CONFIRM_MSG",
"= 'Non-Square Packing Help' bl_idname = 'uvpackmaster2.uv_heuristic_search_help' bl_description = \"Show help for heuristic",
"= '' if self.progress_iter_done >= 0: iter_str = 'Iter. done: {}. '.format(self.progress_iter_done) else:",
"= \"Time left: {} sec. \".format(self.progress_sec_left) else: time_left_str = '' percent_progress_str = ''",
"if self.prefs.fixed_scale_enabled(self.scene_props): uvp_args += ['-O'] uvp_args += ['-F', self.scene_props.fixed_scale_strategy] if self.prefs.FEATURE_island_rotation: if self.scene_props.rot_enable:",
"if in_debug_mode(): if self.prefs.seed > 0: uvp_args_final += ['-S', str(self.prefs.seed)] if self.prefs.wait_for_debugger: uvp_args_final.append('-G')",
"op_status) self.prefs['op_warnings'] = self.op_warnings # self.prefs.stats_op_warnings.add(warning_msg) def exit_common(self): if self.interactive: wm = self.p_context.context.window_manager",
"pass class NoUvFaceError(Exception): pass class UVP2_OT_PackOperatorGeneric(bpy.types.Operator): bl_options = {'UNDO'} MODAL_INTERVAL_S = 0.1 interactive",
"END GPL LICENSE BLOCK ##### import subprocess import queue import threading import signal",
"if progress_size > len(self.progress_array): self.progress_array = [0] * (progress_size) for i in range(progress_size):",
"thread self.progress_queue = queue.Queue() self.connection_thread = threading.Thread(target=connection_thread_func, args=(self.uvp_proc.stdout, self.progress_queue)) self.connection_thread.daemon = True self.connection_thread.start()",
"def handle_uvp_msg_spec(self, msg_code, msg): if msg_code == UvPackMessageCode.AREA: self.area = self.read_area(msg) return True",
"off in order to group by similarity\") if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: validate_target_box(self.scene_props) def",
"uvp_args += ['-q', str(self.pack_ratio)] return uvp_args class UVP2_OT_SelectSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_select_similar' bl_label =",
"self.raiseUnexpectedOutputError() raise InvalidIslandsError(error_msg) def require_selection(self): return True def finish_after_op_done(self): return True def handle_op_done(self):",
"'.format(percent_progress_str) if self.area is not None: end_str = '(press ESC to apply result)",
"except: raise RuntimeError('The UVP process wait timeout reached') self.connection_thread.join() self.check_uvp_retcode(self.uvp_proc.returncode) if not self.p_context.islands_received():",
"== UvPackingPhaseCode.AREA_MEASUREMENT: return 'Area measurement in progress (press ESC to cancel)' if self.curr_phase",
"unexpectedly') self.handle_progress_msg() except OpFinishedException: finish = True except: raise if finish: return self.finish(context)",
"= 'Measure Area' bl_description = 'Measure area of selected UV islands' def process_result(self):",
"for a longer time (press ESC to abort)' if self.curr_phase is None: return",
"from the pack process') def set_status(self, status_type, status): self.op_status_type = status_type self.op_status =",
"force_read_int(islands_msg) selected_cnt = force_read_int(islands_msg) for i in range(island_cnt): islands.append(read_int_array(islands_msg)) self.p_context.set_islands(selected_cnt, islands) def process_invalid_islands(self):",
"self.ctrl = False while True: event = FakeTimerEvent() ret = self.modal(context, event) if",
"RuntimeError('Unexpected packing phase encountered') def handle_uvp_msg_spec(self, msg_code, msg): return False def handle_event_spec(self, event):",
"= 'Pack selected UV islands' def __init__(self): self.cancel_sig_sent = False self.area = None",
"print_backtrace(ex) self.report({'ERROR'}, 'Unexpected error') self.p_context.update_meshes() return {'FINISHED'} def get_scale_factors(self): return (1.0, 1.0) class",
"= 'Adjust Islands To Texture' bl_description = \"Adjust scale of selected islands so",
"bl_idname = 'uvpackmaster2.uv_island_rot_step_help' bl_description = \"Show help for setting rotation step on per-island",
"side self.handle_communication() if not self.op_done: # Special value indicating a crash self.prefs.uvp_retcode =",
"self.raiseUnexpectedOutputError() area = self.read_area(self.area_msg) self.prefs.stats_area = area self.set_status('INFO', 'Islands area: ' + str(area))",
"{:3}% (press ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.VALIDATION: return \"Per-face overlap check:",
"self.handle_op_done() elif msg_code == UvPackMessageCode.INVALID_ISLANDS: if self.invalid_islands_msg is not None: self.raiseUnexpectedOutputError() self.invalid_islands_msg =",
"tab for details)' self.report({op_status_type}, op_status) self.prefs['op_warnings'] = self.op_warnings # self.prefs.stats_op_warnings.add(warning_msg) def exit_common(self): if",
"self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) if invalid_face_count > 0: self.set_status('WARNING', 'Pre-validation failed. Number of invalid",
"['-M', str(self.scene_props.pixel_margin)] uvp_args += ['-y', str(self.prefs.pixel_margin_tex_size(self.scene_props, self.p_context.context))] if self.prefs.pixel_padding_enabled(self.scene_props): uvp_args += ['-N', str(self.scene_props.pixel_padding)]",
"similar_island_count = force_read_int(self.similar_islands_msg) similar_islands = read_int_array(self.similar_islands_msg) if not self.prefs.FEATURE_demo: if len(similar_islands) != similar_island_count:",
"self.curr_phase == UvPackingPhaseCode.INITIALIZATION: return 'Initialization (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_ANALYSIS:",
"non-square packing read the documentation\" def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return (ratio, 1.0)",
"be enabled in order to group by similarity\") if self.scene_props.prerot_disable: raise RuntimeError(\"'Pre-Rotation Disable'",
"unselected_cnt = self.p_context.serialize_uv_maps(send_unselected, send_groups, send_rot_step, send_lock_groups, send_verts_3d, self.get_group_method() if send_groups else None) if",
"else 'INFO' op_status = self.op_status if len(self.op_warnings) > 0: if op_status_type == 'INFO':",
"self.get_progress_msg_spec() if progress_msg_spec: return progress_msg_spec if self.curr_phase == UvPackingPhaseCode.INITIALIZATION: return 'Initialization (press ESC",
"error') self.p_context.update_meshes() return {'FINISHED'} def get_scale_factors(self): return (1.0, 1.0) class UVP2_OT_AdjustIslandsToTexture(UVP2_OT_ScaleIslands): bl_idname =",
"def send_verts_3d(self): return False def read_area(self, area_msg): return round(force_read_float(area_msg) / self.pack_ratio, 3) class",
"##### END GPL LICENSE BLOCK ##### import subprocess import queue import threading import",
"no unselected island found in the packing box\") if retcode == UvPackerErrorCode.MAX_GROUP_COUNT_EXCEEDED: raise",
"== UvPackMessageCode.BENCHMARK: stats = self.prefs.stats_array.add() dev_name_len = force_read_int(msg) stats.dev_name = msg.read(dev_name_len).decode('ascii') stats.iter_count =",
"'ESC': raise OpCancelledException() elif event.type == 'TIMER': self.handle_communication() def modal(self, context, event): cancel",
"self.p_context.scale_selected_faces(self.get_scale_factors()) except RuntimeError as ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, str(ex)) except Exception as",
"order to group by similarity\") if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: validate_target_box(self.scene_props) def get_target_box_string(self, target_box):",
"was performed only on the islands which were packed\") else: op_status = 'Packing",
"UvGroupingMethod.SIMILARITY.code: if self.prefs.pack_to_others_enabled(self.scene_props): raise RuntimeError(\"'Pack To Others' is not supported with grouping by",
"msg_received += 1 curr_time = time.time() if msg_received > 0: self.last_msg_time = curr_time",
"self.set_status('INFO', 'Operation cancelled by the user') cancel = True except InvalidIslandsError as err:",
"for i in range(island_cnt): islands.append(read_int_array(islands_msg)) self.p_context.set_islands(selected_cnt, islands) def process_invalid_islands(self): if self.uvp_proc.returncode != UvPackerErrorCode.INVALID_ISLANDS:",
"+= '. (WARNINGS were reported - check the UVP tab for details)' self.report({op_status_type},",
"= 'Select Similar' bl_description = \"Selects all islands which have similar shape to",
"\"island-rotation-step\" class UVP2_OT_UdimSupportHelp(UVP2_OT_Help): bl_label = 'UDIM Support Help' bl_idname = 'uvpackmaster2.uv_udim_support_help' bl_description =",
"non-square packing\" URL_SUFFIX = \"non-square-packing\" class UVP2_OT_SimilarityDetectionHelp(UVP2_OT_Help): bl_label = 'Similarity Detection Help' bl_idname",
"self.report({'ERROR'}, 'Unexpected error') self.p_context.update_meshes() return {'FINISHED'} def get_scale_factors(self): return (1.0, 1.0) class UVP2_OT_AdjustIslandsToTexture(UVP2_OT_ScaleIslands):",
"['-o', str(UvPackerOpcode.VALIDATE_UVS)] return uvp_args class UVP2_OT_ProcessSimilar(UVP2_OT_PackOperatorGeneric): def validate_pack_params(self): pass def get_uvp_args(self): uvp_args =",
"now = time.time() if now - self.progress_last_update_time > msg_refresh_interval or new_progress_msg != self.progress_msg:",
"else: time_left_str = '' percent_progress_str = '' for prog in self.progress_array: percent_progress_str +=",
"== UvPackerErrorCode.NO_SPACE: op_status = 'Packing stopped - no space to pack all islands'",
"self.prefs.grouping_enabled(self.scene_props) def get_group_method(self): return self.scene_props.group_method def send_rot_step(self): return self.prefs.FEATURE_island_rotation_step and self.scene_props.rot_enable and self.scene_props.island_rot_step_enable",
"self.invalid_islands_msg is not None: self.raiseUnexpectedOutputError() self.invalid_islands_msg = msg elif msg_code == UvPackMessageCode.ISLAND_FLAGS: if",
"get_group_method(self): raise RuntimeError('Unexpected grouping requested') def send_rot_step(self): return False def lock_groups_enabled(self): return False",
"= ['-o', str(self.get_uvp_opcode()), '-I', str(self.scene_props.similarity_threshold)] uvp_args += ['-i', str(self.scene_props.precision)] uvp_args += ['-r', str(90)]",
"process_result(self): if self.similar_islands_msg is None: self.raiseUnexpectedOutputError() similar_island_count = force_read_int(self.similar_islands_msg) similar_islands = read_int_array(self.similar_islands_msg) if",
"bl_description = \"Show help for setting rotation step on per-island level\" URL_SUFFIX =",
"read_pack_solution(msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) return True elif msg_code == UvPackMessageCode.BENCHMARK: stats = self.prefs.stats_array.add() dev_name_len",
"False def grouping_enabled(self): return False def get_group_method(self): raise RuntimeError('Unexpected grouping requested') def send_rot_step(self):",
"def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.OVERLAP_CHECK)] return uvp_args class UVP2_OT_MeasureAreaOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_measure_area'",
"str(UvPackerOpcode.OVERLAP_CHECK)] return uvp_args class UVP2_OT_MeasureAreaOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_measure_area' bl_label = 'Measure Area' bl_description",
"return # Generic event processing code if event.type == 'ESC': raise OpCancelledException() elif",
"= force_read_int(msg) self.progress_iter_done = force_read_int(msg) # Inform the upper layer wheter it should",
"get_prefs() self.scene_props = context.scene.uvp2_props self.p_context = None self.pack_ratio = 1.0 self.target_box = None",
"'-E', '-e', str(UvTopoAnalysisLevel.FORCE_EXTENDED), '-t', str(self.prefs.thread_count)] + self.get_uvp_args() if send_unselected: uvp_args_final.append('-s') if self.grouping_enabled(): uvp_args_final",
"== 0: self.raiseUnexpectedOutputError() self.p_context.handle_invalid_islands(invalid_islands) if code == UvInvalidIslandCode.TOPOLOGY: error_msg = \"Invalid topology encountered",
"if self.prefs.multi_device_enabled(self.scene_props): uvp_args.append('-u') if self.prefs.lock_overlap_enabled(self.scene_props): uvp_args += ['-l', self.scene_props.lock_overlapping_mode] if self.prefs.pack_to_others_enabled(self.scene_props): uvp_args +=",
"packing click the help icon\" def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return (1.0 /",
"'.format(self.area if self.area is not None else 'none') else: header_str = '' if",
"= 'Current area: {}. '.format(self.area if self.area is not None else 'none') else:",
"= get_prefs() self.scene_props = context.scene.uvp2_props self.confirmation_msg = self.get_confirmation_msg() wm = context.window_manager if self.confirmation_msg",
"op_status += ', packed islands area: ' + str(self.area) self.set_status('INFO', op_status) if overlap_detected:",
"self.report_status() return {'FINISHED'} if self.interactive: wm = context.window_manager self._timer = wm.event_timer_add(self.MODAL_INTERVAL_S, window=context.window) wm.modal_handler_add(self)",
"will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty",
"process') def set_status(self, status_type, status): self.op_status_type = status_type self.op_status = status def add_warning(self,",
"err: self.set_status('ERROR', str(err)) cancel = True except RuntimeError as ex: if in_debug_mode(): print_backtrace(ex)",
"return if retcode == UvPackerErrorCode.CANCELLED: raise OpCancelledException() if retcode == UvPackerErrorCode.NO_VALID_STATIC_ISLAND: raise RuntimeError(\"'Pack",
"= \"Show help for similarity detection\" URL_SUFFIX = \"similarity-detection\" class UVP2_OT_InvalidTopologyHelp(UVP2_OT_Help): bl_label =",
"out_stream.flush() self.start_time = time.time() self.last_msg_time = self.start_time self.hang_detected = False self.hang_timeout = 10.0",
"raise RuntimeError('Unexpected output from the pack process') def set_status(self, status_type, status): self.op_status_type =",
"rot_step_value = -1 uvp_args += ['-r', str(rot_step_value)] if self.prefs.heuristic_enabled(self.scene_props): uvp_args += ['-h', str(self.scene_props.heuristic_search_time),",
"islands detected') else: self.set_status('INFO', 'No overlapping islands detected') def validate_pack_params(self): pass def get_uvp_args(self):",
"broken\") reset_stats(self.prefs) self.p_context = PackContext(context) self.pre_op_initialize() send_unselected = self.send_unselected_islands() send_rot_step = self.send_rot_step() send_groups",
"if cancel: return self.cancel(context) return {'RUNNING_MODAL'} if not self.op_done else {'PASS_THROUGH'} def pre_op_initialize(self):",
"UvPackingPhaseCode.OVERLAP_CHECK: return 'Overlap check in progress (press ESC to cancel)' if self.curr_phase ==",
"end_str return False def handle_uvp_msg_spec(self, msg_code, msg): if msg_code == UvPackMessageCode.AREA: self.area =",
"pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.MEASURE_AREA)] return uvp_args class UVP2_OT_ValidateOperator(UVP2_OT_PackOperatorGeneric): bl_idname =",
"if self.curr_phase == UvPackingPhaseCode.AREA_MEASUREMENT: return 'Area measurement in progress (press ESC to cancel)'",
"= percent_progress_str[:-2] progress_str = 'Pack progress: {} '.format(percent_progress_str) if self.area is not None:",
"str(similar_island_count)) class UVP2_OT_AlignSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_align_similar' bl_label = 'Align Similar' bl_description = \"Align",
"def handle_communication(self): if self.op_done: return msg_received = 0 while True: try: item =",
"self.area_msg = None self.invalid_faces_msg = None self.similar_islands_msg = None self.islands_metadata_msg = None except",
"For for info regarding non-square packing read the documentation\" def get_scale_factors(self): ratio =",
"= self.send_unselected_islands() send_rot_step = self.send_rot_step() send_groups = self.grouping_enabled() and (to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.EXTERNAL) send_lock_groups",
"Foundation; either version 2 # of the License, or (at your option) any",
"pack_mode.req_feature != '' and not getattr(self.prefs, 'FEATURE_' + pack_mode.req_feature): raise RuntimeError('Selected packing mode",
"islands' self.add_warning(\"Overlap check was performed only on the islands which were packed\") else:",
"not be required to but check once again to be on the safe",
"# as published by the Free Software Foundation; either version 2 # of",
"bl_description = 'Pack selected UV islands' def __init__(self): self.cancel_sig_sent = False self.area =",
"self.pack_ratio = get_active_image_ratio(self.p_context.context) uvp_args += ['-q', str(self.pack_ratio)] return uvp_args class UVP2_OT_SelectSimilar(UVP2_OT_ProcessSimilar): bl_idname =",
"for packing into the active texture. CAUTION: this operator should be used only",
"'(press ESC to apply result) ' else: end_str = '(press ESC to cancel)",
"'uvpackmaster2.uv_align_similar' bl_label = 'Align Similar' bl_description = \"Align selected islands, so islands which",
"= 'Manual Grouping Help' bl_idname = 'uvpackmaster2.uv_manual_grouping_help' bl_description = \"Show help for manual",
"send_verts_3d(self): return False def read_area(self, area_msg): return round(force_read_float(area_msg) / self.pack_ratio, 3) class UVP2_OT_PackOperator(UVP2_OT_PackOperatorGeneric):",
"self.uvp_proc = None self.prefs = get_prefs() self.scene_props = context.scene.uvp2_props self.p_context = None self.pack_ratio",
"True send_finish_confirmation(self.uvp_proc) try: self.uvp_proc.wait(5) except: raise RuntimeError('The UVP process wait timeout reached') self.connection_thread.join()",
"similarity detection\" URL_SUFFIX = \"similarity-detection\" class UVP2_OT_InvalidTopologyHelp(UVP2_OT_Help): bl_label = 'Invalid Topology Help' bl_idname",
"['-o', str(UvPackerOpcode.OVERLAP_CHECK)] return uvp_args class UVP2_OT_MeasureAreaOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_measure_area' bl_label = 'Measure Area'",
"self.prefs.multi_device_enabled(self.scene_props): uvp_args.append('-u') if self.prefs.lock_overlap_enabled(self.scene_props): uvp_args += ['-l', self.scene_props.lock_overlapping_mode] if self.prefs.pack_to_others_enabled(self.scene_props): uvp_args += ['-x']",
"validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.MEASURE_AREA)] return uvp_args class UVP2_OT_ValidateOperator(UVP2_OT_PackOperatorGeneric): bl_idname",
"-1 uvp_args += ['-r', str(rot_step_value)] if self.prefs.heuristic_enabled(self.scene_props): uvp_args += ['-h', str(self.scene_props.heuristic_search_time), '-j', str(self.scene_props.heuristic_max_wait_time)]",
"msg): msg_code = force_read_int(msg) if self.handle_uvp_msg_spec(msg_code, msg): return if msg_code == UvPackMessageCode.PROGRESS_REPORT: self.curr_phase",
"'Number of invalid faces found: ' + str(invalid_face_count)) else: self.set_status('INFO', 'No invalid faces",
"'UVP Setup Help' bl_idname = 'uvpackmaster2.uv_uvp_setup_help' bl_description = \"Show help for UVP setup\"",
"if self.curr_phase == UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT: header_str = 'Pixel margin adjustment. ' elif self.prefs.heuristic_enabled(self.scene_props): header_str",
"self.read_area(msg) return True elif msg_code == UvPackMessageCode.PACK_SOLUTION: pack_solution = read_pack_solution(msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) return",
"bl_description = \"Show help for similarity detection\" URL_SUFFIX = \"similarity-detection\" class UVP2_OT_InvalidTopologyHelp(UVP2_OT_Help): bl_label",
"UVP2_OT_HeuristicSearchHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing Help' bl_idname = 'uvpackmaster2.uv_heuristic_search_help' bl_description = \"Show help",
"self.p_context.update_meshes() if cancel: if self.uvp_proc is not None: self.uvp_proc.terminate() self.report_status() return {'FINISHED'} if",
"invalid UV faces i.e. faces with area close to 0, self-intersecting faces, faces",
"= 'WARNING' op_status += '. (WARNINGS were reported - check the UVP tab",
"def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.OVERLAP_CHECK)] return uvp_args class UVP2_OT_MeasureAreaOperator(UVP2_OT_PackOperatorGeneric):",
"= True except: raise if finish: return self.finish(context) except OpAbortedException: self.set_status('INFO', 'Packer process",
"event.type == 'ESC': raise OpAbortedException() if self.handle_event_spec(event): return # Generic event processing code",
"= \"Show help for non-square packing\" URL_SUFFIX = \"non-square-packing\" class UVP2_OT_SimilarityDetectionHelp(UVP2_OT_Help): bl_label =",
"None self.similar_islands_msg = None self.islands_metadata_msg = None except NoUvFaceError as ex: self.set_status('WARNING', str(ex))",
"stats.dev_name = msg.read(dev_name_len).decode('ascii') stats.iter_count = force_read_int(msg) stats.total_time = force_read_int(msg) stats.avg_time = force_read_int(msg) return",
"['-U', str(self.scene_props.group_compactness)] if self.prefs.multi_device_enabled(self.scene_props): uvp_args.append('-u') if self.prefs.lock_overlap_enabled(self.scene_props): uvp_args += ['-l', self.scene_props.lock_overlapping_mode] if self.prefs.pack_to_others_enabled(self.scene_props):",
"process returned an error') def raiseUnexpectedOutputError(self): raise RuntimeError('Unexpected output from the pack process')",
"retcode in {UvPackerErrorCode.SUCCESS, UvPackerErrorCode.INVALID_ISLANDS, UvPackerErrorCode.NO_SPACE, UvPackerErrorCode.PRE_VALIDATION_FAILED}: return if retcode == UvPackerErrorCode.CANCELLED: raise OpCancelledException()",
"'EDIT' def check_uvp_retcode(self, retcode): self.prefs.uvp_retcode = retcode if retcode in {UvPackerErrorCode.SUCCESS, UvPackerErrorCode.INVALID_ISLANDS, UvPackerErrorCode.NO_SPACE,",
"event): # Kill the UVP process unconditionally if a hang was detected if",
"self.prefs.tiles_enabled(self.scene_props): uvp_args += ['-C', str(tiles_in_row)] if self.grouping_enabled(): if to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.SIMILARITY: uvp_args +=",
"read_int_array(self.island_flags_msg) overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags) if self.area is not None: self.prefs.stats_area = self.area",
"= get_prefs() self.scene_props = context.scene.uvp2_props self.p_context = None self.pack_ratio = 1.0 self.target_box =",
"= \"island-rotation-step\" class UVP2_OT_UdimSupportHelp(UVP2_OT_Help): bl_label = 'UDIM Support Help' bl_idname = 'uvpackmaster2.uv_udim_support_help' bl_description",
"self.grouping_enabled(): uvp_args_final += ['-a', str(to_uvp_group_method(self.get_group_method()))] if self.send_rot_step(): uvp_args_final += ['-R'] if self.lock_groups_enabled(): uvp_args_final",
"self.prefs.FEATURE_lock_overlapping and self.scene_props.lock_groups_enable def send_verts_3d(self): return self.scene_props.normalize_islands def get_progress_msg_spec(self): if self.curr_phase in {",
"rotations must be enabled in order to group by similarity\") if self.scene_props.prerot_disable: raise",
"self.curr_phase == UvPackingPhaseCode.OVERLAP_CHECK: return 'Overlap check in progress (press ESC to cancel)' if",
"without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR",
"island_flags = read_int_array(self.island_flags_msg) overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags) if overlap_detected: self.set_status('WARNING', 'Overlapping islands detected')",
"= get_active_image_ratio(self.p_context.context) uvp_args += ['-q', str(self.pack_ratio)] return uvp_args class UVP2_OT_SelectSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_select_similar'",
"import tempfile class InvalidIslandsError(Exception): pass class NoUvFaceError(Exception): pass class UVP2_OT_PackOperatorGeneric(bpy.types.Operator): bl_options = {'UNDO'}",
"= IslandParamInfo.get_param_info_array() error_msg = \"Faces with inconsistent {} values found in the selected",
"bl_idname = 'uvpackmaster2.uv_manual_grouping_help' bl_description = \"Show help for manual grouping\" URL_SUFFIX = \"udim-support#manual-grouping\"",
"LICENSE BLOCK ##### import subprocess import queue import threading import signal import webbrowser",
"aborted') return if not self.prefs.FEATURE_demo: if self.island_flags_msg is None: self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg)",
"cancel = False finish = False try: try: self.handle_event(event) # Check whether the",
"= \"invalid-topology-issues\" class UVP2_OT_PixelMarginHelp(UVP2_OT_Help): bl_label = 'Pixel Margin Help' bl_idname = 'uvpackmaster2.uv_pixel_margin_help' bl_description",
"percent_progress_str[:-2] progress_str = 'Pack progress: {} '.format(percent_progress_str) if self.area is not None: end_str",
"error_msg = \"Invalid topology encountered in the selected islands. Check the Help panel",
"force_read_int(msg) if self.handle_uvp_msg_spec(msg_code, msg): return if msg_code == UvPackMessageCode.PROGRESS_REPORT: self.curr_phase = force_read_int(msg) progress_size",
"add_warning(self, warn_msg): self.op_warnings.append(warn_msg) def report_status(self): if self.op_status is not None: self.prefs['op_status'] = self.op_status",
"if self.prefs.tiles_enabled(self.scene_props): uvp_args += ['-C', str(tiles_in_row)] if self.grouping_enabled(): if to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.SIMILARITY: uvp_args",
"(progress_size) for i in range(progress_size): self.progress_array[i] = force_read_int(msg) self.progress_sec_left = force_read_int(msg) self.progress_iter_done =",
"a copy of the GNU General Public License # along with this program;",
"= [0] * (progress_size) for i in range(progress_size): self.progress_array[i] = force_read_int(msg) self.progress_sec_left =",
"raise NoUvFaceError('No UV face visible') self.validate_pack_params() if self.prefs.write_to_file: out_filepath = os.path.join(tempfile.gettempdir(), 'uv_islands.data') out_file",
"wheter it should finish if self.curr_phase == UvPackingPhaseCode.DONE: self.handle_op_done() elif msg_code == UvPackMessageCode.INVALID_ISLANDS:",
"if self.send_rot_step(): uvp_args_final += ['-R'] if self.lock_groups_enabled(): uvp_args_final += ['-Q'] if in_debug_mode(): if",
"str(self.scene_props.heuristic_search_time), '-j', str(self.scene_props.heuristic_max_wait_time)] if self.prefs.FEATURE_advanced_heuristic and self.scene_props.advanced_heuristic: uvp_args.append('-H') uvp_args += ['-g', self.scene_props.pack_mode] tile_count,",
"RuntimeError('Unexpected output from the connection thread') msg_received += 1 curr_time = time.time() if",
"islands which were packed\") else: op_status = 'Packing done' if self.area is not",
"'Darwin': active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None if active_dev is",
"(if used in the operation).\") if outside_detected: self.add_warning(\"Some islands are outside their packing",
"+ '%, ' percent_progress_str = percent_progress_str[:-2] progress_str = 'Pack progress: {} '.format(percent_progress_str) if",
"[0] self.progress_msg = '' self.progress_sec_left = -1 self.progress_iter_done = -1 self.progress_last_update_time = 0.0",
"== UvPackingPhaseCode.SIMILAR_ALIGNING: return 'Similar islands aligning (press ESC to cancel)' if self.curr_phase ==",
"You should have received a copy of the GNU General Public License #",
"engine edition') if self.grouping_enabled(): if self.get_group_method() == UvGroupingMethod.SIMILARITY.code: if self.prefs.pack_to_others_enabled(self.scene_props): raise RuntimeError(\"'Pack To",
"!= UvPackingPhaseCode.RENDER_PRESENTATION and curr_time - self.last_msg_time > self.hang_timeout: self.hang_detected = True def handle_event(self,",
"self.URL_SUFFIX) return {'FINISHED'} class UVP2_OT_UvpSetupHelp(UVP2_OT_Help): bl_label = 'UVP Setup Help' bl_idname = 'uvpackmaster2.uv_uvp_setup_help'",
"= get_prefs() return prefs.uvp_initialized and context.active_object is not None and context.active_object.mode == 'EDIT'",
"if len(self.op_warnings) > 0: if op_status_type == 'INFO': op_status_type = 'WARNING' op_status +=",
"to cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_ALIGNING: return 'Similar islands aligning (press ESC to",
"= -1 uvp_args += ['-r', str(rot_step_value)] if self.prefs.heuristic_enabled(self.scene_props): uvp_args += ['-h', str(self.scene_props.heuristic_search_time), '-j',",
"{:3}% (press ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.OVERLAP_CHECK: return 'Overlap check in",
"= msg.read(dev_name_len).decode('ascii') stats.iter_count = force_read_int(msg) stats.total_time = force_read_int(msg) stats.avg_time = force_read_int(msg) return True",
"info regarding similarity detection click the help button\" def get_confirmation_msg(self): if self.prefs.FEATURE_demo: return",
"try: item = self.progress_queue.get_nowait() except queue.Empty as ex: break if isinstance(item, str): raise",
"+ time_left_str + progress_str + end_str return False def handle_uvp_msg_spec(self, msg_code, msg): if",
"'Pixel Margin Help' bl_idname = 'uvpackmaster2.uv_pixel_margin_help' bl_description = \"Show help for setting margin",
"', packed islands area: ' + str(self.area) self.set_status('INFO', op_status) if overlap_detected: self.add_warning(\"Overlapping islands",
"len(invalid_islands) == 0: self.raiseUnexpectedOutputError() self.p_context.handle_invalid_islands(invalid_islands) if code == UvInvalidIslandCode.TOPOLOGY: error_msg = \"Invalid topology",
"= self.op_status op_status_type = self.op_status_type if self.op_status_type is not None else 'INFO' op_status",
"unregister_uvp() redraw_ui(context) raise RuntimeError(\"UVP engine broken\") reset_stats(self.prefs) self.p_context = PackContext(context) self.pre_op_initialize() send_unselected =",
"packed\") else: op_status = 'Packing done' if self.area is not None: op_status +=",
"error_msg = \"Faces with inconsistent {} values found in the selected islands\".format(param_array[subcode].NAME) else:",
"def get_progress_msg(self): if self.hang_detected: return 'Packer process not responding for a longer time",
"process not responding for a longer time (press ESC to abort)' if self.curr_phase",
"= \"pixel-margin\" class UVP2_OT_IslandRotStepHelp(UVP2_OT_Help): bl_label = 'Island Rotation Step Help' bl_idname = 'uvpackmaster2.uv_island_rot_step_help'",
"ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.OVERLAP_CHECK: return 'Overlap check in progress (press",
"def poll(cls, context): return context.active_object is not None and context.active_object.mode == 'EDIT' def",
"= FakeTimerEvent() ret = self.modal(context, event) if ret.intersection({'FINISHED', 'CANCELLED'}): return ret time.sleep(self.MODAL_INTERVAL_S) def",
"Rotation Step Help' bl_idname = 'uvpackmaster2.uv_island_rot_step_help' bl_description = \"Show help for setting rotation",
"!= '': pix_per_char = 5 dialog_width = pix_per_char * len(self.confirmation_msg) + 50 return",
"get_uvp_opcode(self): return UvPackerOpcode.SELECT_SIMILAR def process_result(self): if self.similar_islands_msg is None: self.raiseUnexpectedOutputError() similar_island_count = force_read_int(self.similar_islands_msg)",
"self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) self.set_status('INFO', 'Islands aligned') class UVP2_OT_ScaleIslands(bpy.types.Operator): bl_options = {'UNDO'} @classmethod def poll(cls,",
"force_read_int(islands_msg) for i in range(island_cnt): islands.append(read_int_array(islands_msg)) self.p_context.set_islands(selected_cnt, islands) def process_invalid_islands(self): if self.uvp_proc.returncode !=",
"pack_solution) return True elif msg_code == UvPackMessageCode.BENCHMARK: stats = self.prefs.stats_array.add() dev_name_len = force_read_int(msg)",
"return 'WARNING: in the demo mode only the number of invalid faces found",
"retcode == UvPackerErrorCode.DEVICE_DOESNT_SUPPORT_GROUPS_TOGETHER: raise RuntimeError(\"Selected device doesn't support packing groups together\") raise RuntimeError('Pack",
"'Manual Grouping Help' bl_idname = 'uvpackmaster2.uv_manual_grouping_help' bl_description = \"Show help for manual grouping\"",
"except RuntimeError as ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, str(ex)) except Exception as ex:",
"is not None: self.uvp_proc.terminate() self.report_status() return {'FINISHED'} if self.interactive: wm = context.window_manager self._timer",
"(press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.RENDER_PRESENTATION: return 'Close the demo window",
"uvp_args class UVP2_OT_SelectSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_select_similar' bl_label = 'Select Similar' bl_description = \"Selects",
"regarding non-square packing click the help icon\" def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return",
"islands will not be selected. Click OK to continue' return '' def send_unselected_islands(self):",
"False, True) else: self.p_context.context.tool_settings.uv_select_mode = 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) if invalid_face_count > 0:",
"return self.prefs.FEATURE_island_rotation_step and self.scene_props.rot_enable and self.scene_props.island_rot_step_enable def lock_groups_enabled(self): return self.prefs.FEATURE_lock_overlapping and self.scene_props.lock_groups_enable def",
"status_type, status): self.op_status_type = status_type self.op_status = status def add_warning(self, warn_msg): self.op_warnings.append(warn_msg) def",
"self.prefs.fixed_scale_enabled(self.scene_props): uvp_args += ['-O'] uvp_args += ['-F', self.scene_props.fixed_scale_strategy] if self.prefs.FEATURE_island_rotation: if self.scene_props.rot_enable: rot_step_value",
"error') def raiseUnexpectedOutputError(self): raise RuntimeError('Unexpected output from the pack process') def set_status(self, status_type,",
"handle_op_done(self): self.op_done = True send_finish_confirmation(self.uvp_proc) try: self.uvp_proc.wait(5) except: raise RuntimeError('The UVP process wait",
"encountered') def handle_uvp_msg_spec(self, msg_code, msg): return False def handle_event_spec(self, event): return False def",
"self.invalid_faces_msg = msg elif msg_code == UvPackMessageCode.SIMILAR_ISLANDS: if self.similar_islands_msg is not None: self.raiseUnexpectedOutputError()",
"wm = context.window_manager self._timer = wm.event_timer_add(self.MODAL_INTERVAL_S, window=context.window) wm.modal_handler_add(self) return {'RUNNING_MODAL'} class FakeTimerEvent: def",
"= force_read_int(self.invalid_islands_msg) subcode = force_read_int(self.invalid_islands_msg) invalid_islands = read_int_array(self.invalid_islands_msg) if len(invalid_islands) == 0: self.raiseUnexpectedOutputError()",
"= force_read_int(msg) if progress_size > len(self.progress_array): self.progress_array = [0] * (progress_size) for i",
"context): return context.active_object is not None and context.active_object.mode == 'EDIT' def execute(self, context):",
"is None: self.raiseUnexpectedOutputError() area = self.read_area(self.area_msg) self.prefs.stats_area = area self.set_status('INFO', 'Islands area: '",
"if active_dev is not None and active_dev.id.startswith('cuda'): return UvpLabels.CUDA_MACOS_CONFIRM_MSG if self.prefs.pack_groups_together(self.scene_props) and not",
"URL_SUFFIX = \"heuristic-search\" class UVP2_OT_NonSquarePackingHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing Help' bl_idname = 'uvpackmaster2.uv_nonsquare_packing_help'",
"self.scene_props.normalize_islands def get_progress_msg_spec(self): if self.curr_phase in { UvPackingPhaseCode.PACKING, UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT }: if self.curr_phase ==",
"self.hang_timeout = 10.0 # Start progress monitor thread self.progress_queue = queue.Queue() self.connection_thread =",
"exit_common(self): if self.interactive: wm = self.p_context.context.window_manager wm.event_timer_remove(self._timer) self.p_context.update_meshes() self.report_status() if in_debug_mode(): print('UVP operation",
"force_read_int(msg) # Inform the upper layer wheter it should finish if self.curr_phase ==",
"= False self.op_done = False self.uvp_proc = None self.prefs = get_prefs() self.scene_props =",
"info regarding non-square packing click the help icon\" def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context)",
"handle_event_spec(self, event): if event.type == 'ESC': if not self.cancel_sig_sent: self.uvp_proc.send_signal(os_cancel_sig()) self.cancel_sig_sent = True",
".utils import * from .pack_context import * from .connection import * from .prefs",
"area: {}. '.format(self.area if self.area is not None else 'none') else: header_str =",
"faces overlapping each other' def get_confirmation_msg(self): if self.prefs.FEATURE_demo: return 'WARNING: in the demo",
"long enough.\") def validate_pack_params(self): active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None",
"islands). Consider increasing the 'Precision' parameter. Sometimes increasing the 'Adjustment Time' may solve",
".register import check_uvp, unregister_uvp import bmesh import bpy import mathutils import tempfile class",
"bl_label = 'Non-Square Packing Help' bl_idname = 'uvpackmaster2.uv_nonsquare_packing_help' bl_description = \"Show help for",
"group by similarity\") if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: validate_target_box(self.scene_props) def get_target_box_string(self, target_box): prec =",
"cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_SELECTION: return 'Searching for similar islands (press ESC to",
"return True def handle_op_done(self): self.op_done = True send_finish_confirmation(self.uvp_proc) try: self.uvp_proc.wait(5) except: raise RuntimeError('The",
"poll(cls, context): return context.active_object is not None and context.active_object.mode == 'EDIT' def execute(self,",
"UVP process wait timeout reached') self.connection_thread.join() self.check_uvp_retcode(self.uvp_proc.returncode) if not self.p_context.islands_received(): self.raiseUnexpectedOutputError() self.process_invalid_islands() self.process_result()",
"for info regarding non-square packing click the help icon\" def get_scale_factors(self): ratio =",
"'No invalid faces found') def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.VALIDATE_UVS)]",
"island found in the packing box\") if retcode == UvPackerErrorCode.MAX_GROUP_COUNT_EXCEEDED: raise RuntimeError(\"Maximal group",
"for info regarding non-square packing read the documentation\" def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context)",
"\"pixel-margin\" class UVP2_OT_IslandRotStepHelp(UVP2_OT_Help): bl_label = 'Island Rotation Step Help' bl_idname = 'uvpackmaster2.uv_island_rot_step_help' bl_description",
"into the active texture. CAUTION: this operator should be used only when packing",
"not None: self.p_context.update_meshes() if cancel: if self.uvp_proc is not None: self.uvp_proc.terminate() self.report_status() return",
"and the 'Adjustment Time' is not long enough.\") def validate_pack_params(self): active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx]",
"'INFO': op_status_type = 'WARNING' op_status += '. (WARNINGS were reported - check the",
"is not None: self.prefs.stats_area = self.area if self.uvp_proc.returncode == UvPackerErrorCode.NO_SPACE: op_status = 'Packing",
"not None: self.raiseUnexpectedOutputError() self.island_flags_msg = msg elif msg_code == UvPackMessageCode.PACK_SOLUTION: if self.pack_solution_msg is",
"is not supported with grouping by similarity\") if not self.scene_props.rot_enable: raise RuntimeError(\"Island rotations",
"= area self.set_status('INFO', 'Islands area: ' + str(area)) def validate_pack_params(self): pass def get_uvp_args(self):",
"self.type = 'TIMER' self.value = 'NOTHING' self.ctrl = False while True: event =",
"['-S', str(self.prefs.seed)] if self.prefs.wait_for_debugger: uvp_args_final.append('-G') uvp_args_final += ['-T', str(self.prefs.test_param)] print('Pakcer args: ' +",
"raise RuntimeError('Could not find a packing device') if not active_dev.supported: raise RuntimeError('Selected packing",
"uvp_args += ['-V', str(tile_count)] if self.prefs.tiles_enabled(self.scene_props): uvp_args += ['-C', str(tiles_in_row)] if self.grouping_enabled(): if",
"if overlap_detected: self.set_status('WARNING', 'Overlapping islands detected') else: self.set_status('INFO', 'No overlapping islands detected') def",
"ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', 'Unexpected error') cancel = True if self.p_context is",
"return \"{}:{}:{}:{}\".format( round(target_box[0].x, prec), round(target_box[0].y, prec), round(target_box[1].x, prec), round(target_box[1].y, prec)) def get_uvp_args(self): uvp_args",
"if self.island_flags_msg is None: self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg) overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags) if",
"self.scene_props.rot_enable: raise RuntimeError(\"Island rotations must be enabled in order to group by similarity\")",
"prec), round(target_box[1].y, prec)) def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.PACK), '-i', str(self.scene_props.precision), '-m', str(self.scene_props.margin)]",
"UvPackMessageCode.INVALID_FACES: if self.invalid_faces_msg is not None: self.raiseUnexpectedOutputError() self.invalid_faces_msg = msg elif msg_code ==",
"UvGroupingMethodUvp.SIMILARITY: uvp_args += ['-I', str(self.scene_props.similarity_threshold)] if self.prefs.pack_groups_together(self.scene_props): uvp_args += ['-U', str(self.scene_props.group_compactness)] if self.prefs.multi_device_enabled(self.scene_props):",
"if len(similar_islands) > 0: self.raiseUnexpectedOutputError() self.set_status('INFO', 'Similar islands found: ' + str(similar_island_count)) class",
"self.raiseUnexpectedOutputError() self.process_invalid_islands() self.process_result() if self.finish_after_op_done(): raise OpFinishedException() def finish(self, context): self.exit_common() return {'FINISHED',",
"iter_str = '' if self.progress_sec_left >= 0: time_left_str = \"Time left: {} sec.",
"check the UVP tab for details)' self.report({op_status_type}, op_status) self.prefs['op_warnings'] = self.op_warnings # self.prefs.stats_op_warnings.add(warning_msg)",
"== UvPackMessageCode.ISLANDS_METADATA: if self.islands_metadata_msg is not None: self.raiseUnexpectedOutputError() self.islands_metadata_msg = msg else: self.raiseUnexpectedOutputError()",
"= False else: if self.curr_phase != UvPackingPhaseCode.RENDER_PRESENTATION and curr_time - self.last_msg_time > self.hang_timeout:",
"= None self.prefs = get_prefs() self.scene_props = context.scene.uvp2_props self.p_context = None self.pack_ratio =",
"not supported in this engine edition') if self.grouping_enabled(): if self.get_group_method() == UvGroupingMethod.SIMILARITY.code: if",
"if active_dev is None: raise RuntimeError('Could not find a packing device') if not",
"+= ['-q', str(self.pack_ratio)] if self.target_box is not None: self.target_box[0].x *= self.pack_ratio self.target_box[1].x *=",
"= 0 while True: try: item = self.progress_queue.get_nowait() except queue.Empty as ex: break",
"from .prefs import * from .os_iface import * from .island_params import * from",
"percent_progress_str = '' for prog in self.progress_array: percent_progress_str += str(prog).rjust(3, ' ') +",
"button\" def get_confirmation_msg(self): if self.prefs.FEATURE_demo: return 'WARNING: in the demo mode only the",
"def process_result(self): if self.prefs.FEATURE_demo: return if self.pack_solution_msg is None: self.raiseUnexpectedOutputError() pack_solution = read_pack_solution(self.pack_solution_msg)",
"selected UV islands overlap each other' def process_result(self): if self.island_flags_msg is None: self.raiseUnexpectedOutputError()",
"bl_label = 'Select Similar' bl_description = \"Selects all islands which have similar shape",
"def __init__(self): self.cancel_sig_sent = False self.area = None def get_confirmation_msg(self): if platform.system() ==",
"class UVP2_OT_SelectSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_select_similar' bl_label = 'Select Similar' bl_description = \"Selects all",
"= 10.0 # Start progress monitor thread self.progress_queue = queue.Queue() self.connection_thread = threading.Thread(target=connection_thread_func,",
"check_uvp_retcode(self, retcode): self.prefs.uvp_retcode = retcode if retcode in {UvPackerErrorCode.SUCCESS, UvPackerErrorCode.INVALID_ISLANDS, UvPackerErrorCode.NO_SPACE, UvPackerErrorCode.PRE_VALIDATION_FAILED}: return",
"else None if active_dev is not None and active_dev.id.startswith('cuda'): return UvpLabels.CUDA_MACOS_CONFIRM_MSG if self.prefs.pack_groups_together(self.scene_props)",
"of invalid faces found: ' + str(invalid_face_count)) else: self.set_status('INFO', 'No invalid faces found')",
"if self.area is not None: op_status += ', packed islands area: ' +",
"to cancel) ' return header_str + iter_str + time_left_str + progress_str + end_str",
"header_str = 'Pixel margin adjustment. ' elif self.prefs.heuristic_enabled(self.scene_props): header_str = 'Current area: {}.",
"else None if active_dev is None: raise RuntimeError('Could not find a packing device')",
"= \"Show help for handling invalid topology errors\" URL_SUFFIX = \"invalid-topology-issues\" class UVP2_OT_PixelMarginHelp(UVP2_OT_Help):",
"return prefs.uvp_initialized and context.active_object is not None and context.active_object.mode == 'EDIT' def check_uvp_retcode(self,",
"if self.confirmation_msg != '': pix_per_char = 5 dialog_width = pix_per_char * len(self.confirmation_msg) +",
"= 'uvpackmaster2.uv_nonsquare_packing_help' bl_description = \"Show help for non-square packing\" URL_SUFFIX = \"non-square-packing\" class",
"= 'Validate selected UV faces. The validation procedure looks for invalid UV faces",
"finish_after_op_done(self): return True def handle_op_done(self): self.op_done = True send_finish_confirmation(self.uvp_proc) try: self.uvp_proc.wait(5) except: raise",
"UvPackingPhaseCode.INITIALIZATION: return 'Initialization (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_ANALYSIS: return \"Topology",
"{}. '.format(self.progress_iter_done) else: iter_str = '' if self.progress_sec_left >= 0: time_left_str = \"Time",
"group by similarity\") if self.scene_props.prerot_disable: raise RuntimeError(\"'Pre-Rotation Disable' option must be off in",
"def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return (ratio, 1.0) class UVP2_OT_Help(bpy.types.Operator): bl_label = 'Help'",
"detected') def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.OVERLAP_CHECK)] return uvp_args class",
"uvp_args += ['-w'] else: rot_step_value = -1 uvp_args += ['-r', str(rot_step_value)] if self.prefs.heuristic_enabled(self.scene_props):",
"UVP2_OT_AlignSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_align_similar' bl_label = 'Align Similar' bl_description = \"Align selected islands,",
"islands are again suitable for packing into a square texture. For for info",
"ratio = get_active_image_ratio(self.p_context.context) return (ratio, 1.0) class UVP2_OT_Help(bpy.types.Operator): bl_label = 'Help' def execute(self,",
"if self.curr_phase == UvPackingPhaseCode.INITIALIZATION: return 'Initialization (press ESC to cancel)' if self.curr_phase ==",
"engine edition') # Validate pack mode pack_mode = UvPackingMode.get_mode(self.scene_props.pack_mode) if pack_mode.req_feature != ''",
"bl_label = 'Invalid Topology Help' bl_idname = 'uvpackmaster2.uv_invalid_topology_help' bl_description = \"Show help for",
"ESC to cancel)\".format(self.progress_array[0]) raise RuntimeError('Unexpected packing phase encountered') def handle_uvp_msg_spec(self, msg_code, msg): return",
"['-o', str(UvPackerOpcode.PACK), '-i', str(self.scene_props.precision), '-m', str(self.scene_props.margin)] uvp_args += ['-d', self.prefs.dev_array[self.prefs.sel_dev_idx].id] if self.prefs.pixel_margin_enabled(self.scene_props): uvp_args",
"= force_read_int(self.invalid_islands_msg) invalid_islands = read_int_array(self.invalid_islands_msg) if len(invalid_islands) == 0: self.raiseUnexpectedOutputError() self.p_context.handle_invalid_islands(invalid_islands) if code",
"if not check_uvp(): unregister_uvp() redraw_ui(context) raise RuntimeError(\"UVP engine broken\") reset_stats(self.prefs) self.p_context = PackContext(context)",
"Help' bl_idname = 'uvpackmaster2.uv_uvp_setup_help' bl_description = \"Show help for UVP setup\" URL_SUFFIX =",
"may solve the problem (if used in the operation).\") if outside_detected: self.add_warning(\"Some islands",
"['-q', str(self.pack_ratio)] return uvp_args class UVP2_OT_SelectSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_select_similar' bl_label = 'Select Similar'",
"self.scene_props = context.scene.uvp2_props self.confirmation_msg = self.get_confirmation_msg() wm = context.window_manager if self.confirmation_msg != '':",
"= 'Align Similar' bl_description = \"Align selected islands, so islands which are similar",
"in the operation).\") if outside_detected: self.add_warning(\"Some islands are outside their packing box after",
"{UvPackerErrorCode.SUCCESS, UvPackerErrorCode.INVALID_ISLANDS, UvPackerErrorCode.NO_SPACE, UvPackerErrorCode.PRE_VALIDATION_FAILED}: return if retcode == UvPackerErrorCode.CANCELLED: raise OpCancelledException() if retcode",
"RuntimeError('Unexpected grouping requested') def send_rot_step(self): return False def lock_groups_enabled(self): return False def send_verts_3d(self):",
"except OpAbortedException: self.set_status('INFO', 'Packer process killed') cancel = True except OpCancelledException: self.set_status('INFO', 'Operation",
"Support Help' bl_idname = 'uvpackmaster2.uv_udim_support_help' bl_description = \"Show help for UDIM support\" URL_SUFFIX",
".connection import * from .prefs import * from .os_iface import * from .island_params",
"+= ['-S', str(self.prefs.seed)] if self.prefs.wait_for_debugger: uvp_args_final.append('-G') uvp_args_final += ['-T', str(self.prefs.test_param)] print('Pakcer args: '",
"return 'Initialization (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_ANALYSIS: return \"Topology analysis:",
"self.curr_phase = force_read_int(msg) progress_size = force_read_int(msg) if progress_size > len(self.progress_array): self.progress_array = [0]",
"= \"non-square-packing\" class UVP2_OT_SimilarityDetectionHelp(UVP2_OT_Help): bl_label = 'Similarity Detection Help' bl_idname = 'uvpackmaster2.uv_similarity_detection_help' bl_description",
"if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) if self.pack_ratio != 1.0: uvp_args += ['-q', str(self.pack_ratio)]",
"self.hang_detected = False self.hang_timeout = 10.0 # Start progress monitor thread self.progress_queue =",
"ex: break if isinstance(item, str): raise RuntimeError(item) elif isinstance(item, io.BytesIO): self.handle_uvp_msg(item) else: raise",
"with area close to 0, self-intersecting faces, faces overlapping each other' def get_confirmation_msg(self):",
"raise NoUvFaceError('No UV face selected') else: if selected_cnt + unselected_cnt == 0: raise",
"code if event.type == 'ESC': raise OpCancelledException() elif event.type == 'TIMER': self.handle_communication() def",
"self.set_status('INFO', 'Islands area: ' + str(area)) def validate_pack_params(self): pass def get_uvp_args(self): uvp_args =",
"panel to learn more\" elif code == UvInvalidIslandCode.INT_PARAM: param_array = IslandParamInfo.get_param_info_array() error_msg =",
"self.prefs.pixel_padding_enabled(self.scene_props): uvp_args += ['-N', str(self.scene_props.pixel_padding)] uvp_args += ['-W', self.scene_props.pixel_margin_method] uvp_args += ['-Y', str(self.scene_props.pixel_margin_adjust_time)]",
"info regarding non-square packing read the documentation\" def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return",
"with inconsistent {} values found in the selected islands\".format(param_array[subcode].NAME) else: self.raiseUnexpectedOutputError() raise InvalidIslandsError(error_msg)",
"= os_uvp_creation_flags() popen_args = dict() if creation_flags is not None: popen_args['creationflags'] = creation_flags",
"str(self.scene_props.margin)] uvp_args += ['-d', self.prefs.dev_array[self.prefs.sel_dev_idx].id] if self.prefs.pixel_margin_enabled(self.scene_props): uvp_args += ['-M', str(self.scene_props.pixel_margin)] uvp_args +=",
"on top of each other. For more info regarding similarity detection click the",
"(to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.EXTERNAL) send_lock_groups = self.lock_groups_enabled() send_verts_3d = self.send_verts_3d() selected_cnt, unselected_cnt = self.p_context.serialize_uv_maps(send_unselected,",
"msg_code == UvPackMessageCode.SIMILAR_ISLANDS: if self.similar_islands_msg is not None: self.raiseUnexpectedOutputError() self.similar_islands_msg = msg elif",
"in similar_islands: self.p_context.select_island_faces(island_idx, self.p_context.uv_island_faces_list[island_idx], True) else: if len(similar_islands) > 0: self.raiseUnexpectedOutputError() self.set_status('INFO', 'Similar",
"as ex: self.set_status('WARNING', str(ex)) cancel = True except RuntimeError as ex: if in_debug_mode():",
"return {'RUNNING_MODAL'} class FakeTimerEvent: def __init__(self): self.type = 'TIMER' self.value = 'NOTHING' self.ctrl",
"== UvPackerErrorCode.CANCELLED: raise OpCancelledException() if retcode == UvPackerErrorCode.NO_VALID_STATIC_ISLAND: raise RuntimeError(\"'Pack To Others' option",
"elif msg_code == UvPackMessageCode.AREA: if self.area_msg is not None: self.raiseUnexpectedOutputError() self.area_msg = msg",
"to finish' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_VALIDATION: return \"Topology validation: {:3}% (press ESC to",
"grouping by similarity\") if not self.scene_props.rot_enable: raise RuntimeError(\"Island rotations must be enabled in",
"to continue' return '' def send_unselected_islands(self): return True def get_uvp_opcode(self): return UvPackerOpcode.SELECT_SIMILAR def",
"require_selection(self): return True def finish_after_op_done(self): return True def handle_op_done(self): self.op_done = True send_finish_confirmation(self.uvp_proc)",
"ratio = get_active_image_ratio(self.p_context.context) self.p_context.scale_selected_faces(self.get_scale_factors()) except RuntimeError as ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, str(ex))",
"= self.prefs.target_box(self.scene_props) if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) if self.pack_ratio != 1.0: uvp_args +=",
"+= ['-B', self.get_target_box_string(self.target_box)] uvp_args.append('-b') return uvp_args class UVP2_OT_OverlapCheckOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_overlap_check' bl_label =",
"self.curr_phase = UvPackingPhaseCode.INITIALIZATION self.invalid_islands_msg = None self.island_flags_msg = None self.pack_solution_msg = None self.area_msg",
"= UvPackingMode.get_mode(self.scene_props.pack_mode) if pack_mode.req_feature != '' and not getattr(self.prefs, 'FEATURE_' + pack_mode.req_feature): raise",
"+= ['-M', str(self.scene_props.pixel_margin)] uvp_args += ['-y', str(self.prefs.pixel_margin_tex_size(self.scene_props, self.p_context.context))] if self.prefs.pixel_padding_enabled(self.scene_props): uvp_args += ['-N',",
"a non-square texture. For for info regarding non-square packing click the help icon\"",
"is not None: # It should not be required to but check once",
"self.process_invalid_islands() self.process_result() if self.finish_after_op_done(): raise OpFinishedException() def finish(self, context): self.exit_common() return {'FINISHED', 'PASS_THROUGH'}",
"= '(press ESC to apply result) ' else: end_str = '(press ESC to",
"+= ['-r', str(90)] if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) uvp_args += ['-q', str(self.pack_ratio)] return",
"check in progress (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.AREA_MEASUREMENT: return 'Area",
"done' if self.area is not None: op_status += ', packed islands area: '",
"'-j', str(self.scene_props.heuristic_max_wait_time)] if self.prefs.FEATURE_advanced_heuristic and self.scene_props.advanced_heuristic: uvp_args.append('-H') uvp_args += ['-g', self.scene_props.pack_mode] tile_count, tiles_in_row",
"50 return wm.invoke_props_dialog(self, width=dialog_width) return self.execute(context) def draw(self, context): layout = self.layout col",
"if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', 'Unexpected error') cancel = True if self.p_context is not",
"None: self.uvp_proc.terminate() self.report_status() return {'FINISHED'} if self.interactive: wm = context.window_manager self._timer = wm.event_timer_add(self.MODAL_INTERVAL_S,",
"UvPackingMode.get_mode(self.scene_props.pack_mode) if pack_mode.req_feature != '' and not getattr(self.prefs, 'FEATURE_' + pack_mode.req_feature): raise RuntimeError('Selected",
"UvPackMessageCode.PROGRESS_REPORT: self.curr_phase = force_read_int(msg) progress_size = force_read_int(msg) if progress_size > len(self.progress_array): self.progress_array =",
"'Overlap check in progress (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.AREA_MEASUREMENT: return",
"= context.scene.uvp2_props self.confirmation_msg = self.get_confirmation_msg() wm = context.window_manager if self.confirmation_msg != '': pix_per_char",
"['-h', str(self.scene_props.heuristic_search_time), '-j', str(self.scene_props.heuristic_max_wait_time)] if self.prefs.FEATURE_advanced_heuristic and self.scene_props.advanced_heuristic: uvp_args.append('-H') uvp_args += ['-g', self.scene_props.pack_mode]",
"to cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.OVERLAP_CHECK: return 'Overlap check in progress (press ESC",
"self.op_done and self.uvp_proc.poll() is not None: # It should not be required to",
"MODAL_INTERVAL_S = 0.1 interactive = False @classmethod def poll(cls, context): prefs = get_prefs()",
"in order to group by similarity\") if self.scene_props.prerot_disable: raise RuntimeError(\"'Pre-Rotation Disable' option must",
"encountered in the selected islands. Check the Help panel to learn more\" elif",
"in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, 'Unexpected error') self.p_context.update_meshes() return {'FINISHED'} def get_scale_factors(self): return (1.0, 1.0)",
"creation_flags self.uvp_proc = subprocess.Popen(uvp_args_final, stdin=subprocess.PIPE, stdout=subprocess.PIPE, **popen_args) out_stream = self.uvp_proc.stdin out_stream.write(self.p_context.serialized_maps) out_stream.flush() self.start_time",
"= force_read_int(msg) progress_size = force_read_int(msg) if progress_size > len(self.progress_array): self.progress_array = [0] *",
"detected after packing (check the selected islands). Consider increasing the 'Precision' parameter. Sometimes",
"the help icon\" def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return (1.0 / ratio, 1.0)",
"return if msg_code == UvPackMessageCode.PROGRESS_REPORT: self.curr_phase = force_read_int(msg) progress_size = force_read_int(msg) if progress_size",
"is not None: self.target_box[0].x *= self.pack_ratio self.target_box[1].x *= self.pack_ratio else: self.target_box = (Vector((0.0,",
"islands area: ' + str(self.area) self.set_status('INFO', op_status) if overlap_detected: self.add_warning(\"Overlapping islands were detected",
"overlap_detected: self.add_warning(\"Overlapping islands were detected after packing (check the selected islands). Consider increasing",
"UV faces i.e. faces with area close to 0, self-intersecting faces, faces overlapping",
"self.grouping_enabled(): if self.get_group_method() == UvGroupingMethod.SIMILARITY.code: if self.prefs.pack_to_others_enabled(self.scene_props): raise RuntimeError(\"'Pack To Others' is not",
"not self.p_context.islands_received(): self.raiseUnexpectedOutputError() self.process_invalid_islands() self.process_result() if self.finish_after_op_done(): raise OpFinishedException() def finish(self, context): self.exit_common()",
"it will be useful, # but WITHOUT ANY WARRANTY; without even the implied",
"not self.prefs.FEATURE_demo: if self.island_flags_msg is None: self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg) overlap_detected, outside_detected =",
"def process_result(self): if self.invalid_faces_msg is None: self.raiseUnexpectedOutputError() invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces = read_int_array(self.invalid_faces_msg)",
"similarity\") if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: validate_target_box(self.scene_props) def get_target_box_string(self, target_box): prec = 4 return",
"in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', 'Unexpected error') cancel = True if cancel: return self.cancel(context) return",
"None: self.raiseUnexpectedOutputError() self.pack_solution_msg = msg elif msg_code == UvPackMessageCode.AREA: if self.area_msg is not",
"['-Y', str(self.scene_props.pixel_margin_adjust_time)] if self.prefs.fixed_scale_enabled(self.scene_props): uvp_args += ['-O'] uvp_args += ['-F', self.scene_props.fixed_scale_strategy] if self.prefs.FEATURE_island_rotation:",
"progress_msg_spec = self.get_progress_msg_spec() if progress_msg_spec: return progress_msg_spec if self.curr_phase == UvPackingPhaseCode.INITIALIZATION: return 'Initialization",
"get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.VALIDATE_UVS)] return uvp_args class UVP2_OT_ProcessSimilar(UVP2_OT_PackOperatorGeneric): def validate_pack_params(self): pass def",
"context): try: self.p_context = PackContext(context) ratio = get_active_image_ratio(self.p_context.context) self.p_context.scale_selected_faces(self.get_scale_factors()) except RuntimeError as ex:",
"False try: try: self.handle_event(event) # Check whether the uvp process is alive if",
"= self.p_context.context.window_manager wm.event_timer_remove(self._timer) self.p_context.update_meshes() self.report_status() if in_debug_mode(): print('UVP operation time: ' + str(time.time()",
"islands (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_ALIGNING: return 'Similar islands aligning",
"box\") if retcode == UvPackerErrorCode.MAX_GROUP_COUNT_EXCEEDED: raise RuntimeError(\"Maximal group count exceeded\") if retcode ==",
"icon\" def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return (1.0 / ratio, 1.0) class UVP2_OT_UndoIslandsAdjustemntToTexture(UVP2_OT_ScaleIslands):",
"msg elif msg_code == UvPackMessageCode.INVALID_FACES: if self.invalid_faces_msg is not None: self.raiseUnexpectedOutputError() self.invalid_faces_msg =",
"def get_confirmation_msg(self): if self.prefs.FEATURE_demo: return 'WARNING: in the demo mode only the number",
"window to finish' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_VALIDATION: return \"Topology validation: {:3}% (press ESC",
"pixels\" URL_SUFFIX = \"pixel-margin\" class UVP2_OT_IslandRotStepHelp(UVP2_OT_Help): bl_label = 'Island Rotation Step Help' bl_idname",
"be required to but check once again to be on the safe side",
"if not self.prefs.FEATURE_demo: if self.island_flags_msg is None: self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg) overlap_detected, outside_detected",
"groups together\") raise RuntimeError('Pack process returned an error') def raiseUnexpectedOutputError(self): raise RuntimeError('Unexpected output",
"self.p_context.context.window_manager wm.event_timer_remove(self._timer) self.p_context.update_meshes() self.report_status() if in_debug_mode(): print('UVP operation time: ' + str(time.time() -",
"area self.set_status('INFO', 'Islands area: ' + str(area)) def validate_pack_params(self): pass def get_uvp_args(self): uvp_args",
"if self.prefs.FEATURE_demo: return 'WARNING: in the demo mode only the number of invalid",
"for packing into a square texture. For for info regarding non-square packing read",
"import subprocess import queue import threading import signal import webbrowser from .utils import",
"island_flags = read_int_array(self.island_flags_msg) overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags) if self.area is not None: self.prefs.stats_area",
"False else: if self.curr_phase != UvPackingPhaseCode.RENDER_PRESENTATION and curr_time - self.last_msg_time > self.hang_timeout: self.hang_detected",
"if self.p_context.context.tool_settings.use_uv_select_sync: self.p_context.context.tool_settings.mesh_select_mode = (False, False, True) else: self.p_context.context.tool_settings.uv_select_mode = 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces),",
"are again suitable for packing into a square texture. For for info regarding",
"UVP2_OT_IslandRotStepHelp(UVP2_OT_Help): bl_label = 'Island Rotation Step Help' bl_idname = 'uvpackmaster2.uv_island_rot_step_help' bl_description = \"Show",
"# It should not be required to but check once again to be",
"UVP2_OT_PackOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_pack' bl_label = 'Pack' bl_description = 'Pack selected UV islands'",
"None: self.raiseUnexpectedOutputError() self.invalid_islands_msg = msg elif msg_code == UvPackMessageCode.ISLAND_FLAGS: if self.island_flags_msg is not",
"send_verts_3d, self.get_group_method() if send_groups else None) if self.require_selection(): if selected_cnt == 0: raise",
"status_type self.op_status = status def add_warning(self, warn_msg): self.op_warnings.append(warn_msg) def report_status(self): if self.op_status is",
"to cancel)' if self.curr_phase == UvPackingPhaseCode.RENDER_PRESENTATION: return 'Close the demo window to finish'",
"+ str(invalid_face_count) + '. Packing aborted') return if not self.prefs.FEATURE_demo: if self.island_flags_msg is",
"the # GNU General Public License for more details. # # You should",
"= False outside_detected = False if self.invalid_faces_msg is not None: invalid_face_count = force_read_int(self.invalid_faces_msg)",
"True) else: self.p_context.context.tool_settings.uv_select_mode = 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) if invalid_face_count > 0: self.set_status('WARNING',",
"= (Vector((0.0, 0.0)), Vector((self.pack_ratio, 1.0))) if self.target_box is not None: uvp_args += ['-B',",
"self.cancel_sig_sent: self.uvp_proc.send_signal(os_cancel_sig()) self.cancel_sig_sent = True return True return False def process_result(self): overlap_detected =",
"found in the selected islands\".format(param_array[subcode].NAME) else: self.raiseUnexpectedOutputError() raise InvalidIslandsError(error_msg) def require_selection(self): return True",
"only the number of similar islands found is reported, islands will not be",
"self.prefs.heuristic_enabled(self.scene_props): header_str = 'Current area: {}. '.format(self.area if self.area is not None else",
"self.curr_phase == UvPackingPhaseCode.TOPOLOGY_ANALYSIS: return \"Topology analysis: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase",
"= new_progress_msg self.report({'INFO'}, self.progress_msg) def handle_uvp_msg(self, msg): msg_code = force_read_int(msg) if self.handle_uvp_msg_spec(msg_code, msg):",
"read_islands(self, islands_msg): islands = [] island_cnt = force_read_int(islands_msg) selected_cnt = force_read_int(islands_msg) for i",
"self.islands_metadata_msg is not None: self.raiseUnexpectedOutputError() self.islands_metadata_msg = msg else: self.raiseUnexpectedOutputError() def handle_communication(self): if",
"self.scene_props.prerot_disable: raise RuntimeError(\"'Pre-Rotation Disable' option must be off in order to group by",
"['-N', str(self.scene_props.pixel_padding)] uvp_args += ['-W', self.scene_props.pixel_margin_method] uvp_args += ['-Y', str(self.scene_props.pixel_margin_adjust_time)] if self.prefs.fixed_scale_enabled(self.scene_props): uvp_args",
"if not self.op_done and self.uvp_proc.poll() is not None: # It should not be",
"return UvPackerOpcode.SELECT_SIMILAR def process_result(self): if self.similar_islands_msg is None: self.raiseUnexpectedOutputError() similar_island_count = force_read_int(self.similar_islands_msg) similar_islands",
"elif event.type == 'TIMER': self.handle_communication() def modal(self, context, event): cancel = False finish",
"faces with area close to 0, self-intersecting faces, faces overlapping each other' def",
"(False, False, True) else: self.p_context.context.tool_settings.uv_select_mode = 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) if invalid_face_count >",
"= status_type self.op_status = status def add_warning(self, warn_msg): self.op_warnings.append(warn_msg) def report_status(self): if self.op_status",
"ret = self.modal(context, event) if ret.intersection({'FINISHED', 'CANCELLED'}): return ret time.sleep(self.MODAL_INTERVAL_S) def invoke(self, context,",
"not None: # It should not be required to but check once again",
"should finish if self.curr_phase == UvPackingPhaseCode.DONE: self.handle_op_done() elif msg_code == UvPackMessageCode.INVALID_ISLANDS: if self.invalid_islands_msg",
"the operation).\") if outside_detected: self.add_warning(\"Some islands are outside their packing box after packing",
"wm = self.p_context.context.window_manager wm.event_timer_remove(self._timer) self.p_context.update_meshes() self.report_status() if in_debug_mode(): print('UVP operation time: ' +",
"force_read_int(msg) progress_size = force_read_int(msg) if progress_size > len(self.progress_array): self.progress_array = [0] * (progress_size)",
"the selected islands\".format(param_array[subcode].NAME) else: self.raiseUnexpectedOutputError() raise InvalidIslandsError(error_msg) def require_selection(self): return True def finish_after_op_done(self):",
"return False def handle_uvp_msg_spec(self, msg_code, msg): if msg_code == UvPackMessageCode.AREA: self.area = self.read_area(msg)",
"'-i', str(self.scene_props.precision), '-m', str(self.scene_props.margin)] uvp_args += ['-d', self.prefs.dev_array[self.prefs.sel_dev_idx].id] if self.prefs.pixel_margin_enabled(self.scene_props): uvp_args += ['-M',",
"return {'FINISHED'} def get_scale_factors(self): return (1.0, 1.0) class UVP2_OT_AdjustIslandsToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_adjust_islands_to_texture' bl_label",
"islands.append(read_int_array(islands_msg)) self.p_context.set_islands(selected_cnt, islands) def process_invalid_islands(self): if self.uvp_proc.returncode != UvPackerErrorCode.INVALID_ISLANDS: return if self.invalid_islands_msg is",
"= self.layout col = layout.column() col.label(text=self.confirmation_msg) def get_confirmation_msg(self): return '' def send_unselected_islands(self): return",
"the documentation\" def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return (ratio, 1.0) class UVP2_OT_Help(bpy.types.Operator): bl_label",
"self.target_box is not None: self.target_box[0].x *= self.pack_ratio self.target_box[1].x *= self.pack_ratio else: self.target_box =",
"prec = 4 return \"{}:{}:{}:{}\".format( round(target_box[0].x, prec), round(target_box[0].y, prec), round(target_box[1].x, prec), round(target_box[1].y, prec))",
".labels import UvpLabels from .register import check_uvp, unregister_uvp import bmesh import bpy import",
"str(self.scene_props.pixel_margin)] uvp_args += ['-y', str(self.prefs.pixel_margin_tex_size(self.scene_props, self.p_context.context))] if self.prefs.pixel_padding_enabled(self.scene_props): uvp_args += ['-N', str(self.scene_props.pixel_padding)] uvp_args",
"class UVP2_OT_PixelMarginHelp(UVP2_OT_Help): bl_label = 'Pixel Margin Help' bl_idname = 'uvpackmaster2.uv_pixel_margin_help' bl_description = \"Show",
"rot_step_value = self.scene_props.rot_step if self.scene_props.prerot_disable: uvp_args += ['-w'] else: rot_step_value = -1 uvp_args",
"level\" URL_SUFFIX = \"island-rotation-step\" class UVP2_OT_UdimSupportHelp(UVP2_OT_Help): bl_label = 'UDIM Support Help' bl_idname =",
"not None: invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces = read_int_array(self.invalid_faces_msg) if not self.prefs.FEATURE_demo: if len(invalid_faces)",
"raise InvalidIslandsError(error_msg) def require_selection(self): return True def finish_after_op_done(self): return True def handle_op_done(self): self.op_done",
"RuntimeError('Selected packing device is not supported in this engine edition') # Validate pack",
"if self.pack_solution_msg is not None: self.raiseUnexpectedOutputError() self.pack_solution_msg = msg elif msg_code == UvPackMessageCode.AREA:",
"except Exception as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', 'Unexpected error') cancel = True",
"if not, write to the Free Software Foundation, # Inc., 51 Franklin Street,",
"of each other. For more info regarding similarity detection click the help button\"",
"the uvp process is alive if not self.op_done and self.uvp_proc.poll() is not None:",
"on the safe side self.handle_communication() if not self.op_done: # Special value indicating a",
"def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.MEASURE_AREA)] return uvp_args class UVP2_OT_ValidateOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_validate'",
"context): webbrowser.open(UvpLabels.HELP_BASEURL + self.URL_SUFFIX) return {'FINISHED'} class UVP2_OT_UvpSetupHelp(UVP2_OT_Help): bl_label = 'UVP Setup Help'",
"scale of selected islands so they are suitable for packing into the active",
"return if self.pack_solution_msg is None: self.raiseUnexpectedOutputError() pack_solution = read_pack_solution(self.pack_solution_msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) self.set_status('INFO', 'Islands",
"uvp_args_final += ['-T', str(self.prefs.test_param)] print('Pakcer args: ' + ' '.join(x for x in",
"of the License, or (at your option) any later version. # # This",
"= None self.pack_solution_msg = None self.area_msg = None self.invalid_faces_msg = None self.similar_islands_msg =",
"== 'INFO': op_status_type = 'WARNING' op_status += '. (WARNINGS were reported - check",
"detected if self.hang_detected and event.type == 'ESC': raise OpAbortedException() if self.handle_event_spec(event): return #",
"True elif msg_code == UvPackMessageCode.PACK_SOLUTION: pack_solution = read_pack_solution(msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) return True elif",
"self.prefs.FEATURE_demo: return if self.pack_solution_msg is None: self.raiseUnexpectedOutputError() pack_solution = read_pack_solution(self.pack_solution_msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) self.set_status('INFO',",
"bl_idname = 'uvpackmaster2.uv_uvp_setup_help' bl_description = \"Show help for UVP setup\" URL_SUFFIX = \"uvp-setup\"",
"regarding similarity detection click the help button\" def get_uvp_opcode(self): return UvPackerOpcode.ALIGN_SIMILAR def process_result(self):",
"get_progress_msg_spec(self): return False def get_progress_msg(self): if self.hang_detected: return 'Packer process not responding for",
"self.raiseUnexpectedOutputError() self.island_flags_msg = msg elif msg_code == UvPackMessageCode.PACK_SOLUTION: if self.pack_solution_msg is not None:",
"the islands which were packed\") else: op_status = 'Packing done' if self.area is",
"if self.p_context is not None: self.p_context.update_meshes() if cancel: if self.uvp_proc is not None:",
"= False self.uvp_proc = None self.prefs = get_prefs() self.scene_props = context.scene.uvp2_props self.p_context =",
"code == UvInvalidIslandCode.INT_PARAM: param_array = IslandParamInfo.get_param_info_array() error_msg = \"Faces with inconsistent {} values",
"self.report_status() if in_debug_mode(): print('UVP operation time: ' + str(time.time() - self.start_time)) def read_islands(self,",
"str(UvPackerOpcode.VALIDATE_UVS)] return uvp_args class UVP2_OT_ProcessSimilar(UVP2_OT_PackOperatorGeneric): def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o',",
"if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', str(ex)) cancel = True except Exception as ex: if",
"bl_idname = 'uvpackmaster2.uv_measure_area' bl_label = 'Measure Area' bl_description = 'Measure area of selected",
"execute(self, context): try: self.p_context = PackContext(context) ratio = get_active_image_ratio(self.p_context.context) self.p_context.scale_selected_faces(self.get_scale_factors()) except RuntimeError as",
"BLOCK ##### # # This program is free software; you can redistribute it",
"== UvInvalidIslandCode.TOPOLOGY: error_msg = \"Invalid topology encountered in the selected islands. Check the",
"self.send_rot_step() send_groups = self.grouping_enabled() and (to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.EXTERNAL) send_lock_groups = self.lock_groups_enabled() send_verts_3d =",
"'Packer process not responding for a longer time (press ESC to abort)' if",
"self.island_flags_msg = msg elif msg_code == UvPackMessageCode.PACK_SOLUTION: if self.pack_solution_msg is not None: self.raiseUnexpectedOutputError()",
"PARTICULAR PURPOSE. See the # GNU General Public License for more details. #",
"status def add_warning(self, warn_msg): self.op_warnings.append(warn_msg) def report_status(self): if self.op_status is not None: self.prefs['op_status']",
"context): cancel = False self.op_done = False self.uvp_proc = None self.prefs = get_prefs()",
"'' self.progress_sec_left = -1 self.progress_iter_done = -1 self.progress_last_update_time = 0.0 self.curr_phase = UvPackingPhaseCode.INITIALIZATION",
"raise RuntimeError('Unexpected grouping requested') def send_rot_step(self): return False def lock_groups_enabled(self): return False def",
"# Kill the UVP process unconditionally if a hang was detected if self.hang_detected",
"uvp_args = ['-o', str(UvPackerOpcode.OVERLAP_CHECK)] return uvp_args class UVP2_OT_MeasureAreaOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_measure_area' bl_label =",
"Help' bl_idname = 'uvpackmaster2.uv_invalid_topology_help' bl_description = \"Show help for handling invalid topology errors\"",
"None self.island_flags_msg = None self.pack_solution_msg = None self.area_msg = None self.invalid_faces_msg = None",
"self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None if active_dev is not None and",
"is not None and context.active_object.mode == 'EDIT' def check_uvp_retcode(self, retcode): self.prefs.uvp_retcode = retcode",
"self.handle_event(event) # Check whether the uvp process is alive if not self.op_done and",
"'uvpackmaster2.uv_heuristic_search_help' bl_description = \"Show help for heuristic search\" URL_SUFFIX = \"heuristic-search\" class UVP2_OT_NonSquarePackingHelp(UVP2_OT_Help):",
"len(self.progress_array): self.progress_array = [0] * (progress_size) for i in range(progress_size): self.progress_array[i] = force_read_int(msg)",
"Area' bl_description = 'Measure area of selected UV islands' def process_result(self): if self.area_msg",
"if self.similar_islands_msg is not None: self.raiseUnexpectedOutputError() self.similar_islands_msg = msg elif msg_code == UvPackMessageCode.ISLANDS:",
"redraw_ui(context) raise RuntimeError(\"UVP engine broken\") reset_stats(self.prefs) self.p_context = PackContext(context) self.pre_op_initialize() send_unselected = self.send_unselected_islands()",
"similar_islands = read_int_array(self.similar_islands_msg) if not self.prefs.FEATURE_demo: if len(similar_islands) != similar_island_count: self.raiseUnexpectedOutputError() for island_idx",
"by similarity\") if not self.scene_props.rot_enable: raise RuntimeError(\"Island rotations must be enabled in order",
"must be off in order to group by similarity\") if self.prefs.FEATURE_target_box and self.prefs.target_box_enable:",
"'' def send_unselected_islands(self): return self.prefs.pack_to_others_enabled(self.scene_props) def grouping_enabled(self): return self.prefs.grouping_enabled(self.scene_props) def get_group_method(self): return self.scene_props.group_method",
"button\" def get_uvp_opcode(self): return UvPackerOpcode.ALIGN_SIMILAR def process_result(self): if self.prefs.FEATURE_demo: return if self.pack_solution_msg is",
"== UvPackingPhaseCode.OVERLAP_CHECK: return 'Overlap check in progress (press ESC to cancel)' if self.curr_phase",
"setting rotation step on per-island level\" URL_SUFFIX = \"island-rotation-step\" class UVP2_OT_UdimSupportHelp(UVP2_OT_Help): bl_label =",
"self.raiseUnexpectedOutputError() self.p_context.handle_invalid_islands(invalid_islands) if code == UvInvalidIslandCode.TOPOLOGY: error_msg = \"Invalid topology encountered in the",
"uvp_args class UVP2_OT_MeasureAreaOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_measure_area' bl_label = 'Measure Area' bl_description = 'Measure",
"ratio = get_active_image_ratio(self.p_context.context) return (1.0 / ratio, 1.0) class UVP2_OT_UndoIslandsAdjustemntToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_undo_islands_adjustment_to_texture'",
"= context.window_manager if self.confirmation_msg != '': pix_per_char = 5 dialog_width = pix_per_char *",
"NoUvFaceError('No UV face visible') self.validate_pack_params() if self.prefs.write_to_file: out_filepath = os.path.join(tempfile.gettempdir(), 'uv_islands.data') out_file =",
"True except InvalidIslandsError as err: self.set_status('ERROR', str(err)) cancel = True except RuntimeError as",
"isinstance(item, io.BytesIO): self.handle_uvp_msg(item) else: raise RuntimeError('Unexpected output from the connection thread') msg_received +=",
"elif isinstance(item, io.BytesIO): self.handle_uvp_msg(item) else: raise RuntimeError('Unexpected output from the connection thread') msg_received",
"done: {}. '.format(self.progress_iter_done) else: iter_str = '' if self.progress_sec_left >= 0: time_left_str =",
"OK to continue' return '' def send_unselected_islands(self): return True def get_uvp_opcode(self): return UvPackerOpcode.SELECT_SIMILAR",
"\"Per-face overlap check: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) raise RuntimeError('Unexpected packing phase encountered')",
"UvPackMessageCode.ISLANDS_METADATA: if self.islands_metadata_msg is not None: self.raiseUnexpectedOutputError() self.islands_metadata_msg = msg else: self.raiseUnexpectedOutputError() def",
"packing device is not supported in this engine edition') # Validate pack mode",
"to a non-square texture. For for info regarding non-square packing click the help",
"packing phase encountered') def handle_uvp_msg_spec(self, msg_code, msg): return False def handle_event_spec(self, event): return",
"except Exception as ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, 'Unexpected error') self.p_context.update_meshes() return {'FINISHED'}",
"selected_cnt = force_read_int(islands_msg) for i in range(island_cnt): islands.append(read_int_array(islands_msg)) self.p_context.set_islands(selected_cnt, islands) def process_invalid_islands(self): if",
"indicating a crash self.prefs.uvp_retcode = -1 raise RuntimeError('Packer process died unexpectedly') self.handle_progress_msg() except",
"self.op_done = True send_finish_confirmation(self.uvp_proc) try: self.uvp_proc.wait(5) except: raise RuntimeError('The UVP process wait timeout",
"send_rot_step = self.send_rot_step() send_groups = self.grouping_enabled() and (to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.EXTERNAL) send_lock_groups = self.lock_groups_enabled()",
"self.p_context.islands_received(): self.raiseUnexpectedOutputError() self.process_invalid_islands() self.process_result() if self.finish_after_op_done(): raise OpFinishedException() def finish(self, context): self.exit_common() return",
"self.raiseUnexpectedOutputError() def handle_communication(self): if self.op_done: return msg_received = 0 while True: try: item",
"class UVP2_OT_OverlapCheckOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_overlap_check' bl_label = 'Overlap Check' bl_description = 'Check wheter",
"self.add_warning(\"Overlap check was performed only on the islands which were packed\") else: op_status",
".island_params import * from .labels import UvpLabels from .register import check_uvp, unregister_uvp import",
"len(similar_islands) > 0: self.raiseUnexpectedOutputError() self.set_status('INFO', 'Similar islands found: ' + str(similar_island_count)) class UVP2_OT_AlignSimilar(UVP2_OT_ProcessSimilar):",
"self.op_done: return msg_received = 0 while True: try: item = self.progress_queue.get_nowait() except queue.Empty",
"context.scene.uvp2_props self.p_context = None self.pack_ratio = 1.0 self.target_box = None self.op_status_type = None",
"= self.op_warnings # self.prefs.stats_op_warnings.add(warning_msg) def exit_common(self): if self.interactive: wm = self.p_context.context.window_manager wm.event_timer_remove(self._timer) self.p_context.update_meshes()",
"= self.read_area(self.area_msg) self.prefs.stats_area = area self.set_status('INFO', 'Islands area: ' + str(area)) def validate_pack_params(self):",
"useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of #",
"out_filepath = os.path.join(tempfile.gettempdir(), 'uv_islands.data') out_file = open(out_filepath, 'wb') out_file.write(self.p_context.serialized_maps) out_file.close() uvp_args_final = [get_uvp_execpath(),",
"uvp_args += ['-Y', str(self.scene_props.pixel_margin_adjust_time)] if self.prefs.fixed_scale_enabled(self.scene_props): uvp_args += ['-O'] uvp_args += ['-F', self.scene_props.fixed_scale_strategy]",
"GNU General Public License # along with this program; if not, write to",
"validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.OVERLAP_CHECK)] return uvp_args class UVP2_OT_MeasureAreaOperator(UVP2_OT_PackOperatorGeneric): bl_idname",
"+= ['-R'] if self.lock_groups_enabled(): uvp_args_final += ['-Q'] if in_debug_mode(): if self.prefs.seed > 0:",
"'TIMER' self.value = 'NOTHING' self.ctrl = False while True: event = FakeTimerEvent() ret",
"def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(self.get_uvp_opcode()), '-I', str(self.scene_props.similarity_threshold)] uvp_args +=",
"> 0: if op_status_type == 'INFO': op_status_type = 'WARNING' op_status += '. (WARNINGS",
"None def get_confirmation_msg(self): if platform.system() == 'Darwin': active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx <",
"if self.prefs.pixel_margin_enabled(self.scene_props): uvp_args += ['-M', str(self.scene_props.pixel_margin)] uvp_args += ['-y', str(self.prefs.pixel_margin_tex_size(self.scene_props, self.p_context.context))] if self.prefs.pixel_padding_enabled(self.scene_props):",
"= 'UDIM Support Help' bl_idname = 'uvpackmaster2.uv_udim_support_help' bl_description = \"Show help for UDIM",
"found: ' + str(invalid_face_count)) else: self.set_status('INFO', 'No invalid faces found') def validate_pack_params(self): pass",
"wm.event_timer_add(self.MODAL_INTERVAL_S, window=context.window) wm.modal_handler_add(self) return {'RUNNING_MODAL'} class FakeTimerEvent: def __init__(self): self.type = 'TIMER' self.value",
"even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.",
"return {'FINISHED'} if self.interactive: wm = context.window_manager self._timer = wm.event_timer_add(self.MODAL_INTERVAL_S, window=context.window) wm.modal_handler_add(self) return",
"and self.prefs.target_box_enable: validate_target_box(self.scene_props) def get_target_box_string(self, target_box): prec = 4 return \"{}:{}:{}:{}\".format( round(target_box[0].x, prec),",
"'uvpackmaster2.uv_adjust_islands_to_texture' bl_label = 'Adjust Islands To Texture' bl_description = \"Adjust scale of selected",
"str(self.scene_props.similarity_threshold)] uvp_args += ['-i', str(self.scene_props.precision)] uvp_args += ['-r', str(90)] if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio =",
"None: end_str = '(press ESC to apply result) ' else: end_str = '(press",
"Time' may solve the problem (if used in the operation).\") if outside_detected: self.add_warning(\"Some",
"progress_size = force_read_int(msg) if progress_size > len(self.progress_array): self.progress_array = [0] * (progress_size) for",
"os.path.join(tempfile.gettempdir(), 'uv_islands.data') out_file = open(out_filepath, 'wb') out_file.write(self.p_context.serialized_maps) out_file.close() uvp_args_final = [get_uvp_execpath(), '-E', '-e',",
"Others' is not supported with grouping by similarity\") if not self.scene_props.rot_enable: raise RuntimeError(\"Island",
"IslandParamInfo.get_param_info_array() error_msg = \"Faces with inconsistent {} values found in the selected islands\".format(param_array[subcode].NAME)",
"if self.op_done: return msg_refresh_interval = 2.0 new_progress_msg = self.get_progress_msg() if not new_progress_msg: return",
"msg_code == UvPackMessageCode.ISLAND_FLAGS: if self.island_flags_msg is not None: self.raiseUnexpectedOutputError() self.island_flags_msg = msg elif",
"False def handle_progress_msg(self): if self.op_done: return msg_refresh_interval = 2.0 new_progress_msg = self.get_progress_msg() if",
"# # This program is distributed in the hope that it will be",
"0: iter_str = 'Iter. done: {}. '.format(self.progress_iter_done) else: iter_str = '' if self.progress_sec_left",
"str(rot_step_value)] if self.prefs.heuristic_enabled(self.scene_props): uvp_args += ['-h', str(self.scene_props.heuristic_search_time), '-j', str(self.scene_props.heuristic_max_wait_time)] if self.prefs.FEATURE_advanced_heuristic and self.scene_props.advanced_heuristic:",
"self.prefs.uvp_retcode = -1 raise RuntimeError('Packer process died unexpectedly') self.handle_progress_msg() except OpFinishedException: finish =",
"raise if finish: return self.finish(context) except OpAbortedException: self.set_status('INFO', 'Packer process killed') cancel =",
"the number of invalid faces found is reported, invalid faces will not be",
"str(time.time() - self.start_time)) def read_islands(self, islands_msg): islands = [] island_cnt = force_read_int(islands_msg) selected_cnt",
"{'FINISHED'} class UVP2_OT_UvpSetupHelp(UVP2_OT_Help): bl_label = 'UVP Setup Help' bl_idname = 'uvpackmaster2.uv_uvp_setup_help' bl_description =",
"'Validate UVs' bl_description = 'Validate selected UV faces. The validation procedure looks for",
"True except RuntimeError as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', str(ex)) cancel = True",
"+= ['-T', str(self.prefs.test_param)] print('Pakcer args: ' + ' '.join(x for x in uvp_args_final))",
"pack_mode = UvPackingMode.get_mode(self.scene_props.pack_mode) if pack_mode.req_feature != '' and not getattr(self.prefs, 'FEATURE_' + pack_mode.req_feature):",
"self.hang_detected = False else: if self.curr_phase != UvPackingPhaseCode.RENDER_PRESENTATION and curr_time - self.last_msg_time >",
"if self.finish_after_op_done(): raise OpFinishedException() def finish(self, context): self.exit_common() return {'FINISHED', 'PASS_THROUGH'} def cancel(self,",
"+= ['-F', self.scene_props.fixed_scale_strategy] if self.prefs.FEATURE_island_rotation: if self.scene_props.rot_enable: rot_step_value = self.scene_props.rot_step if self.scene_props.prerot_disable: uvp_args",
"class UVP2_OT_ManualGroupingHelp(UVP2_OT_Help): bl_label = 'Manual Grouping Help' bl_idname = 'uvpackmaster2.uv_manual_grouping_help' bl_description = \"Show",
"= \"Show help for setting rotation step on per-island level\" URL_SUFFIX = \"island-rotation-step\"",
"['-i', str(self.scene_props.precision)] uvp_args += ['-r', str(90)] if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) uvp_args +=",
"+ self.URL_SUFFIX) return {'FINISHED'} class UVP2_OT_UvpSetupHelp(UVP2_OT_Help): bl_label = 'UVP Setup Help' bl_idname =",
"{}. '.format(self.area if self.area is not None else 'none') else: header_str = ''",
"def process_result(self): if self.island_flags_msg is None: self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg) overlap_detected, outside_detected =",
"uvp_args = ['-o', str(UvPackerOpcode.VALIDATE_UVS)] return uvp_args class UVP2_OT_ProcessSimilar(UVP2_OT_PackOperatorGeneric): def validate_pack_params(self): pass def get_uvp_args(self):",
"class UVP2_OT_UvpSetupHelp(UVP2_OT_Help): bl_label = 'UVP Setup Help' bl_idname = 'uvpackmaster2.uv_uvp_setup_help' bl_description = \"Show",
"process killed') cancel = True except OpCancelledException: self.set_status('INFO', 'Operation cancelled by the user')",
"it under the terms of the GNU General Public License # as published",
"self.similar_islands_msg = msg elif msg_code == UvPackMessageCode.ISLANDS: self.read_islands(msg) elif msg_code == UvPackMessageCode.ISLANDS_METADATA: if",
"op_status = 'Packing stopped - no space to pack all islands' self.add_warning(\"Overlap check",
"= 'uvpackmaster2.uv_island_rot_step_help' bl_description = \"Show help for setting rotation step on per-island level\"",
"0: if op_status_type == 'INFO': op_status_type = 'WARNING' op_status += '. (WARNINGS were",
"is not None: self.raiseUnexpectedOutputError() self.island_flags_msg = msg elif msg_code == UvPackMessageCode.PACK_SOLUTION: if self.pack_solution_msg",
"self.curr_phase == UvPackingPhaseCode.DONE: self.handle_op_done() elif msg_code == UvPackMessageCode.INVALID_ISLANDS: if self.invalid_islands_msg is not None:",
"in_debug_mode(): if self.prefs.seed > 0: uvp_args_final += ['-S', str(self.prefs.seed)] if self.prefs.wait_for_debugger: uvp_args_final.append('-G') uvp_args_final",
"= -1 self.progress_iter_done = -1 self.progress_last_update_time = 0.0 self.curr_phase = UvPackingPhaseCode.INITIALIZATION self.invalid_islands_msg =",
"all islands' self.add_warning(\"Overlap check was performed only on the islands which were packed\")",
"col.label(text=self.confirmation_msg) def get_confirmation_msg(self): return '' def send_unselected_islands(self): return False def grouping_enabled(self): return False",
"'Undo Islands Adjustment' bl_description = \"Undo adjustment performed by the 'Adjust Islands To",
"return 'Searching for similar islands (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_ALIGNING:",
"== UvGroupingMethodUvp.EXTERNAL) send_lock_groups = self.lock_groups_enabled() send_verts_3d = self.send_verts_3d() selected_cnt, unselected_cnt = self.p_context.serialize_uv_maps(send_unselected, send_groups,",
"not None: end_str = '(press ESC to apply result) ' else: end_str =",
"performed only on the islands which were packed\") else: op_status = 'Packing done'",
"in the demo mode only the number of similar islands found is reported,",
"their packing box after packing (check the selected islands). This usually happens when",
"self.p_context.select_island_faces(island_idx, self.p_context.uv_island_faces_list[island_idx], True) else: if len(similar_islands) > 0: self.raiseUnexpectedOutputError() self.set_status('INFO', 'Similar islands found:",
"== UvPackingPhaseCode.INITIALIZATION: return 'Initialization (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_ANALYSIS: return",
"UVP2_OT_AdjustIslandsToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_adjust_islands_to_texture' bl_label = 'Adjust Islands To Texture' bl_description = \"Adjust",
"OpCancelledException: self.set_status('INFO', 'Operation cancelled by the user') cancel = True except InvalidIslandsError as",
"self.scene_props.advanced_heuristic: uvp_args.append('-H') uvp_args += ['-g', self.scene_props.pack_mode] tile_count, tiles_in_row = self.prefs.tile_grid_config(self.scene_props, self.p_context.context) if self.prefs.pack_to_tiles(self.scene_props):",
"as err: self.set_status('ERROR', str(err)) cancel = True except RuntimeError as ex: if in_debug_mode():",
"self.set_status('ERROR', str(err)) cancel = True except RuntimeError as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR',",
"self.set_status('ERROR', 'Unexpected error') cancel = True if cancel: return self.cancel(context) return {'RUNNING_MODAL'} if",
"progress_msg_spec: return progress_msg_spec if self.curr_phase == UvPackingPhaseCode.INITIALIZATION: return 'Initialization (press ESC to cancel)'",
"progress (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.AREA_MEASUREMENT: return 'Area measurement in",
"into a square texture. For for info regarding non-square packing read the documentation\"",
"OK to continue' return '' def process_result(self): if self.invalid_faces_msg is None: self.raiseUnexpectedOutputError() invalid_face_count",
"UvPackingPhaseCode.SIMILAR_ALIGNING: return 'Similar islands aligning (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.RENDER_PRESENTATION:",
"self.area is not None: op_status += ', packed islands area: ' + str(self.area)",
"self.lock_groups_enabled() send_verts_3d = self.send_verts_3d() selected_cnt, unselected_cnt = self.p_context.serialize_uv_maps(send_unselected, send_groups, send_rot_step, send_lock_groups, send_verts_3d, self.get_group_method()",
"UV faces. The validation procedure looks for invalid UV faces i.e. faces with",
"msg_code == UvPackMessageCode.AREA: if self.area_msg is not None: self.raiseUnexpectedOutputError() self.area_msg = msg elif",
"+= ['-I', str(self.scene_props.similarity_threshold)] if self.prefs.pack_groups_together(self.scene_props): uvp_args += ['-U', str(self.scene_props.group_compactness)] if self.prefs.multi_device_enabled(self.scene_props): uvp_args.append('-u') if",
"return round(force_read_float(area_msg) / self.pack_ratio, 3) class UVP2_OT_PackOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_pack' bl_label = 'Pack'",
"self.area = None def get_confirmation_msg(self): if platform.system() == 'Darwin': active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if",
"curr_time - self.last_msg_time > self.hang_timeout: self.hang_detected = True def handle_event(self, event): # Kill",
"True) if invalid_face_count > 0: self.set_status('WARNING', 'Pre-validation failed. Number of invalid faces found:",
"def poll(cls, context): prefs = get_prefs() return prefs.uvp_initialized and context.active_object is not None",
"not None: self.raiseUnexpectedOutputError() self.islands_metadata_msg = msg else: self.raiseUnexpectedOutputError() def handle_communication(self): if self.op_done: return",
"self.get_group_method() == UvGroupingMethod.SIMILARITY.code: if self.prefs.pack_to_others_enabled(self.scene_props): raise RuntimeError(\"'Pack To Others' is not supported with",
"self.prefs.lock_overlap_enabled(self.scene_props): uvp_args += ['-l', self.scene_props.lock_overlapping_mode] if self.prefs.pack_to_others_enabled(self.scene_props): uvp_args += ['-x'] if self.prefs.FEATURE_validation and",
"return False def process_result(self): overlap_detected = False outside_detected = False if self.invalid_faces_msg is",
"self.progress_array: percent_progress_str += str(prog).rjust(3, ' ') + '%, ' percent_progress_str = percent_progress_str[:-2] progress_str",
"InvalidIslandsError(error_msg) def require_selection(self): return True def finish_after_op_done(self): return True def handle_op_done(self): self.op_done =",
"= True send_finish_confirmation(self.uvp_proc) try: self.uvp_proc.wait(5) except: raise RuntimeError('The UVP process wait timeout reached')",
"send_unselected = self.send_unselected_islands() send_rot_step = self.send_rot_step() send_groups = self.grouping_enabled() and (to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.EXTERNAL)",
"sec. \".format(self.progress_sec_left) else: time_left_str = '' percent_progress_str = '' for prog in self.progress_array:",
"selected islands). Consider increasing the 'Precision' parameter. Sometimes increasing the 'Adjustment Time' may",
"0: uvp_args_final += ['-S', str(self.prefs.seed)] if self.prefs.wait_for_debugger: uvp_args_final.append('-G') uvp_args_final += ['-T', str(self.prefs.test_param)] print('Pakcer",
"number of invalid faces found is reported, invalid faces will not be selected.",
"if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None if active_dev is not None and active_dev.id.startswith('cuda'):",
"wm.modal_handler_add(self) return {'RUNNING_MODAL'} class FakeTimerEvent: def __init__(self): self.type = 'TIMER' self.value = 'NOTHING'",
"invalid_faces = read_int_array(self.invalid_faces_msg) if not self.prefs.FEATURE_demo: if len(invalid_faces) != invalid_face_count: self.raiseUnexpectedOutputError() if invalid_face_count",
"self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg) overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags) if overlap_detected: self.set_status('WARNING', 'Overlapping islands",
"self.raiseUnexpectedOutputError() self.islands_metadata_msg = msg else: self.raiseUnexpectedOutputError() def handle_communication(self): if self.op_done: return msg_received =",
"return self.finish(context) except OpAbortedException: self.set_status('INFO', 'Packer process killed') cancel = True except OpCancelledException:",
"if self.prefs.heuristic_enabled(self.scene_props): uvp_args += ['-h', str(self.scene_props.heuristic_search_time), '-j', str(self.scene_props.heuristic_max_wait_time)] if self.prefs.FEATURE_advanced_heuristic and self.scene_props.advanced_heuristic: uvp_args.append('-H')",
"[get_uvp_execpath(), '-E', '-e', str(UvTopoAnalysisLevel.FORCE_EXTENDED), '-t', str(self.prefs.thread_count)] + self.get_uvp_args() if send_unselected: uvp_args_final.append('-s') if self.grouping_enabled():",
"= self.grouping_enabled() and (to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.EXTERNAL) send_lock_groups = self.lock_groups_enabled() send_verts_3d = self.send_verts_3d() selected_cnt,",
"None: popen_args['creationflags'] = creation_flags self.uvp_proc = subprocess.Popen(uvp_args_final, stdin=subprocess.PIPE, stdout=subprocess.PIPE, **popen_args) out_stream = self.uvp_proc.stdin",
"should not be required to but check once again to be on the",
"UvPackMessageCode.BENCHMARK: stats = self.prefs.stats_array.add() dev_name_len = force_read_int(msg) stats.dev_name = msg.read(dev_name_len).decode('ascii') stats.iter_count = force_read_int(msg)",
"for similarity detection\" URL_SUFFIX = \"similarity-detection\" class UVP2_OT_InvalidTopologyHelp(UVP2_OT_Help): bl_label = 'Invalid Topology Help'",
"ex: self.set_status('WARNING', str(ex)) cancel = True except RuntimeError as ex: if in_debug_mode(): print_backtrace(ex)",
"self.handle_communication() if not self.op_done: # Special value indicating a crash self.prefs.uvp_retcode = -1",
"click the help button\" def get_uvp_opcode(self): return UvPackerOpcode.ALIGN_SIMILAR def process_result(self): if self.prefs.FEATURE_demo: return",
"self.send_rot_step(): uvp_args_final += ['-R'] if self.lock_groups_enabled(): uvp_args_final += ['-Q'] if in_debug_mode(): if self.prefs.seed",
"'Pixel margin adjustment. ' elif self.prefs.heuristic_enabled(self.scene_props): header_str = 'Current area: {}. '.format(self.area if",
"'Islands area: ' + str(area)) def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o',",
"i in range(progress_size): self.progress_array[i] = force_read_int(msg) self.progress_sec_left = force_read_int(msg) self.progress_iter_done = force_read_int(msg) #",
"faces. The validation procedure looks for invalid UV faces i.e. faces with area",
"uvp_args += ['-O'] uvp_args += ['-F', self.scene_props.fixed_scale_strategy] if self.prefs.FEATURE_island_rotation: if self.scene_props.rot_enable: rot_step_value =",
"UvPackMessageCode.PACK_SOLUTION: if self.pack_solution_msg is not None: self.raiseUnexpectedOutputError() self.pack_solution_msg = msg elif msg_code ==",
"and context.active_object is not None and context.active_object.mode == 'EDIT' def check_uvp_retcode(self, retcode): self.prefs.uvp_retcode",
"if selected_cnt == 0: raise NoUvFaceError('No UV face selected') else: if selected_cnt +",
"== UvPackMessageCode.SIMILAR_ISLANDS: if self.similar_islands_msg is not None: self.raiseUnexpectedOutputError() self.similar_islands_msg = msg elif msg_code",
"= self.area if self.uvp_proc.returncode == UvPackerErrorCode.NO_SPACE: op_status = 'Packing stopped - no space",
"self.interactive = True self.prefs = get_prefs() self.scene_props = context.scene.uvp2_props self.confirmation_msg = self.get_confirmation_msg() wm",
"Help' bl_idname = 'uvpackmaster2.uv_similarity_detection_help' bl_description = \"Show help for similarity detection\" URL_SUFFIX =",
"self.prefs.FEATURE_demo: return 'WARNING: in the demo mode only the number of invalid faces",
"if not new_progress_msg: return now = time.time() if now - self.progress_last_update_time > msg_refresh_interval",
"self.raiseUnexpectedOutputError() self.invalid_faces_msg = msg elif msg_code == UvPackMessageCode.SIMILAR_ISLANDS: if self.similar_islands_msg is not None:",
"= \"Faces with inconsistent {} values found in the selected islands\".format(param_array[subcode].NAME) else: self.raiseUnexpectedOutputError()",
"curr_time = time.time() if msg_received > 0: self.last_msg_time = curr_time self.hang_detected = False",
"self.get_uvp_args() if send_unselected: uvp_args_final.append('-s') if self.grouping_enabled(): uvp_args_final += ['-a', str(to_uvp_group_method(self.get_group_method()))] if self.send_rot_step(): uvp_args_final",
"def get_progress_msg_spec(self): if self.curr_phase in { UvPackingPhaseCode.PACKING, UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT }: if self.curr_phase == UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT:",
"self.pack_ratio, 3) class UVP2_OT_PackOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_pack' bl_label = 'Pack' bl_description = 'Pack",
"0.1 interactive = False @classmethod def poll(cls, context): prefs = get_prefs() return prefs.uvp_initialized",
"== UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT: header_str = 'Pixel margin adjustment. ' elif self.prefs.heuristic_enabled(self.scene_props): header_str = 'Current",
"already selected. For more info regarding similarity detection click the help button\" def",
"and event.type == 'ESC': raise OpAbortedException() if self.handle_event_spec(event): return # Generic event processing",
"not self.prefs.FEATURE_demo: if len(similar_islands) != similar_island_count: self.raiseUnexpectedOutputError() for island_idx in similar_islands: self.p_context.select_island_faces(island_idx, self.p_context.uv_island_faces_list[island_idx],",
"'Adjust Islands To Texture' bl_description = \"Adjust scale of selected islands so they",
"in { UvPackingPhaseCode.PACKING, UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT }: if self.curr_phase == UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT: header_str = 'Pixel margin",
"prec)) def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.PACK), '-i', str(self.scene_props.precision), '-m', str(self.scene_props.margin)] uvp_args +=",
"is not supported in this engine edition') if self.grouping_enabled(): if self.get_group_method() == UvGroupingMethod.SIMILARITY.code:",
"UvPackingPhaseCode.PACKING, UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT }: if self.curr_phase == UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT: header_str = 'Pixel margin adjustment. '",
"if self.curr_phase == UvPackingPhaseCode.OVERLAP_CHECK: return 'Overlap check in progress (press ESC to cancel)'",
"MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### import subprocess",
"= None self.invalid_faces_msg = None self.similar_islands_msg = None self.islands_metadata_msg = None except NoUvFaceError",
"'.join(x for x in uvp_args_final)) creation_flags = os_uvp_creation_flags() popen_args = dict() if creation_flags",
"pass def execute(self, context): cancel = False self.op_done = False self.uvp_proc = None",
"self.p_context.context.tool_settings.use_uv_select_sync: self.p_context.context.tool_settings.mesh_select_mode = (False, False, True) else: self.p_context.context.tool_settings.uv_select_mode = 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True)",
"is reported, islands will not be selected. Click OK to continue' return ''",
"\"heuristic-search\" class UVP2_OT_NonSquarePackingHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing Help' bl_idname = 'uvpackmaster2.uv_nonsquare_packing_help' bl_description =",
"click the help button\" def get_confirmation_msg(self): if self.prefs.FEATURE_demo: return 'WARNING: in the demo",
"= 4 return \"{}:{}:{}:{}\".format( round(target_box[0].x, prec), round(target_box[0].y, prec), round(target_box[1].x, prec), round(target_box[1].y, prec)) def",
"True self.connection_thread.start() self.progress_array = [0] self.progress_msg = '' self.progress_sec_left = -1 self.progress_iter_done =",
"return UvPackerOpcode.ALIGN_SIMILAR def process_result(self): if self.prefs.FEATURE_demo: return if self.pack_solution_msg is None: self.raiseUnexpectedOutputError() pack_solution",
"force_read_int(self.invalid_islands_msg) subcode = force_read_int(self.invalid_islands_msg) invalid_islands = read_int_array(self.invalid_islands_msg) if len(invalid_islands) == 0: self.raiseUnexpectedOutputError() self.p_context.handle_invalid_islands(invalid_islands)",
"return {'FINISHED', 'PASS_THROUGH'} def cancel(self, context): self.uvp_proc.terminate() # self.progress_thread.terminate() self.exit_common() return {'FINISHED'} def",
"self.finish_after_op_done(): raise OpFinishedException() def finish(self, context): self.exit_common() return {'FINISHED', 'PASS_THROUGH'} def cancel(self, context):",
"class FakeTimerEvent: def __init__(self): self.type = 'TIMER' self.value = 'NOTHING' self.ctrl = False",
"bpy import mathutils import tempfile class InvalidIslandsError(Exception): pass class NoUvFaceError(Exception): pass class UVP2_OT_PackOperatorGeneric(bpy.types.Operator):",
"raise RuntimeError(\"'Pack To Others' is not supported with grouping by similarity\") if not",
"== UvPackerErrorCode.NO_VALID_STATIC_ISLAND: raise RuntimeError(\"'Pack To Others' option enabled, but no unselected island found",
"= 'Packing stopped - no space to pack all islands' self.add_warning(\"Overlap check was",
"if self.uvp_proc.returncode != UvPackerErrorCode.INVALID_ISLANDS: return if self.invalid_islands_msg is None: self.raiseUnexpectedOutputError() code = force_read_int(self.invalid_islands_msg)",
"ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_SELECTION: return 'Searching for similar islands (press",
"False self.area = None def get_confirmation_msg(self): if platform.system() == 'Darwin': active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx]",
"= None self.op_warnings = [] try: if not check_uvp(): unregister_uvp() redraw_ui(context) raise RuntimeError(\"UVP",
"0, self-intersecting faces, faces overlapping each other' def get_confirmation_msg(self): if self.prefs.FEATURE_demo: return 'WARNING:",
"packing box after packing (check the selected islands). This usually happens when 'Pixel",
"suitable for packing into a square texture. For for info regarding non-square packing",
"+ '. Packing aborted') return if not self.prefs.FEATURE_demo: if self.island_flags_msg is None: self.raiseUnexpectedOutputError()",
"License # as published by the Free Software Foundation; either version 2 #",
"as ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, 'Unexpected error') self.p_context.update_meshes() return {'FINISHED'} def get_scale_factors(self):",
"= \"Selects all islands which have similar shape to islands which are already",
"def get_target_box_string(self, target_box): prec = 4 return \"{}:{}:{}:{}\".format( round(target_box[0].x, prec), round(target_box[0].y, prec), round(target_box[1].x,",
"msg_refresh_interval or new_progress_msg != self.progress_msg: self.progress_last_update_time = now self.progress_msg = new_progress_msg self.report({'INFO'}, self.progress_msg)",
"self.value = 'NOTHING' self.ctrl = False while True: event = FakeTimerEvent() ret =",
"selected islands. Check the Help panel to learn more\" elif code == UvInvalidIslandCode.INT_PARAM:",
"def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.MEASURE_AREA)] return uvp_args class UVP2_OT_ValidateOperator(UVP2_OT_PackOperatorGeneric):",
"outside their packing box after packing (check the selected islands). This usually happens",
"UvPackingPhaseCode.TOPOLOGY_ANALYSIS: return \"Topology analysis: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.OVERLAP_CHECK:",
"send_verts_3d = self.send_verts_3d() selected_cnt, unselected_cnt = self.p_context.serialize_uv_maps(send_unselected, send_groups, send_rot_step, send_lock_groups, send_verts_3d, self.get_group_method() if",
"> self.hang_timeout: self.hang_detected = True def handle_event(self, event): # Kill the UVP process",
"threading.Thread(target=connection_thread_func, args=(self.uvp_proc.stdout, self.progress_queue)) self.connection_thread.daemon = True self.connection_thread.start() self.progress_array = [0] self.progress_msg = ''",
"op_status = 'Packing done' if self.area is not None: op_status += ', packed",
"longer time (press ESC to abort)' if self.curr_phase is None: return False progress_msg_spec",
"if event.type == 'ESC': raise OpCancelledException() elif event.type == 'TIMER': self.handle_communication() def modal(self,",
"return {'FINISHED'} def get_progress_msg_spec(self): return False def get_progress_msg(self): if self.hang_detected: return 'Packer process",
"if retcode == UvPackerErrorCode.NO_VALID_STATIC_ISLAND: raise RuntimeError(\"'Pack To Others' option enabled, but no unselected",
"was detected if self.hang_detected and event.type == 'ESC': raise OpAbortedException() if self.handle_event_spec(event): return",
"per-island level\" URL_SUFFIX = \"island-rotation-step\" class UVP2_OT_UdimSupportHelp(UVP2_OT_Help): bl_label = 'UDIM Support Help' bl_idname",
"self.pack_solution_msg = msg elif msg_code == UvPackMessageCode.AREA: if self.area_msg is not None: self.raiseUnexpectedOutputError()",
"validate_target_box(self.scene_props) def get_target_box_string(self, target_box): prec = 4 return \"{}:{}:{}:{}\".format( round(target_box[0].x, prec), round(target_box[0].y, prec),",
"ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR",
"you can redistribute it and/or # modify it under the terms of the",
"ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', 'Unexpected error') cancel = True if cancel: return",
"return 'Packer process not responding for a longer time (press ESC to abort)'",
"not None else 'none') else: header_str = '' if self.progress_iter_done >= 0: iter_str",
"None except NoUvFaceError as ex: self.set_status('WARNING', str(ex)) cancel = True except RuntimeError as",
"None self.op_status_type = None self.op_status = None self.op_warnings = [] try: if not",
"finish = True except: raise if finish: return self.finish(context) except OpAbortedException: self.set_status('INFO', 'Packer",
"self.progress_iter_done >= 0: iter_str = 'Iter. done: {}. '.format(self.progress_iter_done) else: iter_str = ''",
"help for UVP setup\" URL_SUFFIX = \"uvp-setup\" class UVP2_OT_HeuristicSearchHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing",
"True def finish_after_op_done(self): return True def handle_op_done(self): self.op_done = True send_finish_confirmation(self.uvp_proc) try: self.uvp_proc.wait(5)",
"= now self.progress_msg = new_progress_msg self.report({'INFO'}, self.progress_msg) def handle_uvp_msg(self, msg): msg_code = force_read_int(msg)",
"WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS",
"msg_code == UvPackMessageCode.INVALID_ISLANDS: if self.invalid_islands_msg is not None: self.raiseUnexpectedOutputError() self.invalid_islands_msg = msg elif",
"def modal(self, context, event): cancel = False finish = False try: try: self.handle_event(event)",
"'uvpackmaster2.uv_overlap_check' bl_label = 'Overlap Check' bl_description = 'Check wheter selected UV islands overlap",
"the problem (if used in the operation).\") if outside_detected: self.add_warning(\"Some islands are outside",
"# # You should have received a copy of the GNU General Public",
"self.uvp_proc = subprocess.Popen(uvp_args_final, stdin=subprocess.PIPE, stdout=subprocess.PIPE, **popen_args) out_stream = self.uvp_proc.stdin out_stream.write(self.p_context.serialized_maps) out_stream.flush() self.start_time =",
"= -1 raise RuntimeError('Packer process died unexpectedly') self.handle_progress_msg() except OpFinishedException: finish = True",
"self.p_context.context))] if self.prefs.pixel_padding_enabled(self.scene_props): uvp_args += ['-N', str(self.scene_props.pixel_padding)] uvp_args += ['-W', self.scene_props.pixel_margin_method] uvp_args +=",
"i.e. faces with area close to 0, self-intersecting faces, faces overlapping each other'",
"is not None: self.raiseUnexpectedOutputError() self.pack_solution_msg = msg elif msg_code == UvPackMessageCode.AREA: if self.area_msg",
"msg_code == UvPackMessageCode.BENCHMARK: stats = self.prefs.stats_array.add() dev_name_len = force_read_int(msg) stats.dev_name = msg.read(dev_name_len).decode('ascii') stats.iter_count",
"if self.op_done: return msg_received = 0 while True: try: item = self.progress_queue.get_nowait() except",
"self.curr_phase == UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT: header_str = 'Pixel margin adjustment. ' elif self.prefs.heuristic_enabled(self.scene_props): header_str =",
"= status def add_warning(self, warn_msg): self.op_warnings.append(warn_msg) def report_status(self): if self.op_status is not None:",
"progress_str + end_str return False def handle_uvp_msg_spec(self, msg_code, msg): if msg_code == UvPackMessageCode.AREA:",
"other' def process_result(self): if self.island_flags_msg is None: self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg) overlap_detected, outside_detected",
"Public License for more details. # # You should have received a copy",
"self.read_islands(msg) elif msg_code == UvPackMessageCode.ISLANDS_METADATA: if self.islands_metadata_msg is not None: self.raiseUnexpectedOutputError() self.islands_metadata_msg =",
"None self.op_warnings = [] try: if not check_uvp(): unregister_uvp() redraw_ui(context) raise RuntimeError(\"UVP engine",
"are already selected. For more info regarding similarity detection click the help button\"",
"return self.scene_props.group_method def send_rot_step(self): return self.prefs.FEATURE_island_rotation_step and self.scene_props.rot_enable and self.scene_props.island_rot_step_enable def lock_groups_enabled(self): return",
"self.area_msg is not None: self.raiseUnexpectedOutputError() self.area_msg = msg elif msg_code == UvPackMessageCode.INVALID_FACES: if",
"to cancel)' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_ANALYSIS: return \"Topology analysis: {:3}% (press ESC to",
"if self.interactive: wm = context.window_manager self._timer = wm.event_timer_add(self.MODAL_INTERVAL_S, window=context.window) wm.modal_handler_add(self) return {'RUNNING_MODAL'} class",
"= 'Overlap Check' bl_description = 'Check wheter selected UV islands overlap each other'",
"prefs.uvp_initialized and context.active_object is not None and context.active_object.mode == 'EDIT' def check_uvp_retcode(self, retcode):",
"== UvPackMessageCode.AREA: if self.area_msg is not None: self.raiseUnexpectedOutputError() self.area_msg = msg elif msg_code",
"force_read_int(msg) self.progress_iter_done = force_read_int(msg) # Inform the upper layer wheter it should finish",
"wheter selected UV islands overlap each other' def process_result(self): if self.island_flags_msg is None:",
"= self.p_context.serialize_uv_maps(send_unselected, send_groups, send_rot_step, send_lock_groups, send_verts_3d, self.get_group_method() if send_groups else None) if self.require_selection():",
"uvp_args_final = [get_uvp_execpath(), '-E', '-e', str(UvTopoAnalysisLevel.FORCE_EXTENDED), '-t', str(self.prefs.thread_count)] + self.get_uvp_args() if send_unselected: uvp_args_final.append('-s')",
"self.prefs.heuristic_enabled(self.scene_props): uvp_args += ['-h', str(self.scene_props.heuristic_search_time), '-j', str(self.scene_props.heuristic_max_wait_time)] if self.prefs.FEATURE_advanced_heuristic and self.scene_props.advanced_heuristic: uvp_args.append('-H') uvp_args",
"Help panel to learn more\" elif code == UvInvalidIslandCode.INT_PARAM: param_array = IslandParamInfo.get_param_info_array() error_msg",
"self.last_msg_time = self.start_time self.hang_detected = False self.hang_timeout = 10.0 # Start progress monitor",
"status): self.op_status_type = status_type self.op_status = status def add_warning(self, warn_msg): self.op_warnings.append(warn_msg) def report_status(self):",
"event): cancel = False finish = False try: try: self.handle_event(event) # Check whether",
"msg_code == UvPackMessageCode.PACK_SOLUTION: pack_solution = read_pack_solution(msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) return True elif msg_code ==",
"from the connection thread') msg_received += 1 curr_time = time.time() if msg_received >",
"(press ESC to abort)' if self.curr_phase is None: return False progress_msg_spec = self.get_progress_msg_spec()",
"None self.islands_metadata_msg = None except NoUvFaceError as ex: self.set_status('WARNING', str(ex)) cancel = True",
"if overlap_detected: self.add_warning(\"Overlapping islands were detected after packing (check the selected islands). Consider",
"False def get_progress_msg(self): if self.hang_detected: return 'Packer process not responding for a longer",
"UVP2_OT_Help(bpy.types.Operator): bl_label = 'Help' def execute(self, context): webbrowser.open(UvpLabels.HELP_BASEURL + self.URL_SUFFIX) return {'FINISHED'} class",
"wm.event_timer_remove(self._timer) self.p_context.update_meshes() self.report_status() if in_debug_mode(): print('UVP operation time: ' + str(time.time() - self.start_time))",
"else: header_str = '' if self.progress_iter_done >= 0: iter_str = 'Iter. done: {}.",
"self.progress_sec_left = -1 self.progress_iter_done = -1 self.progress_last_update_time = 0.0 self.curr_phase = UvPackingPhaseCode.INITIALIZATION self.invalid_islands_msg",
"event.type == 'ESC': if not self.cancel_sig_sent: self.uvp_proc.send_signal(os_cancel_sig()) self.cancel_sig_sent = True return True return",
"self.p_context.handle_island_flags(island_flags) if self.area is not None: self.prefs.stats_area = self.area if self.uvp_proc.returncode == UvPackerErrorCode.NO_SPACE:",
"def get_uvp_opcode(self): return UvPackerOpcode.ALIGN_SIMILAR def process_result(self): if self.prefs.FEATURE_demo: return if self.pack_solution_msg is None:",
"try: try: self.handle_event(event) # Check whether the uvp process is alive if not",
"visible') self.validate_pack_params() if self.prefs.write_to_file: out_filepath = os.path.join(tempfile.gettempdir(), 'uv_islands.data') out_file = open(out_filepath, 'wb') out_file.write(self.p_context.serialized_maps)",
"self.island_flags_msg is not None: self.raiseUnexpectedOutputError() self.island_flags_msg = msg elif msg_code == UvPackMessageCode.PACK_SOLUTION: if",
"self.progress_iter_done = -1 self.progress_last_update_time = 0.0 self.curr_phase = UvPackingPhaseCode.INITIALIZATION self.invalid_islands_msg = None self.island_flags_msg",
"grouping_enabled(self): return False def get_group_method(self): raise RuntimeError('Unexpected grouping requested') def send_rot_step(self): return False",
"To Texture' bl_description = \"Adjust scale of selected islands so they are suitable",
"'Searching for similar islands (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_ALIGNING: return",
"outside_detected = self.p_context.handle_island_flags(island_flags) if overlap_detected: self.set_status('WARNING', 'Overlapping islands detected') else: self.set_status('INFO', 'No overlapping",
"== UvPackingPhaseCode.VALIDATION: return \"Per-face overlap check: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) raise RuntimeError('Unexpected",
"+= ['-a', str(to_uvp_group_method(self.get_group_method()))] if self.send_rot_step(): uvp_args_final += ['-R'] if self.lock_groups_enabled(): uvp_args_final += ['-Q']",
"self.handle_progress_msg() except OpFinishedException: finish = True except: raise if finish: return self.finish(context) except",
"False def handle_uvp_msg_spec(self, msg_code, msg): if msg_code == UvPackMessageCode.AREA: self.area = self.read_area(msg) return",
"'Help' def execute(self, context): webbrowser.open(UvpLabels.HELP_BASEURL + self.URL_SUFFIX) return {'FINISHED'} class UVP2_OT_UvpSetupHelp(UVP2_OT_Help): bl_label =",
"not self.prefs.FEATURE_demo: if len(invalid_faces) != invalid_face_count: self.raiseUnexpectedOutputError() if invalid_face_count > 0: # Switch",
"= read_pack_solution(msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) return True elif msg_code == UvPackMessageCode.BENCHMARK: stats = self.prefs.stats_array.add()",
"bl_label = 'Island Rotation Step Help' bl_idname = 'uvpackmaster2.uv_island_rot_step_help' bl_description = \"Show help",
"pass class UVP2_OT_PackOperatorGeneric(bpy.types.Operator): bl_options = {'UNDO'} MODAL_INTERVAL_S = 0.1 interactive = False @classmethod",
"msg_code == UvPackMessageCode.PROGRESS_REPORT: self.curr_phase = force_read_int(msg) progress_size = force_read_int(msg) if progress_size > len(self.progress_array):",
"self.target_box = None self.op_status_type = None self.op_status = None self.op_warnings = [] try:",
"def cancel(self, context): self.uvp_proc.terminate() # self.progress_thread.terminate() self.exit_common() return {'FINISHED'} def get_progress_msg_spec(self): return False",
"GPL LICENSE BLOCK ##### import subprocess import queue import threading import signal import",
"- self.start_time)) def read_islands(self, islands_msg): islands = [] island_cnt = force_read_int(islands_msg) selected_cnt =",
"if send_groups else None) if self.require_selection(): if selected_cnt == 0: raise NoUvFaceError('No UV",
"finish(self, context): self.exit_common() return {'FINISHED', 'PASS_THROUGH'} def cancel(self, context): self.uvp_proc.terminate() # self.progress_thread.terminate() self.exit_common()",
"True def handle_op_done(self): self.op_done = True send_finish_confirmation(self.uvp_proc) try: self.uvp_proc.wait(5) except: raise RuntimeError('The UVP",
"is not None: self.raiseUnexpectedOutputError() self.invalid_islands_msg = msg elif msg_code == UvPackMessageCode.ISLAND_FLAGS: if self.island_flags_msg",
"> 0: self.set_status('WARNING', 'Pre-validation failed. Number of invalid faces found: ' + str(invalid_face_count)",
"as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', str(ex)) cancel = True except Exception as",
"\"udim-support\" class UVP2_OT_ManualGroupingHelp(UVP2_OT_Help): bl_label = 'Manual Grouping Help' bl_idname = 'uvpackmaster2.uv_manual_grouping_help' bl_description =",
"islands found: ' + str(similar_island_count)) class UVP2_OT_AlignSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_align_similar' bl_label = 'Align",
"'-t', str(self.prefs.thread_count)] + self.get_uvp_args() if send_unselected: uvp_args_final.append('-s') if self.grouping_enabled(): uvp_args_final += ['-a', str(to_uvp_group_method(self.get_group_method()))]",
"to 0, self-intersecting faces, faces overlapping each other' def get_confirmation_msg(self): if self.prefs.FEATURE_demo: return",
"adjustment performed by the 'Adjust Islands To Texture' operator so islands are again",
"if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None if active_dev is None: raise RuntimeError('Could not",
"self.progress_array[i] = force_read_int(msg) self.progress_sec_left = force_read_int(msg) self.progress_iter_done = force_read_int(msg) # Inform the upper",
"return self.cancel(context) return {'RUNNING_MODAL'} if not self.op_done else {'PASS_THROUGH'} def pre_op_initialize(self): pass def",
"self.send_unselected_islands() send_rot_step = self.send_rot_step() send_groups = self.grouping_enabled() and (to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.EXTERNAL) send_lock_groups =",
"unselected island found in the packing box\") if retcode == UvPackerErrorCode.MAX_GROUP_COUNT_EXCEEDED: raise RuntimeError(\"Maximal",
"get_uvp_opcode(self): return UvPackerOpcode.ALIGN_SIMILAR def process_result(self): if self.prefs.FEATURE_demo: return if self.pack_solution_msg is None: self.raiseUnexpectedOutputError()",
"len(invalid_faces) > 0: self.raiseUnexpectedOutputError() if invalid_face_count > 0: self.set_status('WARNING', 'Number of invalid faces",
"solve the problem (if used in the operation).\") if outside_detected: self.add_warning(\"Some islands are",
"== UvPackMessageCode.ISLANDS: self.read_islands(msg) elif msg_code == UvPackMessageCode.ISLANDS_METADATA: if self.islands_metadata_msg is not None: self.raiseUnexpectedOutputError()",
"send_finish_confirmation(self.uvp_proc) try: self.uvp_proc.wait(5) except: raise RuntimeError('The UVP process wait timeout reached') self.connection_thread.join() self.check_uvp_retcode(self.uvp_proc.returncode)",
"= PackContext(context) ratio = get_active_image_ratio(self.p_context.context) self.p_context.scale_selected_faces(self.get_scale_factors()) except RuntimeError as ex: if in_debug_mode(): print_backtrace(ex)",
"self.prefs.FEATURE_validation and self.scene_props.pre_validate: uvp_args.append('-v') if self.prefs.normalize_islands_enabled(self.scene_props): uvp_args.append('-L') if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: self.target_box =",
"\"Topology validation: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.VALIDATION: return \"Per-face",
"number of similar islands found is reported, islands will not be selected. Click",
"\"similarity-detection\" class UVP2_OT_InvalidTopologyHelp(UVP2_OT_Help): bl_label = 'Invalid Topology Help' bl_idname = 'uvpackmaster2.uv_invalid_topology_help' bl_description =",
"'' percent_progress_str = '' for prog in self.progress_array: percent_progress_str += str(prog).rjust(3, ' ')",
"in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', 'Unexpected error') cancel = True if self.p_context is not None:",
"is reported, invalid faces will not be selected. Click OK to continue' return",
"raise RuntimeError('Pack process returned an error') def raiseUnexpectedOutputError(self): raise RuntimeError('Unexpected output from the",
"self.exit_common() return {'FINISHED'} def get_progress_msg_spec(self): return False def get_progress_msg(self): if self.hang_detected: return 'Packer",
"> 0: self.last_msg_time = curr_time self.hang_detected = False else: if self.curr_phase != UvPackingPhaseCode.RENDER_PRESENTATION",
"in range(progress_size): self.progress_array[i] = force_read_int(msg) self.progress_sec_left = force_read_int(msg) self.progress_iter_done = force_read_int(msg) # Inform",
"selected islands). This usually happens when 'Pixel Padding' is set to a small",
"island_cnt = force_read_int(islands_msg) selected_cnt = force_read_int(islands_msg) for i in range(island_cnt): islands.append(read_int_array(islands_msg)) self.p_context.set_islands(selected_cnt, islands)",
"Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE",
"bl_description = \"Show help for non-square packing\" URL_SUFFIX = \"non-square-packing\" class UVP2_OT_SimilarityDetectionHelp(UVP2_OT_Help): bl_label",
"report_status(self): if self.op_status is not None: self.prefs['op_status'] = self.op_status op_status_type = self.op_status_type if",
"if self.grouping_enabled(): if to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.SIMILARITY: uvp_args += ['-I', str(self.scene_props.similarity_threshold)] if self.prefs.pack_groups_together(self.scene_props): uvp_args",
"UvPackerOpcode.ALIGN_SIMILAR def process_result(self): if self.prefs.FEATURE_demo: return if self.pack_solution_msg is None: self.raiseUnexpectedOutputError() pack_solution =",
"[0] * (progress_size) for i in range(progress_size): self.progress_array[i] = force_read_int(msg) self.progress_sec_left = force_read_int(msg)",
"stopped - no space to pack all islands' self.add_warning(\"Overlap check was performed only",
"only the number of invalid faces found is reported, invalid faces will not",
"free software; you can redistribute it and/or # modify it under the terms",
"self.prefs.uvp_retcode = retcode if retcode in {UvPackerErrorCode.SUCCESS, UvPackerErrorCode.INVALID_ISLANDS, UvPackerErrorCode.NO_SPACE, UvPackerErrorCode.PRE_VALIDATION_FAILED}: return if retcode",
"param_array = IslandParamInfo.get_param_info_array() error_msg = \"Faces with inconsistent {} values found in the",
"['-R'] if self.lock_groups_enabled(): uvp_args_final += ['-Q'] if in_debug_mode(): if self.prefs.seed > 0: uvp_args_final",
"process_result(self): overlap_detected = False outside_detected = False if self.invalid_faces_msg is not None: invalid_face_count",
"True def handle_event(self, event): # Kill the UVP process unconditionally if a hang",
"pack_mode.req_feature): raise RuntimeError('Selected packing mode is not supported in this engine edition') if",
"None: self.raiseUnexpectedOutputError() area = self.read_area(self.area_msg) self.prefs.stats_area = area self.set_status('INFO', 'Islands area: ' +",
"else: raise RuntimeError('Unexpected output from the connection thread') msg_received += 1 curr_time =",
"the UVP tab for details)' self.report({op_status_type}, op_status) self.prefs['op_warnings'] = self.op_warnings # self.prefs.stats_op_warnings.add(warning_msg) def",
"to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.SIMILARITY: uvp_args += ['-I', str(self.scene_props.similarity_threshold)] if self.prefs.pack_groups_together(self.scene_props): uvp_args += ['-U', str(self.scene_props.group_compactness)]",
"self.progress_msg = '' self.progress_sec_left = -1 self.progress_iter_done = -1 self.progress_last_update_time = 0.0 self.curr_phase",
"UVP2_OT_SimilarityDetectionHelp(UVP2_OT_Help): bl_label = 'Similarity Detection Help' bl_idname = 'uvpackmaster2.uv_similarity_detection_help' bl_description = \"Show help",
"- check the UVP tab for details)' self.report({op_status_type}, op_status) self.prefs['op_warnings'] = self.op_warnings #",
"islands which are similar are placed on top of each other. For more",
"a packing device') if not active_dev.supported: raise RuntimeError('Selected packing device is not supported",
"= force_read_int(msg) return True return False def handle_event_spec(self, event): if event.type == 'ESC':",
"packing device') if not active_dev.supported: raise RuntimeError('Selected packing device is not supported in",
"self.op_status_type if self.op_status_type is not None else 'INFO' op_status = self.op_status if len(self.op_warnings)",
"problem (if used in the operation).\") if outside_detected: self.add_warning(\"Some islands are outside their",
"return True elif msg_code == UvPackMessageCode.PACK_SOLUTION: pack_solution = read_pack_solution(msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) return True",
"again suitable for packing into a square texture. For for info regarding non-square",
"UDIM support\" URL_SUFFIX = \"udim-support\" class UVP2_OT_ManualGroupingHelp(UVP2_OT_Help): bl_label = 'Manual Grouping Help' bl_idname",
"None: self.raiseUnexpectedOutputError() self.invalid_faces_msg = msg elif msg_code == UvPackMessageCode.SIMILAR_ISLANDS: if self.similar_islands_msg is not",
"self.set_status('ERROR', str(ex)) cancel = True except Exception as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR',",
"'Non-Square Packing Help' bl_idname = 'uvpackmaster2.uv_nonsquare_packing_help' bl_description = \"Show help for non-square packing\"",
"in range(island_cnt): islands.append(read_int_array(islands_msg)) self.p_context.set_islands(selected_cnt, islands) def process_invalid_islands(self): if self.uvp_proc.returncode != UvPackerErrorCode.INVALID_ISLANDS: return if",
"process_result(self): if self.island_flags_msg is None: self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg) overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags)",
"def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.VALIDATE_UVS)] return uvp_args class UVP2_OT_ProcessSimilar(UVP2_OT_PackOperatorGeneric):",
"self.invalid_islands_msg = msg elif msg_code == UvPackMessageCode.ISLAND_FLAGS: if self.island_flags_msg is not None: self.raiseUnexpectedOutputError()",
"WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A",
"if self.hang_detected and event.type == 'ESC': raise OpAbortedException() if self.handle_event_spec(event): return # Generic",
"so islands which are similar are placed on top of each other. For",
"op_status) if overlap_detected: self.add_warning(\"Overlapping islands were detected after packing (check the selected islands).",
"not be selected. Click OK to continue' return '' def send_unselected_islands(self): return True",
"that it will be useful, # but WITHOUT ANY WARRANTY; without even the",
"of the GNU General Public License # along with this program; if not,",
"of invalid faces found is reported, invalid faces will not be selected. Click",
"= (False, False, True) else: self.p_context.context.tool_settings.uv_select_mode = 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) else: if",
"bl_label = 'Non-Square Packing Help' bl_idname = 'uvpackmaster2.uv_heuristic_search_help' bl_description = \"Show help for",
"if self.invalid_faces_msg is not None: invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces = read_int_array(self.invalid_faces_msg) if not",
"'Iter. done: {}. '.format(self.progress_iter_done) else: iter_str = '' if self.progress_sec_left >= 0: time_left_str",
"self.hang_detected: return 'Packer process not responding for a longer time (press ESC to",
"topology errors\" URL_SUFFIX = \"invalid-topology-issues\" class UVP2_OT_PixelMarginHelp(UVP2_OT_Help): bl_label = 'Pixel Margin Help' bl_idname",
"-1 self.progress_iter_done = -1 self.progress_last_update_time = 0.0 self.curr_phase = UvPackingPhaseCode.INITIALIZATION self.invalid_islands_msg = None",
"'Area measurement in progress (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_SELECTION: return",
"more info regarding similarity detection click the help button\" def get_confirmation_msg(self): if self.prefs.FEATURE_demo:",
"Texture' operator so islands are again suitable for packing into a square texture.",
"context, event): self.interactive = True self.prefs = get_prefs() self.scene_props = context.scene.uvp2_props self.confirmation_msg =",
"False def lock_groups_enabled(self): return False def send_verts_3d(self): return False def read_area(self, area_msg): return",
"02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### import subprocess import",
"= msg elif msg_code == UvPackMessageCode.AREA: if self.area_msg is not None: self.raiseUnexpectedOutputError() self.area_msg",
"process_result(self): if self.area_msg is None: self.raiseUnexpectedOutputError() area = self.read_area(self.area_msg) self.prefs.stats_area = area self.set_status('INFO',",
"retcode if retcode in {UvPackerErrorCode.SUCCESS, UvPackerErrorCode.INVALID_ISLANDS, UvPackerErrorCode.NO_SPACE, UvPackerErrorCode.PRE_VALIDATION_FAILED}: return if retcode == UvPackerErrorCode.CANCELLED:",
"self.last_msg_time > self.hang_timeout: self.hang_detected = True def handle_event(self, event): # Kill the UVP",
"self.prefs.FEATURE_demo: if len(similar_islands) != similar_island_count: self.raiseUnexpectedOutputError() for island_idx in similar_islands: self.p_context.select_island_faces(island_idx, self.p_context.uv_island_faces_list[island_idx], True)",
"islands aligning (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.RENDER_PRESENTATION: return 'Close the",
"self.send_verts_3d() selected_cnt, unselected_cnt = self.p_context.serialize_uv_maps(send_unselected, send_groups, send_rot_step, send_lock_groups, send_verts_3d, self.get_group_method() if send_groups else",
"invoke(self, context, event): self.interactive = True self.prefs = get_prefs() self.scene_props = context.scene.uvp2_props self.confirmation_msg",
"implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the",
"after packing (check the selected islands). This usually happens when 'Pixel Padding' is",
"uvp_args += ['-M', str(self.scene_props.pixel_margin)] uvp_args += ['-y', str(self.prefs.pixel_margin_tex_size(self.scene_props, self.p_context.context))] if self.prefs.pixel_padding_enabled(self.scene_props): uvp_args +=",
"invalid faces found: ' + str(invalid_face_count)) else: self.set_status('INFO', 'No invalid faces found') def",
"None: self.prefs.stats_area = self.area if self.uvp_proc.returncode == UvPackerErrorCode.NO_SPACE: op_status = 'Packing stopped -",
"self.scene_props.fixed_scale_strategy] if self.prefs.FEATURE_island_rotation: if self.scene_props.rot_enable: rot_step_value = self.scene_props.rot_step if self.scene_props.prerot_disable: uvp_args += ['-w']",
"self.invalid_islands_msg is None: self.raiseUnexpectedOutputError() code = force_read_int(self.invalid_islands_msg) subcode = force_read_int(self.invalid_islands_msg) invalid_islands = read_int_array(self.invalid_islands_msg)",
"self.op_status = status def add_warning(self, warn_msg): self.op_warnings.append(warn_msg) def report_status(self): if self.op_status is not",
"uvp_args_final.append('-s') if self.grouping_enabled(): uvp_args_final += ['-a', str(to_uvp_group_method(self.get_group_method()))] if self.send_rot_step(): uvp_args_final += ['-R'] if",
"which are already selected. For more info regarding similarity detection click the help",
"will not be selected. Click OK to continue' return '' def send_unselected_islands(self): return",
"(1.0 / ratio, 1.0) class UVP2_OT_UndoIslandsAdjustemntToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_undo_islands_adjustment_to_texture' bl_label = 'Undo Islands",
"+= ['-l', self.scene_props.lock_overlapping_mode] if self.prefs.pack_to_others_enabled(self.scene_props): uvp_args += ['-x'] if self.prefs.FEATURE_validation and self.scene_props.pre_validate: uvp_args.append('-v')",
"= 'Invalid Topology Help' bl_idname = 'uvpackmaster2.uv_invalid_topology_help' bl_description = \"Show help for handling",
"self.set_status('INFO', 'Packer process killed') cancel = True except OpCancelledException: self.set_status('INFO', 'Operation cancelled by",
"self.prefs.target_box(self.scene_props) if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) if self.pack_ratio != 1.0: uvp_args += ['-q',",
"= None self.islands_metadata_msg = None except NoUvFaceError as ex: self.set_status('WARNING', str(ex)) cancel =",
"the hope that it will be useful, # but WITHOUT ANY WARRANTY; without",
"used in the operation).\") if outside_detected: self.add_warning(\"Some islands are outside their packing box",
"with grouping by similarity\") if not self.scene_props.rot_enable: raise RuntimeError(\"Island rotations must be enabled",
"self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) uvp_args += ['-q', str(self.pack_ratio)] return uvp_args class UVP2_OT_SelectSimilar(UVP2_OT_ProcessSimilar): bl_idname",
"if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', 'Unexpected error') cancel = True if cancel: return self.cancel(context)",
"* from .prefs import * from .os_iface import * from .island_params import *",
"if self.grouping_enabled(): uvp_args_final += ['-a', str(to_uvp_group_method(self.get_group_method()))] if self.send_rot_step(): uvp_args_final += ['-R'] if self.lock_groups_enabled():",
"if self.area is not None: end_str = '(press ESC to apply result) '",
"self.progress_last_update_time = 0.0 self.curr_phase = UvPackingPhaseCode.INITIALIZATION self.invalid_islands_msg = None self.island_flags_msg = None self.pack_solution_msg",
"None: invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces = read_int_array(self.invalid_faces_msg) if not self.prefs.FEATURE_demo: if len(invalid_faces) !=",
"bl_description = \"Align selected islands, so islands which are similar are placed on",
"self.scene_props.group_method def send_rot_step(self): return self.prefs.FEATURE_island_rotation_step and self.scene_props.rot_enable and self.scene_props.island_rot_step_enable def lock_groups_enabled(self): return self.prefs.FEATURE_lock_overlapping",
"cancel)' if self.curr_phase == UvPackingPhaseCode.AREA_MEASUREMENT: return 'Area measurement in progress (press ESC to",
"+= ['-N', str(self.scene_props.pixel_padding)] uvp_args += ['-W', self.scene_props.pixel_margin_method] uvp_args += ['-Y', str(self.scene_props.pixel_margin_adjust_time)] if self.prefs.fixed_scale_enabled(self.scene_props):",
"cancel)' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_ANALYSIS: return \"Topology analysis: {:3}% (press ESC to cancel)\".format(self.progress_array[0])",
"'Similar islands found: ' + str(similar_island_count)) class UVP2_OT_AlignSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_align_similar' bl_label =",
"selected. Click OK to continue' return '' def process_result(self): if self.invalid_faces_msg is None:",
"return self.prefs.pack_to_others_enabled(self.scene_props) def grouping_enabled(self): return self.prefs.grouping_enabled(self.scene_props) def get_group_method(self): return self.scene_props.group_method def send_rot_step(self): return",
"# self.prefs.stats_op_warnings.add(warning_msg) def exit_common(self): if self.interactive: wm = self.p_context.context.window_manager wm.event_timer_remove(self._timer) self.p_context.update_meshes() self.report_status() if",
"'' if self.progress_iter_done >= 0: iter_str = 'Iter. done: {}. '.format(self.progress_iter_done) else: iter_str",
"= 'Pack' bl_description = 'Pack selected UV islands' def __init__(self): self.cancel_sig_sent = False",
"self.area is not None: self.prefs.stats_area = self.area if self.uvp_proc.returncode == UvPackerErrorCode.NO_SPACE: op_status =",
"the 'Precision' parameter. Sometimes increasing the 'Adjustment Time' may solve the problem (if",
"0.0)), Vector((self.pack_ratio, 1.0))) if self.target_box is not None: uvp_args += ['-B', self.get_target_box_string(self.target_box)] uvp_args.append('-b')",
"= '' for prog in self.progress_array: percent_progress_str += str(prog).rjust(3, ' ') + '%,",
"to group by similarity\") if self.scene_props.prerot_disable: raise RuntimeError(\"'Pre-Rotation Disable' option must be off",
"packing\" URL_SUFFIX = \"non-square-packing\" class UVP2_OT_SimilarityDetectionHelp(UVP2_OT_Help): bl_label = 'Similarity Detection Help' bl_idname =",
"(False, False, True) else: self.p_context.context.tool_settings.uv_select_mode = 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) else: if len(invalid_faces)",
"edition') if self.grouping_enabled(): if self.get_group_method() == UvGroupingMethod.SIMILARITY.code: if self.prefs.pack_to_others_enabled(self.scene_props): raise RuntimeError(\"'Pack To Others'",
"def read_islands(self, islands_msg): islands = [] island_cnt = force_read_int(islands_msg) selected_cnt = force_read_int(islands_msg) for",
"uvp_args += ['-i', str(self.scene_props.precision)] uvp_args += ['-r', str(90)] if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context)",
"return 'WARNING: in the demo mode only the number of similar islands found",
"stats = self.prefs.stats_array.add() dev_name_len = force_read_int(msg) stats.dev_name = msg.read(dev_name_len).decode('ascii') stats.iter_count = force_read_int(msg) stats.total_time",
"invalid_face_count: self.raiseUnexpectedOutputError() if invalid_face_count > 0: # Switch to the face selection mode",
"Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #",
"self.pack_solution_msg is None: self.raiseUnexpectedOutputError() pack_solution = read_pack_solution(self.pack_solution_msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) self.set_status('INFO', 'Islands aligned') class",
"found: ' + str(similar_island_count)) class UVP2_OT_AlignSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_align_similar' bl_label = 'Align Similar'",
"A PARTICULAR PURPOSE. See the # GNU General Public License for more details.",
"import * from .island_params import * from .labels import UvpLabels from .register import",
"3) class UVP2_OT_PackOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_pack' bl_label = 'Pack' bl_description = 'Pack selected",
"+ str(similar_island_count)) class UVP2_OT_AlignSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_align_similar' bl_label = 'Align Similar' bl_description =",
"Software Foundation; either version 2 # of the License, or (at your option)",
"UvPackMessageCode.ISLAND_FLAGS: if self.island_flags_msg is not None: self.raiseUnexpectedOutputError() self.island_flags_msg = msg elif msg_code ==",
"def handle_event(self, event): # Kill the UVP process unconditionally if a hang was",
"under the terms of the GNU General Public License # as published by",
"the UVP process unconditionally if a hang was detected if self.hang_detected and event.type",
"uvp_args_final += ['-a', str(to_uvp_group_method(self.get_group_method()))] if self.send_rot_step(): uvp_args_final += ['-R'] if self.lock_groups_enabled(): uvp_args_final +=",
"self.islands_metadata_msg = None except NoUvFaceError as ex: self.set_status('WARNING', str(ex)) cancel = True except",
"str(tiles_in_row)] if self.grouping_enabled(): if to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.SIMILARITY: uvp_args += ['-I', str(self.scene_props.similarity_threshold)] if self.prefs.pack_groups_together(self.scene_props):",
"False finish = False try: try: self.handle_event(event) # Check whether the uvp process",
"with this program; if not, write to the Free Software Foundation, # Inc.,",
"import bpy import mathutils import tempfile class InvalidIslandsError(Exception): pass class NoUvFaceError(Exception): pass class",
"as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', 'Unexpected error') cancel = True if cancel:",
"= None self.pack_ratio = 1.0 self.target_box = None self.op_status_type = None self.op_status =",
"raise RuntimeError(\"UVP engine broken\") reset_stats(self.prefs) self.p_context = PackContext(context) self.pre_op_initialize() send_unselected = self.send_unselected_islands() send_rot_step",
"in the packing box\") if retcode == UvPackerErrorCode.MAX_GROUP_COUNT_EXCEEDED: raise RuntimeError(\"Maximal group count exceeded\")",
"new_progress_msg self.report({'INFO'}, self.progress_msg) def handle_uvp_msg(self, msg): msg_code = force_read_int(msg) if self.handle_uvp_msg_spec(msg_code, msg): return",
"if self.prefs.seed > 0: uvp_args_final += ['-S', str(self.prefs.seed)] if self.prefs.wait_for_debugger: uvp_args_final.append('-G') uvp_args_final +=",
"option) any later version. # # This program is distributed in the hope",
"'Unexpected error') self.p_context.update_meshes() return {'FINISHED'} def get_scale_factors(self): return (1.0, 1.0) class UVP2_OT_AdjustIslandsToTexture(UVP2_OT_ScaleIslands): bl_idname",
"cancel = True except RuntimeError as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', str(ex)) cancel",
"help for handling invalid topology errors\" URL_SUFFIX = \"invalid-topology-issues\" class UVP2_OT_PixelMarginHelp(UVP2_OT_Help): bl_label =",
"uvp_args += ['-U', str(self.scene_props.group_compactness)] if self.prefs.multi_device_enabled(self.scene_props): uvp_args.append('-u') if self.prefs.lock_overlap_enabled(self.scene_props): uvp_args += ['-l', self.scene_props.lock_overlapping_mode]",
"if self.curr_phase == UvPackingPhaseCode.RENDER_PRESENTATION: return 'Close the demo window to finish' if self.curr_phase",
"is None: return False progress_msg_spec = self.get_progress_msg_spec() if progress_msg_spec: return progress_msg_spec if self.curr_phase",
"similarity detection click the help button\" def get_uvp_opcode(self): return UvPackerOpcode.ALIGN_SIMILAR def process_result(self): if",
"get_progress_msg(self): if self.hang_detected: return 'Packer process not responding for a longer time (press",
"return 'Area measurement in progress (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_SELECTION:",
"self.prefs.stats_area = self.area if self.uvp_proc.returncode == UvPackerErrorCode.NO_SPACE: op_status = 'Packing stopped - no",
"(check the selected islands). Consider increasing the 'Precision' parameter. Sometimes increasing the 'Adjustment",
"# along with this program; if not, write to the Free Software Foundation,",
"raiseUnexpectedOutputError(self): raise RuntimeError('Unexpected output from the pack process') def set_status(self, status_type, status): self.op_status_type",
"!= invalid_face_count: self.raiseUnexpectedOutputError() if invalid_face_count > 0: # Switch to the face selection",
"to cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.VALIDATION: return \"Per-face overlap check: {:3}% (press ESC",
"this engine edition') # Validate pack mode pack_mode = UvPackingMode.get_mode(self.scene_props.pack_mode) if pack_mode.req_feature !=",
"similar_island_count: self.raiseUnexpectedOutputError() for island_idx in similar_islands: self.p_context.select_island_faces(island_idx, self.p_context.uv_island_faces_list[island_idx], True) else: if len(similar_islands) >",
"is not long enough.\") def validate_pack_params(self): active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array)",
"UvPackerErrorCode.NO_VALID_STATIC_ISLAND: raise RuntimeError(\"'Pack To Others' option enabled, but no unselected island found in",
"else: self.set_status('INFO', 'No overlapping islands detected') def validate_pack_params(self): pass def get_uvp_args(self): uvp_args =",
"supported\") if retcode == UvPackerErrorCode.DEVICE_DOESNT_SUPPORT_GROUPS_TOGETHER: raise RuntimeError(\"Selected device doesn't support packing groups together\")",
"not self.op_done and self.uvp_proc.poll() is not None: # It should not be required",
"progress (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_SELECTION: return 'Searching for similar",
"self.p_context.context.tool_settings.mesh_select_mode = (False, False, True) else: self.p_context.context.tool_settings.uv_select_mode = 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) if",
"if self.grouping_enabled(): if self.get_group_method() == UvGroupingMethod.SIMILARITY.code: if self.prefs.pack_to_others_enabled(self.scene_props): raise RuntimeError(\"'Pack To Others' is",
"def invoke(self, context, event): self.interactive = True self.prefs = get_prefs() self.scene_props = context.scene.uvp2_props",
"self.scene_props.lock_groups_enable def send_verts_3d(self): return self.scene_props.normalize_islands def get_progress_msg_spec(self): if self.curr_phase in { UvPackingPhaseCode.PACKING, UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT",
"+= ['-O'] uvp_args += ['-F', self.scene_props.fixed_scale_strategy] if self.prefs.FEATURE_island_rotation: if self.scene_props.rot_enable: rot_step_value = self.scene_props.rot_step",
"return (1.0 / ratio, 1.0) class UVP2_OT_UndoIslandsAdjustemntToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_undo_islands_adjustment_to_texture' bl_label = 'Undo",
"not None: self.prefs['op_status'] = self.op_status op_status_type = self.op_status_type if self.op_status_type is not None",
"uvp_args_final)) creation_flags = os_uvp_creation_flags() popen_args = dict() if creation_flags is not None: popen_args['creationflags']",
"demo mode only the number of similar islands found is reported, islands will",
"box after packing (check the selected islands). This usually happens when 'Pixel Padding'",
"other. For more info regarding similarity detection click the help button\" def get_uvp_opcode(self):",
"msg_code, msg): return False def handle_event_spec(self, event): return False def handle_progress_msg(self): if self.op_done:",
"modify it under the terms of the GNU General Public License # as",
"uvp_args += ['-h', str(self.scene_props.heuristic_search_time), '-j', str(self.scene_props.heuristic_max_wait_time)] if self.prefs.FEATURE_advanced_heuristic and self.scene_props.advanced_heuristic: uvp_args.append('-H') uvp_args +=",
"= \"Invalid topology encountered in the selected islands. Check the Help panel to",
"self.curr_phase == UvPackingPhaseCode.VALIDATION: return \"Per-face overlap check: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) raise",
"{'RUNNING_MODAL'} class FakeTimerEvent: def __init__(self): self.type = 'TIMER' self.value = 'NOTHING' self.ctrl =",
"= True return True return False def process_result(self): overlap_detected = False outside_detected =",
"RuntimeError(item) elif isinstance(item, io.BytesIO): self.handle_uvp_msg(item) else: raise RuntimeError('Unexpected output from the connection thread')",
"import * from .pack_context import * from .connection import * from .prefs import",
"str(self.scene_props.precision), '-m', str(self.scene_props.margin)] uvp_args += ['-d', self.prefs.dev_array[self.prefs.sel_dev_idx].id] if self.prefs.pixel_margin_enabled(self.scene_props): uvp_args += ['-M', str(self.scene_props.pixel_margin)]",
"str(invalid_face_count)) else: self.set_status('INFO', 'No invalid faces found') def validate_pack_params(self): pass def get_uvp_args(self): uvp_args",
"uvp_args += ['-B', self.get_target_box_string(self.target_box)] uvp_args.append('-b') return uvp_args class UVP2_OT_OverlapCheckOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_overlap_check' bl_label",
"{'RUNNING_MODAL'} if not self.op_done else {'PASS_THROUGH'} def pre_op_initialize(self): pass def execute(self, context): cancel",
"self.uvp_proc.terminate() # self.progress_thread.terminate() self.exit_common() return {'FINISHED'} def get_progress_msg_spec(self): return False def get_progress_msg(self): if",
"finish' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_VALIDATION: return \"Topology validation: {:3}% (press ESC to cancel)\".format(self.progress_array[0])",
"raise RuntimeError(\"Maximal group count exceeded\") if retcode == UvPackerErrorCode.DEVICE_NOT_SUPPORTED: raise RuntimeError(\"Selected device is",
"'-m', str(self.scene_props.margin)] uvp_args += ['-d', self.prefs.dev_array[self.prefs.sel_dev_idx].id] if self.prefs.pixel_margin_enabled(self.scene_props): uvp_args += ['-M', str(self.scene_props.pixel_margin)] uvp_args",
"queue.Empty as ex: break if isinstance(item, str): raise RuntimeError(item) elif isinstance(item, io.BytesIO): self.handle_uvp_msg(item)",
"it should finish if self.curr_phase == UvPackingPhaseCode.DONE: self.handle_op_done() elif msg_code == UvPackMessageCode.INVALID_ISLANDS: if",
"islands' def process_result(self): if self.area_msg is None: self.raiseUnexpectedOutputError() area = self.read_area(self.area_msg) self.prefs.stats_area =",
"== 'Darwin': active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None if active_dev",
"class UVP2_OT_Help(bpy.types.Operator): bl_label = 'Help' def execute(self, context): webbrowser.open(UvpLabels.HELP_BASEURL + self.URL_SUFFIX) return {'FINISHED'}",
"the connection thread') msg_received += 1 curr_time = time.time() if msg_received > 0:",
"else: if len(invalid_faces) > 0: self.raiseUnexpectedOutputError() if invalid_face_count > 0: self.set_status('WARNING', 'Number of",
"return True def get_uvp_opcode(self): return UvPackerOpcode.SELECT_SIMILAR def process_result(self): if self.similar_islands_msg is None: self.raiseUnexpectedOutputError()",
"get_uvp_args(self): uvp_args = ['-o', str(self.get_uvp_opcode()), '-I', str(self.scene_props.similarity_threshold)] uvp_args += ['-i', str(self.scene_props.precision)] uvp_args +=",
"Click OK to continue' return '' def send_unselected_islands(self): return True def get_uvp_opcode(self): return",
"to pack all islands' self.add_warning(\"Overlap check was performed only on the islands which",
"True) else: if len(invalid_faces) > 0: self.raiseUnexpectedOutputError() if invalid_face_count > 0: self.set_status('WARNING', 'Number",
"is not supported in this engine edition') # Validate pack mode pack_mode =",
"bl_description = \"Show help for setting margin in pixels\" URL_SUFFIX = \"pixel-margin\" class",
"= {'UNDO'} @classmethod def poll(cls, context): return context.active_object is not None and context.active_object.mode",
"by the 'Adjust Islands To Texture' operator so islands are again suitable for",
"msg_code == UvPackMessageCode.ISLANDS_METADATA: if self.islands_metadata_msg is not None: self.raiseUnexpectedOutputError() self.islands_metadata_msg = msg else:",
"[] island_cnt = force_read_int(islands_msg) selected_cnt = force_read_int(islands_msg) for i in range(island_cnt): islands.append(read_int_array(islands_msg)) self.p_context.set_islands(selected_cnt,",
"Number of invalid faces found: ' + str(invalid_face_count) + '. Packing aborted') return",
"islands which are already selected. For more info regarding similarity detection click the",
"'Adjustment Time' is not long enough.\") def validate_pack_params(self): active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx",
"operator should be used only when packing to a non-square texture. For for",
"= msg elif msg_code == UvPackMessageCode.INVALID_FACES: if self.invalid_faces_msg is not None: self.raiseUnexpectedOutputError() self.invalid_faces_msg",
"pack all islands' self.add_warning(\"Overlap check was performed only on the islands which were",
"bl_idname = 'uvpackmaster2.uv_udim_support_help' bl_description = \"Show help for UDIM support\" URL_SUFFIX = \"udim-support\"",
"'uvpackmaster2.uv_select_similar' bl_label = 'Select Similar' bl_description = \"Selects all islands which have similar",
"def draw(self, context): layout = self.layout col = layout.column() col.label(text=self.confirmation_msg) def get_confirmation_msg(self): return",
"None: self.raiseUnexpectedOutputError() code = force_read_int(self.invalid_islands_msg) subcode = force_read_int(self.invalid_islands_msg) invalid_islands = read_int_array(self.invalid_islands_msg) if len(invalid_islands)",
"self.progress_sec_left >= 0: time_left_str = \"Time left: {} sec. \".format(self.progress_sec_left) else: time_left_str =",
"not None: self.raiseUnexpectedOutputError() self.invalid_islands_msg = msg elif msg_code == UvPackMessageCode.ISLAND_FLAGS: if self.island_flags_msg is",
"and self.scene_props.rot_enable and self.scene_props.island_rot_step_enable def lock_groups_enabled(self): return self.prefs.FEATURE_lock_overlapping and self.scene_props.lock_groups_enable def send_verts_3d(self): return",
"(Vector((0.0, 0.0)), Vector((self.pack_ratio, 1.0))) if self.target_box is not None: uvp_args += ['-B', self.get_target_box_string(self.target_box)]",
"if self.invalid_islands_msg is not None: self.raiseUnexpectedOutputError() self.invalid_islands_msg = msg elif msg_code == UvPackMessageCode.ISLAND_FLAGS:",
"To Others' option enabled, but no unselected island found in the packing box\")",
"force_read_int(msg) stats.dev_name = msg.read(dev_name_len).decode('ascii') stats.iter_count = force_read_int(msg) stats.total_time = force_read_int(msg) stats.avg_time = force_read_int(msg)",
"not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth",
"bl_description = 'Validate selected UV faces. The validation procedure looks for invalid UV",
"self.scene_props.pre_validate: uvp_args.append('-v') if self.prefs.normalize_islands_enabled(self.scene_props): uvp_args.append('-L') if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: self.target_box = self.prefs.target_box(self.scene_props) if",
"if send_unselected: uvp_args_final.append('-s') if self.grouping_enabled(): uvp_args_final += ['-a', str(to_uvp_group_method(self.get_group_method()))] if self.send_rot_step(): uvp_args_final +=",
"active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None if active_dev is not",
"'Validate selected UV faces. The validation procedure looks for invalid UV faces i.e.",
"self.hang_timeout: self.hang_detected = True def handle_event(self, event): # Kill the UVP process unconditionally",
"if self.prefs.pack_groups_together(self.scene_props): uvp_args += ['-U', str(self.scene_props.group_compactness)] if self.prefs.multi_device_enabled(self.scene_props): uvp_args.append('-u') if self.prefs.lock_overlap_enabled(self.scene_props): uvp_args +=",
"False, True) else: self.p_context.context.tool_settings.uv_select_mode = 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) else: if len(invalid_faces) >",
"invalid_islands = read_int_array(self.invalid_islands_msg) if len(invalid_islands) == 0: self.raiseUnexpectedOutputError() self.p_context.handle_invalid_islands(invalid_islands) if code == UvInvalidIslandCode.TOPOLOGY:",
"str): raise RuntimeError(item) elif isinstance(item, io.BytesIO): self.handle_uvp_msg(item) else: raise RuntimeError('Unexpected output from the",
"terms of the GNU General Public License # as published by the Free",
"= dict() if creation_flags is not None: popen_args['creationflags'] = creation_flags self.uvp_proc = subprocess.Popen(uvp_args_final,",
"True return False def handle_event_spec(self, event): if event.type == 'ESC': if not self.cancel_sig_sent:",
"if op_status_type == 'INFO': op_status_type = 'WARNING' op_status += '. (WARNINGS were reported",
"msg_code == UvPackMessageCode.INVALID_FACES: if self.invalid_faces_msg is not None: self.raiseUnexpectedOutputError() self.invalid_faces_msg = msg elif",
"None: self.raiseUnexpectedOutputError() self.islands_metadata_msg = msg else: self.raiseUnexpectedOutputError() def handle_communication(self): if self.op_done: return msg_received",
"{'PASS_THROUGH'} def pre_op_initialize(self): pass def execute(self, context): cancel = False self.op_done = False",
"face selected') else: if selected_cnt + unselected_cnt == 0: raise NoUvFaceError('No UV face",
"msg_refresh_interval = 2.0 new_progress_msg = self.get_progress_msg() if not new_progress_msg: return now = time.time()",
"UVP tab for details)' self.report({op_status_type}, op_status) self.prefs['op_warnings'] = self.op_warnings # self.prefs.stats_op_warnings.add(warning_msg) def exit_common(self):",
"None self.prefs = get_prefs() self.scene_props = context.scene.uvp2_props self.p_context = None self.pack_ratio = 1.0",
"= ['-o', str(UvPackerOpcode.VALIDATE_UVS)] return uvp_args class UVP2_OT_ProcessSimilar(UVP2_OT_PackOperatorGeneric): def validate_pack_params(self): pass def get_uvp_args(self): uvp_args",
"not None: self.uvp_proc.terminate() self.report_status() return {'FINISHED'} if self.interactive: wm = context.window_manager self._timer =",
"while True: try: item = self.progress_queue.get_nowait() except queue.Empty as ex: break if isinstance(item,",
"ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', str(ex)) cancel = True except Exception as ex:",
"as published by the Free Software Foundation; either version 2 # of the",
"Help' bl_idname = 'uvpackmaster2.uv_island_rot_step_help' bl_description = \"Show help for setting rotation step on",
"UvPackingPhaseCode.INITIALIZATION self.invalid_islands_msg = None self.island_flags_msg = None self.pack_solution_msg = None self.area_msg = None",
"def pre_op_initialize(self): pass def execute(self, context): cancel = False self.op_done = False self.uvp_proc",
"UvPackerErrorCode.INVALID_ISLANDS: return if self.invalid_islands_msg is None: self.raiseUnexpectedOutputError() code = force_read_int(self.invalid_islands_msg) subcode = force_read_int(self.invalid_islands_msg)",
"pix_per_char = 5 dialog_width = pix_per_char * len(self.confirmation_msg) + 50 return wm.invoke_props_dialog(self, width=dialog_width)",
"send_verts_3d(self): return self.scene_props.normalize_islands def get_progress_msg_spec(self): if self.curr_phase in { UvPackingPhaseCode.PACKING, UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT }: if",
"raise RuntimeError('Packer process died unexpectedly') self.handle_progress_msg() except OpFinishedException: finish = True except: raise",
"return self.scene_props.normalize_islands def get_progress_msg_spec(self): if self.curr_phase in { UvPackingPhaseCode.PACKING, UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT }: if self.curr_phase",
"if self.pack_ratio != 1.0: uvp_args += ['-q', str(self.pack_ratio)] if self.target_box is not None:",
"[] try: if not check_uvp(): unregister_uvp() redraw_ui(context) raise RuntimeError(\"UVP engine broken\") reset_stats(self.prefs) self.p_context",
"= 'UVP Setup Help' bl_idname = 'uvpackmaster2.uv_uvp_setup_help' bl_description = \"Show help for UVP",
"check_uvp, unregister_uvp import bmesh import bpy import mathutils import tempfile class InvalidIslandsError(Exception): pass",
"str(self.scene_props.similarity_threshold)] if self.prefs.pack_groups_together(self.scene_props): uvp_args += ['-U', str(self.scene_props.group_compactness)] if self.prefs.multi_device_enabled(self.scene_props): uvp_args.append('-u') if self.prefs.lock_overlap_enabled(self.scene_props): uvp_args",
"'Measure area of selected UV islands' def process_result(self): if self.area_msg is None: self.raiseUnexpectedOutputError()",
"the demo window to finish' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_VALIDATION: return \"Topology validation: {:3}%",
"self.cancel_sig_sent = False self.area = None def get_confirmation_msg(self): if platform.system() == 'Darwin': active_dev",
"is None: self.raiseUnexpectedOutputError() invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces = read_int_array(self.invalid_faces_msg) if not self.prefs.FEATURE_demo: if",
"if self.area_msg is not None: self.raiseUnexpectedOutputError() self.area_msg = msg elif msg_code == UvPackMessageCode.INVALID_FACES:",
"cancel = False self.op_done = False self.uvp_proc = None self.prefs = get_prefs() self.scene_props",
"self.scene_props.island_rot_step_enable def lock_groups_enabled(self): return self.prefs.FEATURE_lock_overlapping and self.scene_props.lock_groups_enable def send_verts_3d(self): return self.scene_props.normalize_islands def get_progress_msg_spec(self):",
"for prog in self.progress_array: percent_progress_str += str(prog).rjust(3, ' ') + '%, ' percent_progress_str",
"ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.VALIDATION: return \"Per-face overlap check: {:3}% (press",
"\"Show help for heuristic search\" URL_SUFFIX = \"heuristic-search\" class UVP2_OT_NonSquarePackingHelp(UVP2_OT_Help): bl_label = 'Non-Square",
"0.0 self.curr_phase = UvPackingPhaseCode.INITIALIZATION self.invalid_islands_msg = None self.island_flags_msg = None self.pack_solution_msg = None",
"if not self.scene_props.rot_enable: raise RuntimeError(\"Island rotations must be enabled in order to group",
"1.0))) if self.target_box is not None: uvp_args += ['-B', self.get_target_box_string(self.target_box)] uvp_args.append('-b') return uvp_args",
"cancelled by the user') cancel = True except InvalidIslandsError as err: self.set_status('ERROR', str(err))",
"if cancel: if self.uvp_proc is not None: self.uvp_proc.terminate() self.report_status() return {'FINISHED'} if self.interactive:",
"a square texture. For for info regarding non-square packing read the documentation\" def",
"self.p_context.context) if self.prefs.pack_to_tiles(self.scene_props): uvp_args += ['-V', str(tile_count)] if self.prefs.tiles_enabled(self.scene_props): uvp_args += ['-C', str(tiles_in_row)]",
"bl_idname = 'uvpackmaster2.uv_select_similar' bl_label = 'Select Similar' bl_description = \"Selects all islands which",
"the safe side self.handle_communication() if not self.op_done: # Special value indicating a crash",
"self.area_msg = msg elif msg_code == UvPackMessageCode.INVALID_FACES: if self.invalid_faces_msg is not None: self.raiseUnexpectedOutputError()",
"context.active_object is not None and context.active_object.mode == 'EDIT' def check_uvp_retcode(self, retcode): self.prefs.uvp_retcode =",
"' + str(similar_island_count)) class UVP2_OT_AlignSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_align_similar' bl_label = 'Align Similar' bl_description",
"for UDIM support\" URL_SUFFIX = \"udim-support\" class UVP2_OT_ManualGroupingHelp(UVP2_OT_Help): bl_label = 'Manual Grouping Help'",
"not None else 'INFO' op_status = self.op_status if len(self.op_warnings) > 0: if op_status_type",
"force_read_int(msg) return True return False def handle_event_spec(self, event): if event.type == 'ESC': if",
"General Public License for more details. # # You should have received a",
"should be used only when packing to a non-square texture. For for info",
"and self.scene_props.island_rot_step_enable def lock_groups_enabled(self): return self.prefs.FEATURE_lock_overlapping and self.scene_props.lock_groups_enable def send_verts_3d(self): return self.scene_props.normalize_islands def",
"'UDIM Support Help' bl_idname = 'uvpackmaster2.uv_udim_support_help' bl_description = \"Show help for UDIM support\"",
"0: raise NoUvFaceError('No UV face selected') else: if selected_cnt + unselected_cnt == 0:",
"RuntimeError('Pack process returned an error') def raiseUnexpectedOutputError(self): raise RuntimeError('Unexpected output from the pack",
"the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See",
"area close to 0, self-intersecting faces, faces overlapping each other' def get_confirmation_msg(self): if",
"= \"Adjust scale of selected islands so they are suitable for packing into",
"lock_groups_enabled(self): return False def send_verts_3d(self): return False def read_area(self, area_msg): return round(force_read_float(area_msg) /",
"prec), round(target_box[0].y, prec), round(target_box[1].x, prec), round(target_box[1].y, prec)) def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.PACK),",
"self.p_context.uv_island_faces_list[island_idx], True) else: if len(similar_islands) > 0: self.raiseUnexpectedOutputError() self.set_status('INFO', 'Similar islands found: '",
"0: self.raiseUnexpectedOutputError() self.p_context.handle_invalid_islands(invalid_islands) if code == UvInvalidIslandCode.TOPOLOGY: error_msg = \"Invalid topology encountered in",
"None: op_status += ', packed islands area: ' + str(self.area) self.set_status('INFO', op_status) if",
"if retcode == UvPackerErrorCode.MAX_GROUP_COUNT_EXCEEDED: raise RuntimeError(\"Maximal group count exceeded\") if retcode == UvPackerErrorCode.DEVICE_NOT_SUPPORTED:",
"time.sleep(self.MODAL_INTERVAL_S) def invoke(self, context, event): self.interactive = True self.prefs = get_prefs() self.scene_props =",
"def process_invalid_islands(self): if self.uvp_proc.returncode != UvPackerErrorCode.INVALID_ISLANDS: return if self.invalid_islands_msg is None: self.raiseUnexpectedOutputError() code",
"inconsistent {} values found in the selected islands\".format(param_array[subcode].NAME) else: self.raiseUnexpectedOutputError() raise InvalidIslandsError(error_msg) def",
"option must be off in order to group by similarity\") if self.prefs.FEATURE_target_box and",
"signal import webbrowser from .utils import * from .pack_context import * from .connection",
"import * from .prefs import * from .os_iface import * from .island_params import",
"uvp_args += ['-I', str(self.scene_props.similarity_threshold)] if self.prefs.pack_groups_together(self.scene_props): uvp_args += ['-U', str(self.scene_props.group_compactness)] if self.prefs.multi_device_enabled(self.scene_props): uvp_args.append('-u')",
"'WARNING: in the demo mode only the number of similar islands found is",
"None: return False progress_msg_spec = self.get_progress_msg_spec() if progress_msg_spec: return progress_msg_spec if self.curr_phase ==",
"UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT }: if self.curr_phase == UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT: header_str = 'Pixel margin adjustment. ' elif",
"self.scene_props = context.scene.uvp2_props self.p_context = None self.pack_ratio = 1.0 self.target_box = None self.op_status_type",
"getattr(self.prefs, 'FEATURE_' + pack_mode.req_feature): raise RuntimeError('Selected packing mode is not supported in this",
"= 'uvpackmaster2.uv_heuristic_search_help' bl_description = \"Show help for heuristic search\" URL_SUFFIX = \"heuristic-search\" class",
"def execute(self, context): cancel = False self.op_done = False self.uvp_proc = None self.prefs",
"= [] island_cnt = force_read_int(islands_msg) selected_cnt = force_read_int(islands_msg) for i in range(island_cnt): islands.append(read_int_array(islands_msg))",
"None and active_dev.id.startswith('cuda'): return UvpLabels.CUDA_MACOS_CONFIRM_MSG if self.prefs.pack_groups_together(self.scene_props) and not self.prefs.heuristic_enabled(self.scene_props): return UvpLabels.GROUPS_TOGETHER_CONFIRM_MSG return",
"not self.op_done else {'PASS_THROUGH'} def pre_op_initialize(self): pass def execute(self, context): cancel = False",
"msg elif msg_code == UvPackMessageCode.PACK_SOLUTION: if self.pack_solution_msg is not None: self.raiseUnexpectedOutputError() self.pack_solution_msg =",
"if self.area is not None else 'none') else: header_str = '' if self.progress_iter_done",
"msg_code == UvPackMessageCode.AREA: self.area = self.read_area(msg) return True elif msg_code == UvPackMessageCode.PACK_SOLUTION: pack_solution",
"str(area)) def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.MEASURE_AREA)] return uvp_args class",
"str(self.area) self.set_status('INFO', op_status) if overlap_detected: self.add_warning(\"Overlapping islands were detected after packing (check the",
"support\" URL_SUFFIX = \"udim-support\" class UVP2_OT_ManualGroupingHelp(UVP2_OT_Help): bl_label = 'Manual Grouping Help' bl_idname =",
"help for non-square packing\" URL_SUFFIX = \"non-square-packing\" class UVP2_OT_SimilarityDetectionHelp(UVP2_OT_Help): bl_label = 'Similarity Detection",
"or (at your option) any later version. # # This program is distributed",
"\"Faces with inconsistent {} values found in the selected islands\".format(param_array[subcode].NAME) else: self.raiseUnexpectedOutputError() raise",
"self.get_progress_msg() if not new_progress_msg: return now = time.time() if now - self.progress_last_update_time >",
"self.pack_solution_msg = None self.area_msg = None self.invalid_faces_msg = None self.similar_islands_msg = None self.islands_metadata_msg",
"= 'uvpackmaster2.uv_validate' bl_label = 'Validate UVs' bl_description = 'Validate selected UV faces. The",
"self.similar_islands_msg = None self.islands_metadata_msg = None except NoUvFaceError as ex: self.set_status('WARNING', str(ex)) cancel",
"return (1.0, 1.0) class UVP2_OT_AdjustIslandsToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_adjust_islands_to_texture' bl_label = 'Adjust Islands To",
"!= similar_island_count: self.raiseUnexpectedOutputError() for island_idx in similar_islands: self.p_context.select_island_faces(island_idx, self.p_context.uv_island_faces_list[island_idx], True) else: if len(similar_islands)",
"['-W', self.scene_props.pixel_margin_method] uvp_args += ['-Y', str(self.scene_props.pixel_margin_adjust_time)] if self.prefs.fixed_scale_enabled(self.scene_props): uvp_args += ['-O'] uvp_args +=",
"if selected_cnt + unselected_cnt == 0: raise NoUvFaceError('No UV face visible') self.validate_pack_params() if",
"' + str(time.time() - self.start_time)) def read_islands(self, islands_msg): islands = [] island_cnt =",
"(WARNINGS were reported - check the UVP tab for details)' self.report({op_status_type}, op_status) self.prefs['op_warnings']",
"validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.VALIDATE_UVS)] return uvp_args class UVP2_OT_ProcessSimilar(UVP2_OT_PackOperatorGeneric): def",
"invalid topology errors\" URL_SUFFIX = \"invalid-topology-issues\" class UVP2_OT_PixelMarginHelp(UVP2_OT_Help): bl_label = 'Pixel Margin Help'",
"out_file = open(out_filepath, 'wb') out_file.write(self.p_context.serialized_maps) out_file.close() uvp_args_final = [get_uvp_execpath(), '-E', '-e', str(UvTopoAnalysisLevel.FORCE_EXTENDED), '-t',",
"False def send_verts_3d(self): return False def read_area(self, area_msg): return round(force_read_float(area_msg) / self.pack_ratio, 3)",
"['-d', self.prefs.dev_array[self.prefs.sel_dev_idx].id] if self.prefs.pixel_margin_enabled(self.scene_props): uvp_args += ['-M', str(self.scene_props.pixel_margin)] uvp_args += ['-y', str(self.prefs.pixel_margin_tex_size(self.scene_props, self.p_context.context))]",
"more details. # # You should have received a copy of the GNU",
"else: self.p_context.context.tool_settings.uv_select_mode = 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) if invalid_face_count > 0: self.set_status('WARNING', 'Pre-validation",
"= subprocess.Popen(uvp_args_final, stdin=subprocess.PIPE, stdout=subprocess.PIPE, **popen_args) out_stream = self.uvp_proc.stdin out_stream.write(self.p_context.serialized_maps) out_stream.flush() self.start_time = time.time()",
"islands which have similar shape to islands which are already selected. For more",
"GNU General Public License for more details. # # You should have received",
"not long enough.\") def validate_pack_params(self): active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else",
"'Close the demo window to finish' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_VALIDATION: return \"Topology validation:",
"creation_flags = os_uvp_creation_flags() popen_args = dict() if creation_flags is not None: popen_args['creationflags'] =",
"area: ' + str(area)) def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.MEASURE_AREA)]",
"Exception as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', 'Unexpected error') cancel = True if",
"tiles_in_row = self.prefs.tile_grid_config(self.scene_props, self.p_context.context) if self.prefs.pack_to_tiles(self.scene_props): uvp_args += ['-V', str(tile_count)] if self.prefs.tiles_enabled(self.scene_props): uvp_args",
"*= self.pack_ratio else: self.target_box = (Vector((0.0, 0.0)), Vector((self.pack_ratio, 1.0))) if self.target_box is not",
"continue' return '' def process_result(self): if self.invalid_faces_msg is None: self.raiseUnexpectedOutputError() invalid_face_count = force_read_int(self.invalid_faces_msg)",
"Start progress monitor thread self.progress_queue = queue.Queue() self.connection_thread = threading.Thread(target=connection_thread_func, args=(self.uvp_proc.stdout, self.progress_queue)) self.connection_thread.daemon",
"self.prefs.target_box_enable: self.target_box = self.prefs.target_box(self.scene_props) if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) if self.pack_ratio != 1.0:",
"msg_code = force_read_int(msg) if self.handle_uvp_msg_spec(msg_code, msg): return if msg_code == UvPackMessageCode.PROGRESS_REPORT: self.curr_phase =",
"raise RuntimeError(item) elif isinstance(item, io.BytesIO): self.handle_uvp_msg(item) else: raise RuntimeError('Unexpected output from the connection",
"invalid_face_count > 0: self.set_status('WARNING', 'Pre-validation failed. Number of invalid faces found: ' +",
"Sometimes increasing the 'Adjustment Time' may solve the problem (if used in the",
"self.start_time = time.time() self.last_msg_time = self.start_time self.hang_detected = False self.hang_timeout = 10.0 #",
"self.uvp_proc.poll() is not None: # It should not be required to but check",
"packing groups together\") raise RuntimeError('Pack process returned an error') def raiseUnexpectedOutputError(self): raise RuntimeError('Unexpected",
"supported in this engine edition') if self.grouping_enabled(): if self.get_group_method() == UvGroupingMethod.SIMILARITY.code: if self.prefs.pack_to_others_enabled(self.scene_props):",
"lock_groups_enabled(self): return self.prefs.FEATURE_lock_overlapping and self.scene_props.lock_groups_enable def send_verts_3d(self): return self.scene_props.normalize_islands def get_progress_msg_spec(self): if self.curr_phase",
"be selected. Click OK to continue' return '' def send_unselected_islands(self): return True def",
"self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg) overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags) if self.area is not None:",
"whether the uvp process is alive if not self.op_done and self.uvp_proc.poll() is not",
"be off in order to group by similarity\") if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: validate_target_box(self.scene_props)",
"self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None if active_dev is None: raise RuntimeError('Could",
"msg else: self.raiseUnexpectedOutputError() def handle_communication(self): if self.op_done: return msg_received = 0 while True:",
"= 1.0 self.target_box = None self.op_status_type = None self.op_status = None self.op_warnings =",
"ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_ANALYSIS: return \"Topology analysis: {:3}% (press ESC",
"self.progress_array = [0] self.progress_msg = '' self.progress_sec_left = -1 self.progress_iter_done = -1 self.progress_last_update_time",
"poll(cls, context): prefs = get_prefs() return prefs.uvp_initialized and context.active_object is not None and",
"force_read_int(msg) if progress_size > len(self.progress_array): self.progress_array = [0] * (progress_size) for i in",
"'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) if invalid_face_count > 0: self.set_status('WARNING', 'Pre-validation failed. Number of",
"round(target_box[1].x, prec), round(target_box[1].y, prec)) def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.PACK), '-i', str(self.scene_props.precision), '-m',",
"'. (WARNINGS were reported - check the UVP tab for details)' self.report({op_status_type}, op_status)",
"msg.read(dev_name_len).decode('ascii') stats.iter_count = force_read_int(msg) stats.total_time = force_read_int(msg) stats.avg_time = force_read_int(msg) return True return",
"def grouping_enabled(self): return False def get_group_method(self): raise RuntimeError('Unexpected grouping requested') def send_rot_step(self): return",
"* len(self.confirmation_msg) + 50 return wm.invoke_props_dialog(self, width=dialog_width) return self.execute(context) def draw(self, context): layout",
"!= 1.0: uvp_args += ['-q', str(self.pack_ratio)] if self.target_box is not None: self.target_box[0].x *=",
"creation_flags is not None: popen_args['creationflags'] = creation_flags self.uvp_proc = subprocess.Popen(uvp_args_final, stdin=subprocess.PIPE, stdout=subprocess.PIPE, **popen_args)",
"def send_unselected_islands(self): return False def grouping_enabled(self): return False def get_group_method(self): raise RuntimeError('Unexpected grouping",
"\"Selects all islands which have similar shape to islands which are already selected.",
"not None: self.prefs.stats_area = self.area if self.uvp_proc.returncode == UvPackerErrorCode.NO_SPACE: op_status = 'Packing stopped",
"event): self.interactive = True self.prefs = get_prefs() self.scene_props = context.scene.uvp2_props self.confirmation_msg = self.get_confirmation_msg()",
"when packing to a non-square texture. For for info regarding non-square packing click",
"get_active_image_ratio(self.p_context.context) if self.pack_ratio != 1.0: uvp_args += ['-q', str(self.pack_ratio)] if self.target_box is not",
"= self.get_progress_msg_spec() if progress_msg_spec: return progress_msg_spec if self.curr_phase == UvPackingPhaseCode.INITIALIZATION: return 'Initialization (press",
"is not None: uvp_args += ['-B', self.get_target_box_string(self.target_box)] uvp_args.append('-b') return uvp_args class UVP2_OT_OverlapCheckOperator(UVP2_OT_PackOperatorGeneric): bl_idname",
"self.get_target_box_string(self.target_box)] uvp_args.append('-b') return uvp_args class UVP2_OT_OverlapCheckOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_overlap_check' bl_label = 'Overlap Check'",
"+= ['-U', str(self.scene_props.group_compactness)] if self.prefs.multi_device_enabled(self.scene_props): uvp_args.append('-u') if self.prefs.lock_overlap_enabled(self.scene_props): uvp_args += ['-l', self.scene_props.lock_overlapping_mode] if",
"is None: self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg) overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags) if overlap_detected: self.set_status('WARNING',",
"handling invalid topology errors\" URL_SUFFIX = \"invalid-topology-issues\" class UVP2_OT_PixelMarginHelp(UVP2_OT_Help): bl_label = 'Pixel Margin",
"= 'uvpackmaster2.uv_select_similar' bl_label = 'Select Similar' bl_description = \"Selects all islands which have",
"'Measure Area' bl_description = 'Measure area of selected UV islands' def process_result(self): if",
"# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free",
"islands\".format(param_array[subcode].NAME) else: self.raiseUnexpectedOutputError() raise InvalidIslandsError(error_msg) def require_selection(self): return True def finish_after_op_done(self): return True",
"process wait timeout reached') self.connection_thread.join() self.check_uvp_retcode(self.uvp_proc.returncode) if not self.p_context.islands_received(): self.raiseUnexpectedOutputError() self.process_invalid_islands() self.process_result() if",
"if self.curr_phase == UvPackingPhaseCode.SIMILAR_SELECTION: return 'Searching for similar islands (press ESC to cancel)'",
"were reported - check the UVP tab for details)' self.report({op_status_type}, op_status) self.prefs['op_warnings'] =",
"Public License # along with this program; if not, write to the Free",
"outside_detected = False if self.invalid_faces_msg is not None: invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces =",
"percent_progress_str += str(prog).rjust(3, ' ') + '%, ' percent_progress_str = percent_progress_str[:-2] progress_str =",
"heuristic search\" URL_SUFFIX = \"heuristic-search\" class UVP2_OT_NonSquarePackingHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing Help' bl_idname",
"outside_detected: self.add_warning(\"Some islands are outside their packing box after packing (check the selected",
"self.island_flags_msg is None: self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg) overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags) if overlap_detected:",
"and (to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.EXTERNAL) send_lock_groups = self.lock_groups_enabled() send_verts_3d = self.send_verts_3d() selected_cnt, unselected_cnt =",
"= False if self.invalid_faces_msg is not None: invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces = read_int_array(self.invalid_faces_msg)",
"pass def get_uvp_args(self): uvp_args = ['-o', str(self.get_uvp_opcode()), '-I', str(self.scene_props.similarity_threshold)] uvp_args += ['-i', str(self.scene_props.precision)]",
"= force_read_int(msg) # Inform the upper layer wheter it should finish if self.curr_phase",
"requested') def send_rot_step(self): return False def lock_groups_enabled(self): return False def send_verts_3d(self): return False",
"get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return (ratio, 1.0) class UVP2_OT_Help(bpy.types.Operator): bl_label = 'Help' def",
"self.raiseUnexpectedOutputError() self.similar_islands_msg = msg elif msg_code == UvPackMessageCode.ISLANDS: self.read_islands(msg) elif msg_code == UvPackMessageCode.ISLANDS_METADATA:",
"hope that it will be useful, # but WITHOUT ANY WARRANTY; without even",
"['-C', str(tiles_in_row)] if self.grouping_enabled(): if to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.SIMILARITY: uvp_args += ['-I', str(self.scene_props.similarity_threshold)] if",
"= force_read_int(msg) self.progress_sec_left = force_read_int(msg) self.progress_iter_done = force_read_int(msg) # Inform the upper layer",
"self.prefs.FEATURE_demo: if len(invalid_faces) != invalid_face_count: self.raiseUnexpectedOutputError() if invalid_face_count > 0: # Switch to",
"return \"Topology validation: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.VALIDATION: return",
"and self.scene_props.lock_groups_enable def send_verts_3d(self): return self.scene_props.normalize_islands def get_progress_msg_spec(self): if self.curr_phase in { UvPackingPhaseCode.PACKING,",
"= True self.prefs = get_prefs() self.scene_props = context.scene.uvp2_props self.confirmation_msg = self.get_confirmation_msg() wm =",
"Generic event processing code if event.type == 'ESC': raise OpCancelledException() elif event.type ==",
"self.progress_queue = queue.Queue() self.connection_thread = threading.Thread(target=connection_thread_func, args=(self.uvp_proc.stdout, self.progress_queue)) self.connection_thread.daemon = True self.connection_thread.start() self.progress_array",
"send_unselected_islands(self): return self.prefs.pack_to_others_enabled(self.scene_props) def grouping_enabled(self): return self.prefs.grouping_enabled(self.scene_props) def get_group_method(self): return self.scene_props.group_method def send_rot_step(self):",
"True) else: self.p_context.context.tool_settings.uv_select_mode = 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) else: if len(invalid_faces) > 0:",
"uvp_args += ['-r', str(rot_step_value)] if self.prefs.heuristic_enabled(self.scene_props): uvp_args += ['-h', str(self.scene_props.heuristic_search_time), '-j', str(self.scene_props.heuristic_max_wait_time)] if",
"= self.modal(context, event) if ret.intersection({'FINISHED', 'CANCELLED'}): return ret time.sleep(self.MODAL_INTERVAL_S) def invoke(self, context, event):",
"self.prefs.heuristic_enabled(self.scene_props): return UvpLabels.GROUPS_TOGETHER_CONFIRM_MSG return '' def send_unselected_islands(self): return self.prefs.pack_to_others_enabled(self.scene_props) def grouping_enabled(self): return self.prefs.grouping_enabled(self.scene_props)",
"+= str(prog).rjust(3, ' ') + '%, ' percent_progress_str = percent_progress_str[:-2] progress_str = 'Pack",
"get_confirmation_msg(self): return '' def send_unselected_islands(self): return False def grouping_enabled(self): return False def get_group_method(self):",
"step on per-island level\" URL_SUFFIX = \"island-rotation-step\" class UVP2_OT_UdimSupportHelp(UVP2_OT_Help): bl_label = 'UDIM Support",
"self.op_done else {'PASS_THROUGH'} def pre_op_initialize(self): pass def execute(self, context): cancel = False self.op_done",
"+= ['-C', str(tiles_in_row)] if self.grouping_enabled(): if to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.SIMILARITY: uvp_args += ['-I', str(self.scene_props.similarity_threshold)]",
"str(90)] if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) uvp_args += ['-q', str(self.pack_ratio)] return uvp_args class",
"' + str(invalid_face_count) + '. Packing aborted') return if not self.prefs.FEATURE_demo: if self.island_flags_msg",
"(at your option) any later version. # # This program is distributed in",
"if self.similar_islands_msg is None: self.raiseUnexpectedOutputError() similar_island_count = force_read_int(self.similar_islands_msg) similar_islands = read_int_array(self.similar_islands_msg) if not",
"and not getattr(self.prefs, 'FEATURE_' + pack_mode.req_feature): raise RuntimeError('Selected packing mode is not supported",
"= self.lock_groups_enabled() send_verts_3d = self.send_verts_3d() selected_cnt, unselected_cnt = self.p_context.serialize_uv_maps(send_unselected, send_groups, send_rot_step, send_lock_groups, send_verts_3d,",
"islands overlap each other' def process_result(self): if self.island_flags_msg is None: self.raiseUnexpectedOutputError() island_flags =",
"PackContext(context) self.pre_op_initialize() send_unselected = self.send_unselected_islands() send_rot_step = self.send_rot_step() send_groups = self.grouping_enabled() and (to_uvp_group_method(self.get_group_method())",
"self.pack_ratio = get_active_image_ratio(self.p_context.context) if self.pack_ratio != 1.0: uvp_args += ['-q', str(self.pack_ratio)] if self.target_box",
"new_progress_msg != self.progress_msg: self.progress_last_update_time = now self.progress_msg = new_progress_msg self.report({'INFO'}, self.progress_msg) def handle_uvp_msg(self,",
"self.uvp_proc.stdin out_stream.write(self.p_context.serialized_maps) out_stream.flush() self.start_time = time.time() self.last_msg_time = self.start_time self.hang_detected = False self.hang_timeout",
"self.connection_thread = threading.Thread(target=connection_thread_func, args=(self.uvp_proc.stdout, self.progress_queue)) self.connection_thread.daemon = True self.connection_thread.start() self.progress_array = [0] self.progress_msg",
"self.pack_ratio != 1.0: uvp_args += ['-q', str(self.pack_ratio)] if self.target_box is not None: self.target_box[0].x",
"True def get_uvp_opcode(self): return UvPackerOpcode.SELECT_SIMILAR def process_result(self): if self.similar_islands_msg is None: self.raiseUnexpectedOutputError() similar_island_count",
"def send_verts_3d(self): return self.scene_props.normalize_islands def get_progress_msg_spec(self): if self.curr_phase in { UvPackingPhaseCode.PACKING, UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT }:",
"' percent_progress_str = percent_progress_str[:-2] progress_str = 'Pack progress: {} '.format(percent_progress_str) if self.area is",
"setup\" URL_SUFFIX = \"uvp-setup\" class UVP2_OT_HeuristicSearchHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing Help' bl_idname =",
"OpFinishedException: finish = True except: raise if finish: return self.finish(context) except OpAbortedException: self.set_status('INFO',",
"are placed on top of each other. For more info regarding similarity detection",
"- self.last_msg_time > self.hang_timeout: self.hang_detected = True def handle_event(self, event): # Kill the",
"UVP2_OT_ValidateOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_validate' bl_label = 'Validate UVs' bl_description = 'Validate selected UV",
"from .pack_context import * from .connection import * from .prefs import * from",
"if retcode == UvPackerErrorCode.CANCELLED: raise OpCancelledException() if retcode == UvPackerErrorCode.NO_VALID_STATIC_ISLAND: raise RuntimeError(\"'Pack To",
"+= ['-W', self.scene_props.pixel_margin_method] uvp_args += ['-Y', str(self.scene_props.pixel_margin_adjust_time)] if self.prefs.fixed_scale_enabled(self.scene_props): uvp_args += ['-O'] uvp_args",
"def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return (1.0 / ratio, 1.0) class UVP2_OT_UndoIslandsAdjustemntToTexture(UVP2_OT_ScaleIslands): bl_idname",
"to cancel)' if self.curr_phase == UvPackingPhaseCode.AREA_MEASUREMENT: return 'Area measurement in progress (press ESC",
"msg elif msg_code == UvPackMessageCode.SIMILAR_ISLANDS: if self.similar_islands_msg is not None: self.raiseUnexpectedOutputError() self.similar_islands_msg =",
"self.uvp_proc.terminate() self.report_status() return {'FINISHED'} if self.interactive: wm = context.window_manager self._timer = wm.event_timer_add(self.MODAL_INTERVAL_S, window=context.window)",
"placed on top of each other. For more info regarding similarity detection click",
"+= ['-x'] if self.prefs.FEATURE_validation and self.scene_props.pre_validate: uvp_args.append('-v') if self.prefs.normalize_islands_enabled(self.scene_props): uvp_args.append('-L') if self.prefs.FEATURE_target_box and",
"= False try: try: self.handle_event(event) # Check whether the uvp process is alive",
"UvPackerErrorCode.PRE_VALIDATION_FAILED}: return if retcode == UvPackerErrorCode.CANCELLED: raise OpCancelledException() if retcode == UvPackerErrorCode.NO_VALID_STATIC_ISLAND: raise",
"if self.prefs.pack_groups_together(self.scene_props) and not self.prefs.heuristic_enabled(self.scene_props): return UvpLabels.GROUPS_TOGETHER_CONFIRM_MSG return '' def send_unselected_islands(self): return self.prefs.pack_to_others_enabled(self.scene_props)",
"event): if event.type == 'ESC': if not self.cancel_sig_sent: self.uvp_proc.send_signal(os_cancel_sig()) self.cancel_sig_sent = True return",
"1.0) class UVP2_OT_Help(bpy.types.Operator): bl_label = 'Help' def execute(self, context): webbrowser.open(UvpLabels.HELP_BASEURL + self.URL_SUFFIX) return",
"self.progress_queue.get_nowait() except queue.Empty as ex: break if isinstance(item, str): raise RuntimeError(item) elif isinstance(item,",
"self.similar_islands_msg is not None: self.raiseUnexpectedOutputError() self.similar_islands_msg = msg elif msg_code == UvPackMessageCode.ISLANDS: self.read_islands(msg)",
"Vector((self.pack_ratio, 1.0))) if self.target_box is not None: uvp_args += ['-B', self.get_target_box_string(self.target_box)] uvp_args.append('-b') return",
"selected_cnt + unselected_cnt == 0: raise NoUvFaceError('No UV face visible') self.validate_pack_params() if self.prefs.write_to_file:",
"return msg_refresh_interval = 2.0 new_progress_msg = self.get_progress_msg() if not new_progress_msg: return now =",
"def process_result(self): overlap_detected = False outside_detected = False if self.invalid_faces_msg is not None:",
"if code == UvInvalidIslandCode.TOPOLOGY: error_msg = \"Invalid topology encountered in the selected islands.",
"= msg else: self.raiseUnexpectedOutputError() def handle_communication(self): if self.op_done: return msg_received = 0 while",
"# # ##### END GPL LICENSE BLOCK ##### import subprocess import queue import",
"islands so they are suitable for packing into the active texture. CAUTION: this",
"= self.prefs.stats_array.add() dev_name_len = force_read_int(msg) stats.dev_name = msg.read(dev_name_len).decode('ascii') stats.iter_count = force_read_int(msg) stats.total_time =",
"1 curr_time = time.time() if msg_received > 0: self.last_msg_time = curr_time self.hang_detected =",
"!= '' and not getattr(self.prefs, 'FEATURE_' + pack_mode.req_feature): raise RuntimeError('Selected packing mode is",
"True) else: if len(similar_islands) > 0: self.raiseUnexpectedOutputError() self.set_status('INFO', 'Similar islands found: ' +",
"{'UNDO'} MODAL_INTERVAL_S = 0.1 interactive = False @classmethod def poll(cls, context): prefs =",
"handle_communication(self): if self.op_done: return msg_received = 0 while True: try: item = self.progress_queue.get_nowait()",
"looks for invalid UV faces i.e. faces with area close to 0, self-intersecting",
"Islands Adjustment' bl_description = \"Undo adjustment performed by the 'Adjust Islands To Texture'",
"context): self.uvp_proc.terminate() # self.progress_thread.terminate() self.exit_common() return {'FINISHED'} def get_progress_msg_spec(self): return False def get_progress_msg(self):",
"be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of",
"= self.uvp_proc.stdin out_stream.write(self.p_context.serialized_maps) out_stream.flush() self.start_time = time.time() self.last_msg_time = self.start_time self.hang_detected = False",
"can redistribute it and/or # modify it under the terms of the GNU",
"= 'uvpackmaster2.uv_undo_islands_adjustment_to_texture' bl_label = 'Undo Islands Adjustment' bl_description = \"Undo adjustment performed by",
"uvp_args.append('-u') if self.prefs.lock_overlap_enabled(self.scene_props): uvp_args += ['-l', self.scene_props.lock_overlapping_mode] if self.prefs.pack_to_others_enabled(self.scene_props): uvp_args += ['-x'] if",
"Help' bl_idname = 'uvpackmaster2.uv_nonsquare_packing_help' bl_description = \"Show help for non-square packing\" URL_SUFFIX =",
"UVP2_OT_UdimSupportHelp(UVP2_OT_Help): bl_label = 'UDIM Support Help' bl_idname = 'uvpackmaster2.uv_udim_support_help' bl_description = \"Show help",
">= 0: iter_str = 'Iter. done: {}. '.format(self.progress_iter_done) else: iter_str = '' if",
"not responding for a longer time (press ESC to abort)' if self.curr_phase is",
"msg_code == UvPackMessageCode.PACK_SOLUTION: if self.pack_solution_msg is not None: self.raiseUnexpectedOutputError() self.pack_solution_msg = msg elif",
"process_invalid_islands(self): if self.uvp_proc.returncode != UvPackerErrorCode.INVALID_ISLANDS: return if self.invalid_islands_msg is None: self.raiseUnexpectedOutputError() code =",
"= None self.area_msg = None self.invalid_faces_msg = None self.similar_islands_msg = None self.islands_metadata_msg =",
"Adjustment' bl_description = \"Undo adjustment performed by the 'Adjust Islands To Texture' operator",
"\"Time left: {} sec. \".format(self.progress_sec_left) else: time_left_str = '' percent_progress_str = '' for",
"process is alive if not self.op_done and self.uvp_proc.poll() is not None: # It",
"demo window to finish' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_VALIDATION: return \"Topology validation: {:3}% (press",
"to cancel)\".format(self.progress_array[0]) raise RuntimeError('Unexpected packing phase encountered') def handle_uvp_msg_spec(self, msg_code, msg): return False",
"'' def process_result(self): if self.invalid_faces_msg is None: self.raiseUnexpectedOutputError() invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces =",
"found: ' + str(invalid_face_count) + '. Packing aborted') return if not self.prefs.FEATURE_demo: if",
"This usually happens when 'Pixel Padding' is set to a small value and",
"= time.time() self.last_msg_time = self.start_time self.hang_detected = False self.hang_timeout = 10.0 # Start",
"if self.island_flags_msg is not None: self.raiseUnexpectedOutputError() self.island_flags_msg = msg elif msg_code == UvPackMessageCode.PACK_SOLUTION:",
"invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces = read_int_array(self.invalid_faces_msg) if not self.prefs.FEATURE_demo: if len(invalid_faces) != invalid_face_count:",
"and context.active_object.mode == 'EDIT' def execute(self, context): try: self.p_context = PackContext(context) ratio =",
"== 'ESC': if not self.cancel_sig_sent: self.uvp_proc.send_signal(os_cancel_sig()) self.cancel_sig_sent = True return True return False",
"= [] try: if not check_uvp(): unregister_uvp() redraw_ui(context) raise RuntimeError(\"UVP engine broken\") reset_stats(self.prefs)",
"time_left_str + progress_str + end_str return False def handle_uvp_msg_spec(self, msg_code, msg): if msg_code",
"self.prefs.wait_for_debugger: uvp_args_final.append('-G') uvp_args_final += ['-T', str(self.prefs.test_param)] print('Pakcer args: ' + ' '.join(x for",
"help for similarity detection\" URL_SUFFIX = \"similarity-detection\" class UVP2_OT_InvalidTopologyHelp(UVP2_OT_Help): bl_label = 'Invalid Topology",
"'.format(self.progress_iter_done) else: iter_str = '' if self.progress_sec_left >= 0: time_left_str = \"Time left:",
"in the demo mode only the number of invalid faces found is reported,",
"ESC to abort)' if self.curr_phase is None: return False progress_msg_spec = self.get_progress_msg_spec() if",
"ret time.sleep(self.MODAL_INTERVAL_S) def invoke(self, context, event): self.interactive = True self.prefs = get_prefs() self.scene_props",
"is None: self.raiseUnexpectedOutputError() similar_island_count = force_read_int(self.similar_islands_msg) similar_islands = read_int_array(self.similar_islands_msg) if not self.prefs.FEATURE_demo: if",
"class InvalidIslandsError(Exception): pass class NoUvFaceError(Exception): pass class UVP2_OT_PackOperatorGeneric(bpy.types.Operator): bl_options = {'UNDO'} MODAL_INTERVAL_S =",
"False def get_group_method(self): raise RuntimeError('Unexpected grouping requested') def send_rot_step(self): return False def lock_groups_enabled(self):",
"'Align Similar' bl_description = \"Align selected islands, so islands which are similar are",
"bl_description = \"Undo adjustment performed by the 'Adjust Islands To Texture' operator so",
"(press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.AREA_MEASUREMENT: return 'Area measurement in progress",
"is not None: op_status += ', packed islands area: ' + str(self.area) self.set_status('INFO',",
"Setup Help' bl_idname = 'uvpackmaster2.uv_uvp_setup_help' bl_description = \"Show help for UVP setup\" URL_SUFFIX",
"= force_read_int(msg) stats.dev_name = msg.read(dev_name_len).decode('ascii') stats.iter_count = force_read_int(msg) stats.total_time = force_read_int(msg) stats.avg_time =",
"{'FINISHED'} def get_scale_factors(self): return (1.0, 1.0) class UVP2_OT_AdjustIslandsToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_adjust_islands_to_texture' bl_label =",
"is not None else 'none') else: header_str = '' if self.progress_iter_done >= 0:",
"selected UV islands' def __init__(self): self.cancel_sig_sent = False self.area = None def get_confirmation_msg(self):",
"redistribute it and/or # modify it under the terms of the GNU General",
"class UVP2_OT_UndoIslandsAdjustemntToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_undo_islands_adjustment_to_texture' bl_label = 'Undo Islands Adjustment' bl_description = \"Undo",
"cancel = True except OpCancelledException: self.set_status('INFO', 'Operation cancelled by the user') cancel =",
"Check' bl_description = 'Check wheter selected UV islands overlap each other' def process_result(self):",
"but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or",
"= self.read_area(msg) return True elif msg_code == UvPackMessageCode.PACK_SOLUTION: pack_solution = read_pack_solution(msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution)",
"the Free Software Foundation; either version 2 # of the License, or (at",
"get_confirmation_msg(self): if platform.system() == 'Darwin': active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else",
"of the GNU General Public License # as published by the Free Software",
"values found in the selected islands\".format(param_array[subcode].NAME) else: self.raiseUnexpectedOutputError() raise InvalidIslandsError(error_msg) def require_selection(self): return",
"class NoUvFaceError(Exception): pass class UVP2_OT_PackOperatorGeneric(bpy.types.Operator): bl_options = {'UNDO'} MODAL_INTERVAL_S = 0.1 interactive =",
"PackContext(context) ratio = get_active_image_ratio(self.p_context.context) self.p_context.scale_selected_faces(self.get_scale_factors()) except RuntimeError as ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'},",
"\"Undo adjustment performed by the 'Adjust Islands To Texture' operator so islands are",
"self.set_status('WARNING', str(ex)) cancel = True except RuntimeError as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR',",
"a crash self.prefs.uvp_retcode = -1 raise RuntimeError('Packer process died unexpectedly') self.handle_progress_msg() except OpFinishedException:",
"self.area if self.uvp_proc.returncode == UvPackerErrorCode.NO_SPACE: op_status = 'Packing stopped - no space to",
"\"Show help for UVP setup\" URL_SUFFIX = \"uvp-setup\" class UVP2_OT_HeuristicSearchHelp(UVP2_OT_Help): bl_label = 'Non-Square",
"URL_SUFFIX = \"uvp-setup\" class UVP2_OT_HeuristicSearchHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing Help' bl_idname = 'uvpackmaster2.uv_heuristic_search_help'",
"self.target_box[1].x *= self.pack_ratio else: self.target_box = (Vector((0.0, 0.0)), Vector((self.pack_ratio, 1.0))) if self.target_box is",
"tempfile class InvalidIslandsError(Exception): pass class NoUvFaceError(Exception): pass class UVP2_OT_PackOperatorGeneric(bpy.types.Operator): bl_options = {'UNDO'} MODAL_INTERVAL_S",
"msg elif msg_code == UvPackMessageCode.AREA: if self.area_msg is not None: self.raiseUnexpectedOutputError() self.area_msg =",
"= time.time() if msg_received > 0: self.last_msg_time = curr_time self.hang_detected = False else:",
"value indicating a crash self.prefs.uvp_retcode = -1 raise RuntimeError('Packer process died unexpectedly') self.handle_progress_msg()",
"if self.lock_groups_enabled(): uvp_args_final += ['-Q'] if in_debug_mode(): if self.prefs.seed > 0: uvp_args_final +=",
"self.op_status_type = status_type self.op_status = status def add_warning(self, warn_msg): self.op_warnings.append(warn_msg) def report_status(self): if",
"def handle_op_done(self): self.op_done = True send_finish_confirmation(self.uvp_proc) try: self.uvp_proc.wait(5) except: raise RuntimeError('The UVP process",
"packing into the active texture. CAUTION: this operator should be used only when",
"find a packing device') if not active_dev.supported: raise RuntimeError('Selected packing device is not",
"== UvPackingPhaseCode.TOPOLOGY_VALIDATION: return \"Topology validation: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase ==",
"write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor,",
"= '(press ESC to cancel) ' return header_str + iter_str + time_left_str +",
"active texture. CAUTION: this operator should be used only when packing to a",
"get_prefs() self.scene_props = context.scene.uvp2_props self.confirmation_msg = self.get_confirmation_msg() wm = context.window_manager if self.confirmation_msg !=",
"if len(similar_islands) != similar_island_count: self.raiseUnexpectedOutputError() for island_idx in similar_islands: self.p_context.select_island_faces(island_idx, self.p_context.uv_island_faces_list[island_idx], True) else:",
"def get_progress_msg_spec(self): return False def get_progress_msg(self): if self.hang_detected: return 'Packer process not responding",
"OpCancelledException() elif event.type == 'TIMER': self.handle_communication() def modal(self, context, event): cancel = False",
"== UvPackMessageCode.AREA: self.area = self.read_area(msg) return True elif msg_code == UvPackMessageCode.PACK_SOLUTION: pack_solution =",
"None self.pack_solution_msg = None self.area_msg = None self.invalid_faces_msg = None self.similar_islands_msg = None",
"self.set_status('INFO', 'Similar islands found: ' + str(similar_island_count)) class UVP2_OT_AlignSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_align_similar' bl_label",
"\"Show help for UDIM support\" URL_SUFFIX = \"udim-support\" class UVP2_OT_ManualGroupingHelp(UVP2_OT_Help): bl_label = 'Manual",
"selected islands, so islands which are similar are placed on top of each",
"header_str = 'Current area: {}. '.format(self.area if self.area is not None else 'none')",
"str(self.pack_ratio)] if self.target_box is not None: self.target_box[0].x *= self.pack_ratio self.target_box[1].x *= self.pack_ratio else:",
"< len(self.prefs.dev_array) else None if active_dev is not None and active_dev.id.startswith('cuda'): return UvpLabels.CUDA_MACOS_CONFIRM_MSG",
"'CANCELLED'}): return ret time.sleep(self.MODAL_INTERVAL_S) def invoke(self, context, event): self.interactive = True self.prefs =",
"not None and context.active_object.mode == 'EDIT' def execute(self, context): try: self.p_context = PackContext(context)",
"None: self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg) overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags) if overlap_detected: self.set_status('WARNING', 'Overlapping",
"i in range(island_cnt): islands.append(read_int_array(islands_msg)) self.p_context.set_islands(selected_cnt, islands) def process_invalid_islands(self): if self.uvp_proc.returncode != UvPackerErrorCode.INVALID_ISLANDS: return",
"code == UvInvalidIslandCode.TOPOLOGY: error_msg = \"Invalid topology encountered in the selected islands. Check",
"self.uvp_proc.wait(5) except: raise RuntimeError('The UVP process wait timeout reached') self.connection_thread.join() self.check_uvp_retcode(self.uvp_proc.returncode) if not",
"self.prefs.dev_array[self.prefs.sel_dev_idx].id] if self.prefs.pixel_margin_enabled(self.scene_props): uvp_args += ['-M', str(self.scene_props.pixel_margin)] uvp_args += ['-y', str(self.prefs.pixel_margin_tex_size(self.scene_props, self.p_context.context))] if",
"['-o', str(UvPackerOpcode.MEASURE_AREA)] return uvp_args class UVP2_OT_ValidateOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_validate' bl_label = 'Validate UVs'",
"if retcode == UvPackerErrorCode.DEVICE_NOT_SUPPORTED: raise RuntimeError(\"Selected device is not supported\") if retcode ==",
"if self.invalid_faces_msg is not None: self.raiseUnexpectedOutputError() self.invalid_faces_msg = msg elif msg_code == UvPackMessageCode.SIMILAR_ISLANDS:",
"import check_uvp, unregister_uvp import bmesh import bpy import mathutils import tempfile class InvalidIslandsError(Exception):",
"this program; if not, write to the Free Software Foundation, # Inc., 51",
"self.pack_ratio else: self.target_box = (Vector((0.0, 0.0)), Vector((self.pack_ratio, 1.0))) if self.target_box is not None:",
"similarity\") if self.scene_props.prerot_disable: raise RuntimeError(\"'Pre-Rotation Disable' option must be off in order to",
"bl_options = {'UNDO'} MODAL_INTERVAL_S = 0.1 interactive = False @classmethod def poll(cls, context):",
"True if cancel: return self.cancel(context) return {'RUNNING_MODAL'} if not self.op_done else {'PASS_THROUGH'} def",
"search\" URL_SUFFIX = \"heuristic-search\" class UVP2_OT_NonSquarePackingHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing Help' bl_idname =",
"self.area is not None else 'none') else: header_str = '' if self.progress_iter_done >=",
"raise RuntimeError('Selected packing mode is not supported in this engine edition') if self.grouping_enabled():",
"'Adjustment Time' may solve the problem (if used in the operation).\") if outside_detected:",
"in pixels\" URL_SUFFIX = \"pixel-margin\" class UVP2_OT_IslandRotStepHelp(UVP2_OT_Help): bl_label = 'Island Rotation Step Help'",
"+= ['-r', str(rot_step_value)] if self.prefs.heuristic_enabled(self.scene_props): uvp_args += ['-h', str(self.scene_props.heuristic_search_time), '-j', str(self.scene_props.heuristic_max_wait_time)] if self.prefs.FEATURE_advanced_heuristic",
"increasing the 'Adjustment Time' may solve the problem (if used in the operation).\")",
"except RuntimeError as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', str(ex)) cancel = True except",
"== 'EDIT' def execute(self, context): try: self.p_context = PackContext(context) ratio = get_active_image_ratio(self.p_context.context) self.p_context.scale_selected_faces(self.get_scale_factors())",
"True self.prefs = get_prefs() self.scene_props = context.scene.uvp2_props self.confirmation_msg = self.get_confirmation_msg() wm = context.window_manager",
"retcode): self.prefs.uvp_retcode = retcode if retcode in {UvPackerErrorCode.SUCCESS, UvPackerErrorCode.INVALID_ISLANDS, UvPackerErrorCode.NO_SPACE, UvPackerErrorCode.PRE_VALIDATION_FAILED}: return if",
"selected UV faces. The validation procedure looks for invalid UV faces i.e. faces",
"= 'uvpackmaster2.uv_pixel_margin_help' bl_description = \"Show help for setting margin in pixels\" URL_SUFFIX =",
"prog in self.progress_array: percent_progress_str += str(prog).rjust(3, ' ') + '%, ' percent_progress_str =",
"other' def get_confirmation_msg(self): if self.prefs.FEATURE_demo: return 'WARNING: in the demo mode only the",
"operator so islands are again suitable for packing into a square texture. For",
"{'FINISHED', 'PASS_THROUGH'} def cancel(self, context): self.uvp_proc.terminate() # self.progress_thread.terminate() self.exit_common() return {'FINISHED'} def get_progress_msg_spec(self):",
"stdin=subprocess.PIPE, stdout=subprocess.PIPE, **popen_args) out_stream = self.uvp_proc.stdin out_stream.write(self.p_context.serialized_maps) out_stream.flush() self.start_time = time.time() self.last_msg_time =",
"if self.prefs.pack_to_others_enabled(self.scene_props): raise RuntimeError(\"'Pack To Others' is not supported with grouping by similarity\")",
"\"Show help for setting margin in pixels\" URL_SUFFIX = \"pixel-margin\" class UVP2_OT_IslandRotStepHelp(UVP2_OT_Help): bl_label",
"'uvpackmaster2.uv_uvp_setup_help' bl_description = \"Show help for UVP setup\" URL_SUFFIX = \"uvp-setup\" class UVP2_OT_HeuristicSearchHelp(UVP2_OT_Help):",
"self.get_group_method() if send_groups else None) if self.require_selection(): if selected_cnt == 0: raise NoUvFaceError('No",
"for x in uvp_args_final)) creation_flags = os_uvp_creation_flags() popen_args = dict() if creation_flags is",
"be selected. Click OK to continue' return '' def process_result(self): if self.invalid_faces_msg is",
"self.curr_phase == UvPackingPhaseCode.SIMILAR_ALIGNING: return 'Similar islands aligning (press ESC to cancel)' if self.curr_phase",
"!= self.progress_msg: self.progress_last_update_time = now self.progress_msg = new_progress_msg self.report({'INFO'}, self.progress_msg) def handle_uvp_msg(self, msg):",
"selected. For more info regarding similarity detection click the help button\" def get_confirmation_msg(self):",
"to abort)' if self.curr_phase is None: return False progress_msg_spec = self.get_progress_msg_spec() if progress_msg_spec:",
"{} '.format(percent_progress_str) if self.area is not None: end_str = '(press ESC to apply",
"self.check_uvp_retcode(self.uvp_proc.returncode) if not self.p_context.islands_received(): self.raiseUnexpectedOutputError() self.process_invalid_islands() self.process_result() if self.finish_after_op_done(): raise OpFinishedException() def finish(self,",
"active_dev.supported: raise RuntimeError('Selected packing device is not supported in this engine edition') #",
"self.progress_thread.terminate() self.exit_common() return {'FINISHED'} def get_progress_msg_spec(self): return False def get_progress_msg(self): if self.hang_detected: return",
"return context.active_object is not None and context.active_object.mode == 'EDIT' def execute(self, context): try:",
"USA. # # ##### END GPL LICENSE BLOCK ##### import subprocess import queue",
"uvp_args += ['-y', str(self.prefs.pixel_margin_tex_size(self.scene_props, self.p_context.context))] if self.prefs.pixel_padding_enabled(self.scene_props): uvp_args += ['-N', str(self.scene_props.pixel_padding)] uvp_args +=",
"packing read the documentation\" def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return (ratio, 1.0) class",
"bl_description = \"Show help for UVP setup\" URL_SUFFIX = \"uvp-setup\" class UVP2_OT_HeuristicSearchHelp(UVP2_OT_Help): bl_label",
"False if self.invalid_faces_msg is not None: invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces = read_int_array(self.invalid_faces_msg) if",
"else {'PASS_THROUGH'} def pre_op_initialize(self): pass def execute(self, context): cancel = False self.op_done =",
"self.prefs.FEATURE_island_rotation: if self.scene_props.rot_enable: rot_step_value = self.scene_props.rot_step if self.scene_props.prerot_disable: uvp_args += ['-w'] else: rot_step_value",
"' + str(self.area) self.set_status('INFO', op_status) if overlap_detected: self.add_warning(\"Overlapping islands were detected after packing",
"later version. # # This program is distributed in the hope that it",
"platform.system() == 'Darwin': active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None if",
"elif msg_code == UvPackMessageCode.INVALID_FACES: if self.invalid_faces_msg is not None: self.raiseUnexpectedOutputError() self.invalid_faces_msg = msg",
"is not None: self.p_context.update_meshes() if cancel: if self.uvp_proc is not None: self.uvp_proc.terminate() self.report_status()",
"= True except OpCancelledException: self.set_status('INFO', 'Operation cancelled by the user') cancel = True",
"== 0: raise NoUvFaceError('No UV face selected') else: if selected_cnt + unselected_cnt ==",
"be on the safe side self.handle_communication() if not self.op_done: # Special value indicating",
"Packing Help' bl_idname = 'uvpackmaster2.uv_nonsquare_packing_help' bl_description = \"Show help for non-square packing\" URL_SUFFIX",
"more info regarding similarity detection click the help button\" def get_uvp_opcode(self): return UvPackerOpcode.ALIGN_SIMILAR",
"= False self.area = None def get_confirmation_msg(self): if platform.system() == 'Darwin': active_dev =",
"def report_status(self): if self.op_status is not None: self.prefs['op_status'] = self.op_status op_status_type = self.op_status_type",
"0: time_left_str = \"Time left: {} sec. \".format(self.progress_sec_left) else: time_left_str = '' percent_progress_str",
"self.invalid_islands_msg = None self.island_flags_msg = None self.pack_solution_msg = None self.area_msg = None self.invalid_faces_msg",
"(check the selected islands). This usually happens when 'Pixel Padding' is set to",
"and curr_time - self.last_msg_time > self.hang_timeout: self.hang_detected = True def handle_event(self, event): #",
"(press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_ALIGNING: return 'Similar islands aligning (press",
"= None self.op_status = None self.op_warnings = [] try: if not check_uvp(): unregister_uvp()",
"self.op_status if len(self.op_warnings) > 0: if op_status_type == 'INFO': op_status_type = 'WARNING' op_status",
"progress_msg_spec if self.curr_phase == UvPackingPhaseCode.INITIALIZATION: return 'Initialization (press ESC to cancel)' if self.curr_phase",
"self.target_box is not None: uvp_args += ['-B', self.get_target_box_string(self.target_box)] uvp_args.append('-b') return uvp_args class UVP2_OT_OverlapCheckOperator(UVP2_OT_PackOperatorGeneric):",
"\"Topology analysis: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.OVERLAP_CHECK: return 'Overlap",
"self.op_status = None self.op_warnings = [] try: if not check_uvp(): unregister_uvp() redraw_ui(context) raise",
"send_rot_step, send_lock_groups, send_verts_3d, self.get_group_method() if send_groups else None) if self.require_selection(): if selected_cnt ==",
"read_int_array(self.island_flags_msg) overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags) if overlap_detected: self.set_status('WARNING', 'Overlapping islands detected') else: self.set_status('INFO',",
"have received a copy of the GNU General Public License # along with",
"if outside_detected: self.add_warning(\"Some islands are outside their packing box after packing (check the",
"selected. Click OK to continue' return '' def send_unselected_islands(self): return True def get_uvp_opcode(self):",
"self.p_context.handle_invalid_islands(invalid_islands) if code == UvInvalidIslandCode.TOPOLOGY: error_msg = \"Invalid topology encountered in the selected",
"rotation step on per-island level\" URL_SUFFIX = \"island-rotation-step\" class UVP2_OT_UdimSupportHelp(UVP2_OT_Help): bl_label = 'UDIM",
"return True elif msg_code == UvPackMessageCode.BENCHMARK: stats = self.prefs.stats_array.add() dev_name_len = force_read_int(msg) stats.dev_name",
"measurement in progress (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_SELECTION: return 'Searching",
"print_backtrace(ex) self.report({'ERROR'}, str(ex)) except Exception as ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, 'Unexpected error')",
"'-e', str(UvTopoAnalysisLevel.FORCE_EXTENDED), '-t', str(self.prefs.thread_count)] + self.get_uvp_args() if send_unselected: uvp_args_final.append('-s') if self.grouping_enabled(): uvp_args_final +=",
"for island_idx in similar_islands: self.p_context.select_island_faces(island_idx, self.p_context.uv_island_faces_list[island_idx], True) else: if len(similar_islands) > 0: self.raiseUnexpectedOutputError()",
"= \"Align selected islands, so islands which are similar are placed on top",
"margin in pixels\" URL_SUFFIX = \"pixel-margin\" class UVP2_OT_IslandRotStepHelp(UVP2_OT_Help): bl_label = 'Island Rotation Step",
"in {UvPackerErrorCode.SUCCESS, UvPackerErrorCode.INVALID_ISLANDS, UvPackerErrorCode.NO_SPACE, UvPackerErrorCode.PRE_VALIDATION_FAILED}: return if retcode == UvPackerErrorCode.CANCELLED: raise OpCancelledException() if",
"mathutils import tempfile class InvalidIslandsError(Exception): pass class NoUvFaceError(Exception): pass class UVP2_OT_PackOperatorGeneric(bpy.types.Operator): bl_options =",
"str(self.prefs.thread_count)] + self.get_uvp_args() if send_unselected: uvp_args_final.append('-s') if self.grouping_enabled(): uvp_args_final += ['-a', str(to_uvp_group_method(self.get_group_method()))] if",
"self.prefs.pack_to_tiles(self.scene_props): uvp_args += ['-V', str(tile_count)] if self.prefs.tiles_enabled(self.scene_props): uvp_args += ['-C', str(tiles_in_row)] if self.grouping_enabled():",
"= \"uvp-setup\" class UVP2_OT_HeuristicSearchHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing Help' bl_idname = 'uvpackmaster2.uv_heuristic_search_help' bl_description",
"self.uvp_proc.returncode != UvPackerErrorCode.INVALID_ISLANDS: return if self.invalid_islands_msg is None: self.raiseUnexpectedOutputError() code = force_read_int(self.invalid_islands_msg) subcode",
"uvp_args += ['-W', self.scene_props.pixel_margin_method] uvp_args += ['-Y', str(self.scene_props.pixel_margin_adjust_time)] if self.prefs.fixed_scale_enabled(self.scene_props): uvp_args += ['-O']",
"setting margin in pixels\" URL_SUFFIX = \"pixel-margin\" class UVP2_OT_IslandRotStepHelp(UVP2_OT_Help): bl_label = 'Island Rotation",
"is not supported\") if retcode == UvPackerErrorCode.DEVICE_DOESNT_SUPPORT_GROUPS_TOGETHER: raise RuntimeError(\"Selected device doesn't support packing",
"hang was detected if self.hang_detected and event.type == 'ESC': raise OpAbortedException() if self.handle_event_spec(event):",
"Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.",
"self.prefs.pack_groups_together(self.scene_props) and not self.prefs.heuristic_enabled(self.scene_props): return UvpLabels.GROUPS_TOGETHER_CONFIRM_MSG return '' def send_unselected_islands(self): return self.prefs.pack_to_others_enabled(self.scene_props) def",
"self.progress_iter_done = force_read_int(msg) # Inform the upper layer wheter it should finish if",
"= False finish = False try: try: self.handle_event(event) # Check whether the uvp",
"self.prefs.pack_to_others_enabled(self.scene_props): uvp_args += ['-x'] if self.prefs.FEATURE_validation and self.scene_props.pre_validate: uvp_args.append('-v') if self.prefs.normalize_islands_enabled(self.scene_props): uvp_args.append('-L') if",
"return uvp_args class UVP2_OT_OverlapCheckOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_overlap_check' bl_label = 'Overlap Check' bl_description =",
"subprocess import queue import threading import signal import webbrowser from .utils import *",
"'Similarity Detection Help' bl_idname = 'uvpackmaster2.uv_similarity_detection_help' bl_description = \"Show help for similarity detection\"",
"'uvpackmaster2.uv_measure_area' bl_label = 'Measure Area' bl_description = 'Measure area of selected UV islands'",
"else: if len(similar_islands) > 0: self.raiseUnexpectedOutputError() self.set_status('INFO', 'Similar islands found: ' + str(similar_island_count))",
"is not None: self.raiseUnexpectedOutputError() self.invalid_faces_msg = msg elif msg_code == UvPackMessageCode.SIMILAR_ISLANDS: if self.similar_islands_msg",
"== UvPackMessageCode.PROGRESS_REPORT: self.curr_phase = force_read_int(msg) progress_size = force_read_int(msg) if progress_size > len(self.progress_array): self.progress_array",
"finish = False try: try: self.handle_event(event) # Check whether the uvp process is",
"if self.scene_props.prerot_disable: raise RuntimeError(\"'Pre-Rotation Disable' option must be off in order to group",
"= None self.island_flags_msg = None self.pack_solution_msg = None self.area_msg = None self.invalid_faces_msg =",
"copy of the GNU General Public License # along with this program; if",
"option enabled, but no unselected island found in the packing box\") if retcode",
"= read_pack_solution(self.pack_solution_msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) self.set_status('INFO', 'Islands aligned') class UVP2_OT_ScaleIslands(bpy.types.Operator): bl_options = {'UNDO'} @classmethod",
"self.start_time self.hang_detected = False self.hang_timeout = 10.0 # Start progress monitor thread self.progress_queue",
"get_target_box_string(self, target_box): prec = 4 return \"{}:{}:{}:{}\".format( round(target_box[0].x, prec), round(target_box[0].y, prec), round(target_box[1].x, prec),",
"active_dev.id.startswith('cuda'): return UvpLabels.CUDA_MACOS_CONFIRM_MSG if self.prefs.pack_groups_together(self.scene_props) and not self.prefs.heuristic_enabled(self.scene_props): return UvpLabels.GROUPS_TOGETHER_CONFIRM_MSG return '' def",
"Similar' bl_description = \"Selects all islands which have similar shape to islands which",
"* from .os_iface import * from .island_params import * from .labels import UvpLabels",
"= \"Show help for UDIM support\" URL_SUFFIX = \"udim-support\" class UVP2_OT_ManualGroupingHelp(UVP2_OT_Help): bl_label =",
"# ##### END GPL LICENSE BLOCK ##### import subprocess import queue import threading",
"self.invalid_faces_msg is not None: self.raiseUnexpectedOutputError() self.invalid_faces_msg = msg elif msg_code == UvPackMessageCode.SIMILAR_ISLANDS: if",
"' + ' '.join(x for x in uvp_args_final)) creation_flags = os_uvp_creation_flags() popen_args =",
"is not None: self.raiseUnexpectedOutputError() self.islands_metadata_msg = msg else: self.raiseUnexpectedOutputError() def handle_communication(self): if self.op_done:",
"UvPackingPhaseCode.SIMILAR_SELECTION: return 'Searching for similar islands (press ESC to cancel)' if self.curr_phase ==",
"'' def send_unselected_islands(self): return False def grouping_enabled(self): return False def get_group_method(self): raise RuntimeError('Unexpected",
"str(self.scene_props.pixel_padding)] uvp_args += ['-W', self.scene_props.pixel_margin_method] uvp_args += ['-Y', str(self.scene_props.pixel_margin_adjust_time)] if self.prefs.fixed_scale_enabled(self.scene_props): uvp_args +=",
"self.prefs.tile_grid_config(self.scene_props, self.p_context.context) if self.prefs.pack_to_tiles(self.scene_props): uvp_args += ['-V', str(tile_count)] if self.prefs.tiles_enabled(self.scene_props): uvp_args += ['-C',",
"popen_args = dict() if creation_flags is not None: popen_args['creationflags'] = creation_flags self.uvp_proc =",
"width=dialog_width) return self.execute(context) def draw(self, context): layout = self.layout col = layout.column() col.label(text=self.confirmation_msg)",
"'' def send_unselected_islands(self): return True def get_uvp_opcode(self): return UvPackerOpcode.SELECT_SIMILAR def process_result(self): if self.similar_islands_msg",
"in the selected islands. Check the Help panel to learn more\" elif code",
"bl_label = 'Pixel Margin Help' bl_idname = 'uvpackmaster2.uv_pixel_margin_help' bl_description = \"Show help for",
"= 'Island Rotation Step Help' bl_idname = 'uvpackmaster2.uv_island_rot_step_help' bl_description = \"Show help for",
"= msg elif msg_code == UvPackMessageCode.PACK_SOLUTION: if self.pack_solution_msg is not None: self.raiseUnexpectedOutputError() self.pack_solution_msg",
"in order to group by similarity\") if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: validate_target_box(self.scene_props) def get_target_box_string(self,",
"{} sec. \".format(self.progress_sec_left) else: time_left_str = '' percent_progress_str = '' for prog in",
"the packing box\") if retcode == UvPackerErrorCode.MAX_GROUP_COUNT_EXCEEDED: raise RuntimeError(\"Maximal group count exceeded\") if",
"None self.invalid_faces_msg = None self.similar_islands_msg = None self.islands_metadata_msg = None except NoUvFaceError as",
"return self.execute(context) def draw(self, context): layout = self.layout col = layout.column() col.label(text=self.confirmation_msg) def",
"and self.prefs.target_box_enable: self.target_box = self.prefs.target_box(self.scene_props) if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) if self.pack_ratio !=",
"'Pixel Padding' is set to a small value and the 'Adjustment Time' is",
"self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None if active_dev is None: raise RuntimeError('Could not find",
"return False def lock_groups_enabled(self): return False def send_verts_3d(self): return False def read_area(self, area_msg):",
"or new_progress_msg != self.progress_msg: self.progress_last_update_time = now self.progress_msg = new_progress_msg self.report({'INFO'}, self.progress_msg) def",
"the selected islands). This usually happens when 'Pixel Padding' is set to a",
"while True: event = FakeTimerEvent() ret = self.modal(context, event) if ret.intersection({'FINISHED', 'CANCELLED'}): return",
"if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) uvp_args += ['-q', str(self.pack_ratio)] return uvp_args class UVP2_OT_SelectSimilar(UVP2_OT_ProcessSimilar):",
"\"Align selected islands, so islands which are similar are placed on top of",
"['-g', self.scene_props.pack_mode] tile_count, tiles_in_row = self.prefs.tile_grid_config(self.scene_props, self.p_context.context) if self.prefs.pack_to_tiles(self.scene_props): uvp_args += ['-V', str(tile_count)]",
"similar_islands: self.p_context.select_island_faces(island_idx, self.p_context.uv_island_faces_list[island_idx], True) else: if len(similar_islands) > 0: self.raiseUnexpectedOutputError() self.set_status('INFO', 'Similar islands",
"bl_description = 'Check wheter selected UV islands overlap each other' def process_result(self): if",
"'uvpackmaster2.uv_invalid_topology_help' bl_description = \"Show help for handling invalid topology errors\" URL_SUFFIX = \"invalid-topology-issues\"",
"= True except InvalidIslandsError as err: self.set_status('ERROR', str(err)) cancel = True except RuntimeError",
"= self.p_context.handle_island_flags(island_flags) if overlap_detected: self.set_status('WARNING', 'Overlapping islands detected') else: self.set_status('INFO', 'No overlapping islands",
"self.p_context.select_faces(list(invalid_faces), True) else: if len(invalid_faces) > 0: self.raiseUnexpectedOutputError() if invalid_face_count > 0: self.set_status('WARNING',",
"force_read_int(self.similar_islands_msg) similar_islands = read_int_array(self.similar_islands_msg) if not self.prefs.FEATURE_demo: if len(similar_islands) != similar_island_count: self.raiseUnexpectedOutputError() for",
"parameter. Sometimes increasing the 'Adjustment Time' may solve the problem (if used in",
"PURPOSE. See the # GNU General Public License for more details. # #",
"' elif self.prefs.heuristic_enabled(self.scene_props): header_str = 'Current area: {}. '.format(self.area if self.area is not",
"== UvInvalidIslandCode.INT_PARAM: param_array = IslandParamInfo.get_param_info_array() error_msg = \"Faces with inconsistent {} values found",
"str(UvPackerOpcode.PACK), '-i', str(self.scene_props.precision), '-m', str(self.scene_props.margin)] uvp_args += ['-d', self.prefs.dev_array[self.prefs.sel_dev_idx].id] if self.prefs.pixel_margin_enabled(self.scene_props): uvp_args +=",
"return False def handle_event_spec(self, event): return False def handle_progress_msg(self): if self.op_done: return msg_refresh_interval",
"Islands To Texture' bl_description = \"Adjust scale of selected islands so they are",
"self.curr_phase != UvPackingPhaseCode.RENDER_PRESENTATION and curr_time - self.last_msg_time > self.hang_timeout: self.hang_detected = True def",
"import UvpLabels from .register import check_uvp, unregister_uvp import bmesh import bpy import mathutils",
"the License, or (at your option) any later version. # # This program",
"check once again to be on the safe side self.handle_communication() if not self.op_done:",
"invalid faces found') def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.VALIDATE_UVS)] return",
"return 'Overlap check in progress (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.AREA_MEASUREMENT:",
"self.prefs = get_prefs() self.scene_props = context.scene.uvp2_props self.confirmation_msg = self.get_confirmation_msg() wm = context.window_manager if",
"for details)' self.report({op_status_type}, op_status) self.prefs['op_warnings'] = self.op_warnings # self.prefs.stats_op_warnings.add(warning_msg) def exit_common(self): if self.interactive:",
"Packing Help' bl_idname = 'uvpackmaster2.uv_heuristic_search_help' bl_description = \"Show help for heuristic search\" URL_SUFFIX",
"class UVP2_OT_HeuristicSearchHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing Help' bl_idname = 'uvpackmaster2.uv_heuristic_search_help' bl_description = \"Show",
"UvInvalidIslandCode.INT_PARAM: param_array = IslandParamInfo.get_param_info_array() error_msg = \"Faces with inconsistent {} values found in",
"= 'Pack progress: {} '.format(percent_progress_str) if self.area is not None: end_str = '(press",
"+= ['-d', self.prefs.dev_array[self.prefs.sel_dev_idx].id] if self.prefs.pixel_margin_enabled(self.scene_props): uvp_args += ['-M', str(self.scene_props.pixel_margin)] uvp_args += ['-y', str(self.prefs.pixel_margin_tex_size(self.scene_props,",
"curr_time self.hang_detected = False else: if self.curr_phase != UvPackingPhaseCode.RENDER_PRESENTATION and curr_time - self.last_msg_time",
"UVP2_OT_InvalidTopologyHelp(UVP2_OT_Help): bl_label = 'Invalid Topology Help' bl_idname = 'uvpackmaster2.uv_invalid_topology_help' bl_description = \"Show help",
"== 'EDIT' def check_uvp_retcode(self, retcode): self.prefs.uvp_retcode = retcode if retcode in {UvPackerErrorCode.SUCCESS, UvPackerErrorCode.INVALID_ISLANDS,",
"similar islands (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_ALIGNING: return 'Similar islands",
"cancel = True if cancel: return self.cancel(context) return {'RUNNING_MODAL'} if not self.op_done else",
"= None self.similar_islands_msg = None self.islands_metadata_msg = None except NoUvFaceError as ex: self.set_status('WARNING',",
"'uvpackmaster2.uv_pack' bl_label = 'Pack' bl_description = 'Pack selected UV islands' def __init__(self): self.cancel_sig_sent",
"= '' percent_progress_str = '' for prog in self.progress_array: percent_progress_str += str(prog).rjust(3, '",
"self.uvp_proc.send_signal(os_cancel_sig()) self.cancel_sig_sent = True return True return False def process_result(self): overlap_detected = False",
"> 0: self.raiseUnexpectedOutputError() self.set_status('INFO', 'Similar islands found: ' + str(similar_island_count)) class UVP2_OT_AlignSimilar(UVP2_OT_ProcessSimilar): bl_idname",
"}: if self.curr_phase == UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT: header_str = 'Pixel margin adjustment. ' elif self.prefs.heuristic_enabled(self.scene_props):",
"Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### import",
"timeout reached') self.connection_thread.join() self.check_uvp_retcode(self.uvp_proc.returncode) if not self.p_context.islands_received(): self.raiseUnexpectedOutputError() self.process_invalid_islands() self.process_result() if self.finish_after_op_done(): raise",
"self.op_status is not None: self.prefs['op_status'] = self.op_status op_status_type = self.op_status_type if self.op_status_type is",
"safe side self.handle_communication() if not self.op_done: # Special value indicating a crash self.prefs.uvp_retcode",
"'-I', str(self.scene_props.similarity_threshold)] uvp_args += ['-i', str(self.scene_props.precision)] uvp_args += ['-r', str(90)] if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio",
"read_int_array(self.similar_islands_msg) if not self.prefs.FEATURE_demo: if len(similar_islands) != similar_island_count: self.raiseUnexpectedOutputError() for island_idx in similar_islands:",
"wm = context.window_manager if self.confirmation_msg != '': pix_per_char = 5 dialog_width = pix_per_char",
"self.require_selection(): if selected_cnt == 0: raise NoUvFaceError('No UV face selected') else: if selected_cnt",
"raise OpFinishedException() def finish(self, context): self.exit_common() return {'FINISHED', 'PASS_THROUGH'} def cancel(self, context): self.uvp_proc.terminate()",
"overlap check: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) raise RuntimeError('Unexpected packing phase encountered') def",
"print_backtrace(ex) self.set_status('ERROR', str(ex)) cancel = True except Exception as ex: if in_debug_mode(): print_backtrace(ex)",
"read_area(self, area_msg): return round(force_read_float(area_msg) / self.pack_ratio, 3) class UVP2_OT_PackOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_pack' bl_label",
"if self.handle_event_spec(event): return # Generic event processing code if event.type == 'ESC': raise",
"finish: return self.finish(context) except OpAbortedException: self.set_status('INFO', 'Packer process killed') cancel = True except",
"detection\" URL_SUFFIX = \"similarity-detection\" class UVP2_OT_InvalidTopologyHelp(UVP2_OT_Help): bl_label = 'Invalid Topology Help' bl_idname =",
"to be on the safe side self.handle_communication() if not self.op_done: # Special value",
"bl_label = 'UDIM Support Help' bl_idname = 'uvpackmaster2.uv_udim_support_help' bl_description = \"Show help for",
"webbrowser.open(UvpLabels.HELP_BASEURL + self.URL_SUFFIX) return {'FINISHED'} class UVP2_OT_UvpSetupHelp(UVP2_OT_Help): bl_label = 'UVP Setup Help' bl_idname",
"alive if not self.op_done and self.uvp_proc.poll() is not None: # It should not",
"queue import threading import signal import webbrowser from .utils import * from .pack_context",
"str(ex)) cancel = True except RuntimeError as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', str(ex))",
"def get_uvp_args(self): uvp_args = ['-o', str(self.get_uvp_opcode()), '-I', str(self.scene_props.similarity_threshold)] uvp_args += ['-i', str(self.scene_props.precision)] uvp_args",
"bl_options = {'UNDO'} @classmethod def poll(cls, context): return context.active_object is not None and",
"pack_solution = read_pack_solution(self.pack_solution_msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) self.set_status('INFO', 'Islands aligned') class UVP2_OT_ScaleIslands(bpy.types.Operator): bl_options = {'UNDO'}",
"if self.curr_phase == UvPackingPhaseCode.VALIDATION: return \"Per-face overlap check: {:3}% (press ESC to cancel)\".format(self.progress_array[0])",
"queue.Queue() self.connection_thread = threading.Thread(target=connection_thread_func, args=(self.uvp_proc.stdout, self.progress_queue)) self.connection_thread.daemon = True self.connection_thread.start() self.progress_array = [0]",
"handle_event(self, event): # Kill the UVP process unconditionally if a hang was detected",
"if invalid_face_count > 0: self.set_status('WARNING', 'Number of invalid faces found: ' + str(invalid_face_count))",
"the upper layer wheter it should finish if self.curr_phase == UvPackingPhaseCode.DONE: self.handle_op_done() elif",
"details)' self.report({op_status_type}, op_status) self.prefs['op_warnings'] = self.op_warnings # self.prefs.stats_op_warnings.add(warning_msg) def exit_common(self): if self.interactive: wm",
"elif code == UvInvalidIslandCode.INT_PARAM: param_array = IslandParamInfo.get_param_info_array() error_msg = \"Faces with inconsistent {}",
"= 'Non-Square Packing Help' bl_idname = 'uvpackmaster2.uv_nonsquare_packing_help' bl_description = \"Show help for non-square",
"uvp_args_final += ['-R'] if self.lock_groups_enabled(): uvp_args_final += ['-Q'] if in_debug_mode(): if self.prefs.seed >",
"elif msg_code == UvPackMessageCode.ISLANDS: self.read_islands(msg) elif msg_code == UvPackMessageCode.ISLANDS_METADATA: if self.islands_metadata_msg is not",
"event.type == 'ESC': raise OpCancelledException() elif event.type == 'TIMER': self.handle_communication() def modal(self, context,",
"selected islands\".format(param_array[subcode].NAME) else: self.raiseUnexpectedOutputError() raise InvalidIslandsError(error_msg) def require_selection(self): return True def finish_after_op_done(self): return",
"UvPackMessageCode.ISLANDS: self.read_islands(msg) elif msg_code == UvPackMessageCode.ISLANDS_METADATA: if self.islands_metadata_msg is not None: self.raiseUnexpectedOutputError() self.islands_metadata_msg",
"FakeTimerEvent: def __init__(self): self.type = 'TIMER' self.value = 'NOTHING' self.ctrl = False while",
"layout = self.layout col = layout.column() col.label(text=self.confirmation_msg) def get_confirmation_msg(self): return '' def send_unselected_islands(self):",
"self.prefs.pack_to_others_enabled(self.scene_props) def grouping_enabled(self): return self.prefs.grouping_enabled(self.scene_props) def get_group_method(self): return self.scene_props.group_method def send_rot_step(self): return self.prefs.FEATURE_island_rotation_step",
"class UVP2_OT_NonSquarePackingHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing Help' bl_idname = 'uvpackmaster2.uv_nonsquare_packing_help' bl_description = \"Show",
"op_status_type = self.op_status_type if self.op_status_type is not None else 'INFO' op_status = self.op_status",
"return True return False def process_result(self): overlap_detected = False outside_detected = False if",
"retcode == UvPackerErrorCode.NO_VALID_STATIC_ISLAND: raise RuntimeError(\"'Pack To Others' option enabled, but no unselected island",
"self-intersecting faces, faces overlapping each other' def get_confirmation_msg(self): if self.prefs.FEATURE_demo: return 'WARNING: in",
"msg_code, msg): if msg_code == UvPackMessageCode.AREA: self.area = self.read_area(msg) return True elif msg_code",
"['-q', str(self.pack_ratio)] if self.target_box is not None: self.target_box[0].x *= self.pack_ratio self.target_box[1].x *= self.pack_ratio",
"/ self.pack_ratio, 3) class UVP2_OT_PackOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_pack' bl_label = 'Pack' bl_description =",
"self.prefs.target_box_enable: validate_target_box(self.scene_props) def get_target_box_string(self, target_box): prec = 4 return \"{}:{}:{}:{}\".format( round(target_box[0].x, prec), round(target_box[0].y,",
"return progress_msg_spec if self.curr_phase == UvPackingPhaseCode.INITIALIZATION: return 'Initialization (press ESC to cancel)' if",
"if self.prefs.write_to_file: out_filepath = os.path.join(tempfile.gettempdir(), 'uv_islands.data') out_file = open(out_filepath, 'wb') out_file.write(self.p_context.serialized_maps) out_file.close() uvp_args_final",
"except OpCancelledException: self.set_status('INFO', 'Operation cancelled by the user') cancel = True except InvalidIslandsError",
"send_groups = self.grouping_enabled() and (to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.EXTERNAL) send_lock_groups = self.lock_groups_enabled() send_verts_3d = self.send_verts_3d()",
"if self.prefs.wait_for_debugger: uvp_args_final.append('-G') uvp_args_final += ['-T', str(self.prefs.test_param)] print('Pakcer args: ' + ' '.join(x",
"self.similar_islands_msg is None: self.raiseUnexpectedOutputError() similar_island_count = force_read_int(self.similar_islands_msg) similar_islands = read_int_array(self.similar_islands_msg) if not self.prefs.FEATURE_demo:",
"mode is not supported in this engine edition') if self.grouping_enabled(): if self.get_group_method() ==",
"self.finish(context) except OpAbortedException: self.set_status('INFO', 'Packer process killed') cancel = True except OpCancelledException: self.set_status('INFO',",
"= None def get_confirmation_msg(self): if platform.system() == 'Darwin': active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx",
"texture. For for info regarding non-square packing click the help icon\" def get_scale_factors(self):",
"details. # # You should have received a copy of the GNU General",
"bl_label = 'Validate UVs' bl_description = 'Validate selected UV faces. The validation procedure",
"class UVP2_OT_UdimSupportHelp(UVP2_OT_Help): bl_label = 'UDIM Support Help' bl_idname = 'uvpackmaster2.uv_udim_support_help' bl_description = \"Show",
"execute(self, context): webbrowser.open(UvpLabels.HELP_BASEURL + self.URL_SUFFIX) return {'FINISHED'} class UVP2_OT_UvpSetupHelp(UVP2_OT_Help): bl_label = 'UVP Setup",
"['-r', str(90)] if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) uvp_args += ['-q', str(self.pack_ratio)] return uvp_args",
"RuntimeError('Packer process died unexpectedly') self.handle_progress_msg() except OpFinishedException: finish = True except: raise if",
"UvPackMessageCode.SIMILAR_ISLANDS: if self.similar_islands_msg is not None: self.raiseUnexpectedOutputError() self.similar_islands_msg = msg elif msg_code ==",
"islands) def process_invalid_islands(self): if self.uvp_proc.returncode != UvPackerErrorCode.INVALID_ISLANDS: return if self.invalid_islands_msg is None: self.raiseUnexpectedOutputError()",
"self.progress_queue)) self.connection_thread.daemon = True self.connection_thread.start() self.progress_array = [0] self.progress_msg = '' self.progress_sec_left =",
"faces found') def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.VALIDATE_UVS)] return uvp_args",
"RuntimeError('Could not find a packing device') if not active_dev.supported: raise RuntimeError('Selected packing device",
"iter_str = 'Iter. done: {}. '.format(self.progress_iter_done) else: iter_str = '' if self.progress_sec_left >=",
"of similar islands found is reported, islands will not be selected. Click OK",
"'Unexpected error') cancel = True if cancel: return self.cancel(context) return {'RUNNING_MODAL'} if not",
"self.set_status('INFO', op_status) if overlap_detected: self.add_warning(\"Overlapping islands were detected after packing (check the selected",
"except: raise if finish: return self.finish(context) except OpAbortedException: self.set_status('INFO', 'Packer process killed') cancel",
"self.get_confirmation_msg() wm = context.window_manager if self.confirmation_msg != '': pix_per_char = 5 dialog_width =",
"+= ['-i', str(self.scene_props.precision)] uvp_args += ['-r', str(90)] if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) uvp_args",
"ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, 'Unexpected error') self.p_context.update_meshes() return {'FINISHED'} def get_scale_factors(self): return",
"UvGroupingMethodUvp.EXTERNAL) send_lock_groups = self.lock_groups_enabled() send_verts_3d = self.send_verts_3d() selected_cnt, unselected_cnt = self.p_context.serialize_uv_maps(send_unselected, send_groups, send_rot_step,",
"= get_active_image_ratio(self.p_context.context) self.p_context.scale_selected_faces(self.get_scale_factors()) except RuntimeError as ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, str(ex)) except",
"- no space to pack all islands' self.add_warning(\"Overlap check was performed only on",
"def check_uvp_retcode(self, retcode): self.prefs.uvp_retcode = retcode if retcode in {UvPackerErrorCode.SUCCESS, UvPackerErrorCode.INVALID_ISLANDS, UvPackerErrorCode.NO_SPACE, UvPackerErrorCode.PRE_VALIDATION_FAILED}:",
"program is free software; you can redistribute it and/or # modify it under",
"send_unselected_islands(self): return False def grouping_enabled(self): return False def get_group_method(self): raise RuntimeError('Unexpected grouping requested')",
"if self.prefs.pack_to_others_enabled(self.scene_props): uvp_args += ['-x'] if self.prefs.FEATURE_validation and self.scene_props.pre_validate: uvp_args.append('-v') if self.prefs.normalize_islands_enabled(self.scene_props): uvp_args.append('-L')",
"'' for prog in self.progress_array: percent_progress_str += str(prog).rjust(3, ' ') + '%, '",
"enough.\") def validate_pack_params(self): active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None if",
"except OpFinishedException: finish = True except: raise if finish: return self.finish(context) except OpAbortedException:",
"= '' self.progress_sec_left = -1 self.progress_iter_done = -1 self.progress_last_update_time = 0.0 self.curr_phase =",
"send_rot_step(self): return self.prefs.FEATURE_island_rotation_step and self.scene_props.rot_enable and self.scene_props.island_rot_step_enable def lock_groups_enabled(self): return self.prefs.FEATURE_lock_overlapping and self.scene_props.lock_groups_enable",
"get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.OVERLAP_CHECK)] return uvp_args class UVP2_OT_MeasureAreaOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_measure_area' bl_label",
"def handle_event_spec(self, event): if event.type == 'ESC': if not self.cancel_sig_sent: self.uvp_proc.send_signal(os_cancel_sig()) self.cancel_sig_sent =",
"RuntimeError as ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, str(ex)) except Exception as ex: if",
"self.scene_props.pack_mode] tile_count, tiles_in_row = self.prefs.tile_grid_config(self.scene_props, self.p_context.context) if self.prefs.pack_to_tiles(self.scene_props): uvp_args += ['-V', str(tile_count)] if",
"= 'Pixel Margin Help' bl_idname = 'uvpackmaster2.uv_pixel_margin_help' bl_description = \"Show help for setting",
"= 'Validate UVs' bl_description = 'Validate selected UV faces. The validation procedure looks",
"# Check whether the uvp process is alive if not self.op_done and self.uvp_proc.poll()",
"msg): return False def handle_event_spec(self, event): return False def handle_progress_msg(self): if self.op_done: return",
"if self.curr_phase == UvPackingPhaseCode.DONE: self.handle_op_done() elif msg_code == UvPackMessageCode.INVALID_ISLANDS: if self.invalid_islands_msg is not",
"send_rot_step(self): return False def lock_groups_enabled(self): return False def send_verts_3d(self): return False def read_area(self,",
"self.raiseUnexpectedOutputError() for island_idx in similar_islands: self.p_context.select_island_faces(island_idx, self.p_context.uv_island_faces_list[island_idx], True) else: if len(similar_islands) > 0:",
"it and/or # modify it under the terms of the GNU General Public",
"invalid_face_count > 0: self.set_status('WARNING', 'Number of invalid faces found: ' + str(invalid_face_count)) else:",
"reset_stats(self.prefs) self.p_context = PackContext(context) self.pre_op_initialize() send_unselected = self.send_unselected_islands() send_rot_step = self.send_rot_step() send_groups =",
"self.interactive: wm = self.p_context.context.window_manager wm.event_timer_remove(self._timer) self.p_context.update_meshes() self.report_status() if in_debug_mode(): print('UVP operation time: '",
"selected_cnt, unselected_cnt = self.p_context.serialize_uv_maps(send_unselected, send_groups, send_rot_step, send_lock_groups, send_verts_3d, self.get_group_method() if send_groups else None)",
"a small value and the 'Adjustment Time' is not long enough.\") def validate_pack_params(self):",
"doesn't support packing groups together\") raise RuntimeError('Pack process returned an error') def raiseUnexpectedOutputError(self):",
"procedure looks for invalid UV faces i.e. faces with area close to 0,",
"op_status = self.op_status if len(self.op_warnings) > 0: if op_status_type == 'INFO': op_status_type =",
"dev_name_len = force_read_int(msg) stats.dev_name = msg.read(dev_name_len).decode('ascii') stats.iter_count = force_read_int(msg) stats.total_time = force_read_int(msg) stats.avg_time",
"bl_description = \"Show help for UDIM support\" URL_SUFFIX = \"udim-support\" class UVP2_OT_ManualGroupingHelp(UVP2_OT_Help): bl_label",
"License # along with this program; if not, write to the Free Software",
"def raiseUnexpectedOutputError(self): raise RuntimeError('Unexpected output from the pack process') def set_status(self, status_type, status):",
"Validate pack mode pack_mode = UvPackingMode.get_mode(self.scene_props.pack_mode) if pack_mode.req_feature != '' and not getattr(self.prefs,",
"by the user') cancel = True except InvalidIslandsError as err: self.set_status('ERROR', str(err)) cancel",
"pre_op_initialize(self): pass def execute(self, context): cancel = False self.op_done = False self.uvp_proc =",
"+ end_str return False def handle_uvp_msg_spec(self, msg_code, msg): if msg_code == UvPackMessageCode.AREA: self.area",
"uvp_args += ['-g', self.scene_props.pack_mode] tile_count, tiles_in_row = self.prefs.tile_grid_config(self.scene_props, self.p_context.context) if self.prefs.pack_to_tiles(self.scene_props): uvp_args +=",
"= -1 self.progress_last_update_time = 0.0 self.curr_phase = UvPackingPhaseCode.INITIALIZATION self.invalid_islands_msg = None self.island_flags_msg =",
"UvPackingPhaseCode.DONE: self.handle_op_done() elif msg_code == UvPackMessageCode.INVALID_ISLANDS: if self.invalid_islands_msg is not None: self.raiseUnexpectedOutputError() self.invalid_islands_msg",
"bl_description = \"Show help for handling invalid topology errors\" URL_SUFFIX = \"invalid-topology-issues\" class",
"UvPackerErrorCode.DEVICE_NOT_SUPPORTED: raise RuntimeError(\"Selected device is not supported\") if retcode == UvPackerErrorCode.DEVICE_DOESNT_SUPPORT_GROUPS_TOGETHER: raise RuntimeError(\"Selected",
"device is not supported\") if retcode == UvPackerErrorCode.DEVICE_DOESNT_SUPPORT_GROUPS_TOGETHER: raise RuntimeError(\"Selected device doesn't support",
"def get_confirmation_msg(self): return '' def send_unselected_islands(self): return False def grouping_enabled(self): return False def",
"* from .connection import * from .prefs import * from .os_iface import *",
"False progress_msg_spec = self.get_progress_msg_spec() if progress_msg_spec: return progress_msg_spec if self.curr_phase == UvPackingPhaseCode.INITIALIZATION: return",
"which were packed\") else: op_status = 'Packing done' if self.area is not None:",
"'Pack progress: {} '.format(percent_progress_str) if self.area is not None: end_str = '(press ESC",
"if pack_mode.req_feature != '' and not getattr(self.prefs, 'FEATURE_' + pack_mode.req_feature): raise RuntimeError('Selected packing",
"error') cancel = True if cancel: return self.cancel(context) return {'RUNNING_MODAL'} if not self.op_done",
"None: self.raiseUnexpectedOutputError() self.area_msg = msg elif msg_code == UvPackMessageCode.INVALID_FACES: if self.invalid_faces_msg is not",
"len(self.confirmation_msg) + 50 return wm.invoke_props_dialog(self, width=dialog_width) return self.execute(context) def draw(self, context): layout =",
"bl_idname = 'uvpackmaster2.uv_pack' bl_label = 'Pack' bl_description = 'Pack selected UV islands' def",
"uvp_args class UVP2_OT_ValidateOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_validate' bl_label = 'Validate UVs' bl_description = 'Validate",
"version. # # This program is distributed in the hope that it will",
"= \"heuristic-search\" class UVP2_OT_NonSquarePackingHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing Help' bl_idname = 'uvpackmaster2.uv_nonsquare_packing_help' bl_description",
"get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.MEASURE_AREA)] return uvp_args class UVP2_OT_ValidateOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_validate' bl_label",
"URL_SUFFIX = \"pixel-margin\" class UVP2_OT_IslandRotStepHelp(UVP2_OT_Help): bl_label = 'Island Rotation Step Help' bl_idname =",
"> msg_refresh_interval or new_progress_msg != self.progress_msg: self.progress_last_update_time = now self.progress_msg = new_progress_msg self.report({'INFO'},",
"if not self.prefs.FEATURE_demo: if len(invalid_faces) != invalid_face_count: self.raiseUnexpectedOutputError() if invalid_face_count > 0: #",
"this engine edition') if self.grouping_enabled(): if self.get_group_method() == UvGroupingMethod.SIMILARITY.code: if self.prefs.pack_to_others_enabled(self.scene_props): raise RuntimeError(\"'Pack",
"is not None: self.raiseUnexpectedOutputError() self.similar_islands_msg = msg elif msg_code == UvPackMessageCode.ISLANDS: self.read_islands(msg) elif",
"self.scene_props.pixel_margin_method] uvp_args += ['-Y', str(self.scene_props.pixel_margin_adjust_time)] if self.prefs.fixed_scale_enabled(self.scene_props): uvp_args += ['-O'] uvp_args += ['-F',",
"bl_idname = 'uvpackmaster2.uv_adjust_islands_to_texture' bl_label = 'Adjust Islands To Texture' bl_description = \"Adjust scale",
"= 'uvpackmaster2.uv_adjust_islands_to_texture' bl_label = 'Adjust Islands To Texture' bl_description = \"Adjust scale of",
"self.progress_last_update_time > msg_refresh_interval or new_progress_msg != self.progress_msg: self.progress_last_update_time = now self.progress_msg = new_progress_msg",
"##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software;",
"if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, str(ex)) except Exception as ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'},",
"Texture' bl_description = \"Adjust scale of selected islands so they are suitable for",
"GNU General Public License # as published by the Free Software Foundation; either",
"self.prefs.FEATURE_demo: if self.island_flags_msg is None: self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg) overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags)",
"bl_idname = 'uvpackmaster2.uv_align_similar' bl_label = 'Align Similar' bl_description = \"Align selected islands, so",
"else: self.raiseUnexpectedOutputError() raise InvalidIslandsError(error_msg) def require_selection(self): return True def finish_after_op_done(self): return True def",
"is not None else 'INFO' op_status = self.op_status if len(self.op_warnings) > 0: if",
"'Packer process killed') cancel = True except OpCancelledException: self.set_status('INFO', 'Operation cancelled by the",
".pack_context import * from .connection import * from .prefs import * from .os_iface",
"def send_unselected_islands(self): return True def get_uvp_opcode(self): return UvPackerOpcode.SELECT_SIMILAR def process_result(self): if self.similar_islands_msg is",
"the 'Adjustment Time' is not long enough.\") def validate_pack_params(self): active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if",
"the terms of the GNU General Public License # as published by the",
"UVP process unconditionally if a hang was detected if self.hang_detected and event.type ==",
"get_progress_msg_spec(self): if self.curr_phase in { UvPackingPhaseCode.PACKING, UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT }: if self.curr_phase == UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT: header_str",
"round(force_read_float(area_msg) / self.pack_ratio, 3) class UVP2_OT_PackOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_pack' bl_label = 'Pack' bl_description",
"None if active_dev is not None and active_dev.id.startswith('cuda'): return UvpLabels.CUDA_MACOS_CONFIRM_MSG if self.prefs.pack_groups_together(self.scene_props) and",
"print_backtrace(ex) self.set_status('ERROR', 'Unexpected error') cancel = True if cancel: return self.cancel(context) return {'RUNNING_MODAL'}",
"cancel)' if self.curr_phase == UvPackingPhaseCode.RENDER_PRESENTATION: return 'Close the demo window to finish' if",
"(press ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.VALIDATION: return \"Per-face overlap check: {:3}%",
"for non-square packing\" URL_SUFFIX = \"non-square-packing\" class UVP2_OT_SimilarityDetectionHelp(UVP2_OT_Help): bl_label = 'Similarity Detection Help'",
"apply result) ' else: end_str = '(press ESC to cancel) ' return header_str",
"*= self.pack_ratio self.target_box[1].x *= self.pack_ratio else: self.target_box = (Vector((0.0, 0.0)), Vector((self.pack_ratio, 1.0))) if",
"['-l', self.scene_props.lock_overlapping_mode] if self.prefs.pack_to_others_enabled(self.scene_props): uvp_args += ['-x'] if self.prefs.FEATURE_validation and self.scene_props.pre_validate: uvp_args.append('-v') if",
"cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.OVERLAP_CHECK: return 'Overlap check in progress (press ESC to",
"out_file.write(self.p_context.serialized_maps) out_file.close() uvp_args_final = [get_uvp_execpath(), '-E', '-e', str(UvTopoAnalysisLevel.FORCE_EXTENDED), '-t', str(self.prefs.thread_count)] + self.get_uvp_args() if",
"self.progress_last_update_time = now self.progress_msg = new_progress_msg self.report({'INFO'}, self.progress_msg) def handle_uvp_msg(self, msg): msg_code =",
"For more info regarding similarity detection click the help button\" def get_confirmation_msg(self): if",
"support packing groups together\") raise RuntimeError('Pack process returned an error') def raiseUnexpectedOutputError(self): raise",
"click the help icon\" def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return (1.0 / ratio,",
"# GNU General Public License for more details. # # You should have",
"self.prefs.stats_array.add() dev_name_len = force_read_int(msg) stats.dev_name = msg.read(dev_name_len).decode('ascii') stats.iter_count = force_read_int(msg) stats.total_time = force_read_int(msg)",
"= \"similarity-detection\" class UVP2_OT_InvalidTopologyHelp(UVP2_OT_Help): bl_label = 'Invalid Topology Help' bl_idname = 'uvpackmaster2.uv_invalid_topology_help' bl_description",
"= 'uvpackmaster2.uv_similarity_detection_help' bl_description = \"Show help for similarity detection\" URL_SUFFIX = \"similarity-detection\" class",
"have similar shape to islands which are already selected. For more info regarding",
"True: event = FakeTimerEvent() ret = self.modal(context, event) if ret.intersection({'FINISHED', 'CANCELLED'}): return ret",
"selection mode if self.p_context.context.tool_settings.use_uv_select_sync: self.p_context.context.tool_settings.mesh_select_mode = (False, False, True) else: self.p_context.context.tool_settings.uv_select_mode = 'FACE'",
"URL_SUFFIX = \"invalid-topology-issues\" class UVP2_OT_PixelMarginHelp(UVP2_OT_Help): bl_label = 'Pixel Margin Help' bl_idname = 'uvpackmaster2.uv_pixel_margin_help'",
"URL_SUFFIX = \"udim-support\" class UVP2_OT_ManualGroupingHelp(UVP2_OT_Help): bl_label = 'Manual Grouping Help' bl_idname = 'uvpackmaster2.uv_manual_grouping_help'",
"the GNU General Public License # as published by the Free Software Foundation;",
"header_str = '' if self.progress_iter_done >= 0: iter_str = 'Iter. done: {}. '.format(self.progress_iter_done)",
"in this engine edition') if self.grouping_enabled(): if self.get_group_method() == UvGroupingMethod.SIMILARITY.code: if self.prefs.pack_to_others_enabled(self.scene_props): raise",
"self.prefs.normalize_islands_enabled(self.scene_props): uvp_args.append('-L') if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: self.target_box = self.prefs.target_box(self.scene_props) if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio =",
"range(progress_size): self.progress_array[i] = force_read_int(msg) self.progress_sec_left = force_read_int(msg) self.progress_iter_done = force_read_int(msg) # Inform the",
"+ pack_mode.req_feature): raise RuntimeError('Selected packing mode is not supported in this engine edition')",
"else: self.p_context.context.tool_settings.uv_select_mode = 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) else: if len(invalid_faces) > 0: self.raiseUnexpectedOutputError()",
"get_active_image_ratio(self.p_context.context) self.p_context.scale_selected_faces(self.get_scale_factors()) except RuntimeError as ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, str(ex)) except Exception",
"= True def handle_event(self, event): # Kill the UVP process unconditionally if a",
"if self.prefs.lock_overlap_enabled(self.scene_props): uvp_args += ['-l', self.scene_props.lock_overlapping_mode] if self.prefs.pack_to_others_enabled(self.scene_props): uvp_args += ['-x'] if self.prefs.FEATURE_validation",
"operation time: ' + str(time.time() - self.start_time)) def read_islands(self, islands_msg): islands = []",
"self.handle_uvp_msg_spec(msg_code, msg): return if msg_code == UvPackMessageCode.PROGRESS_REPORT: self.curr_phase = force_read_int(msg) progress_size = force_read_int(msg)",
"Switch to the face selection mode if self.p_context.context.tool_settings.use_uv_select_sync: self.p_context.context.tool_settings.mesh_select_mode = (False, False, True)",
"def __init__(self): self.type = 'TIMER' self.value = 'NOTHING' self.ctrl = False while True:",
"'No overlapping islands detected') def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.OVERLAP_CHECK)]",
"handle_uvp_msg_spec(self, msg_code, msg): return False def handle_event_spec(self, event): return False def handle_progress_msg(self): if",
"self.progress_msg = new_progress_msg self.report({'INFO'}, self.progress_msg) def handle_uvp_msg(self, msg): msg_code = force_read_int(msg) if self.handle_uvp_msg_spec(msg_code,",
"overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags) if self.area is not None: self.prefs.stats_area = self.area if",
"uvp_args class UVP2_OT_OverlapCheckOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_overlap_check' bl_label = 'Overlap Check' bl_description = 'Check",
"class UVP2_OT_MeasureAreaOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_measure_area' bl_label = 'Measure Area' bl_description = 'Measure area",
"##### # # This program is free software; you can redistribute it and/or",
"+ str(self.area) self.set_status('INFO', op_status) if overlap_detected: self.add_warning(\"Overlapping islands were detected after packing (check",
"msg elif msg_code == UvPackMessageCode.ISLAND_FLAGS: if self.island_flags_msg is not None: self.raiseUnexpectedOutputError() self.island_flags_msg =",
"stats.avg_time = force_read_int(msg) return True return False def handle_event_spec(self, event): if event.type ==",
"published by the Free Software Foundation; either version 2 # of the License,",
"str(self.scene_props.group_compactness)] if self.prefs.multi_device_enabled(self.scene_props): uvp_args.append('-u') if self.prefs.lock_overlap_enabled(self.scene_props): uvp_args += ['-l', self.scene_props.lock_overlapping_mode] if self.prefs.pack_to_others_enabled(self.scene_props): uvp_args",
"True return False def process_result(self): overlap_detected = False outside_detected = False if self.invalid_faces_msg",
"UVP2_OT_OverlapCheckOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_overlap_check' bl_label = 'Overlap Check' bl_description = 'Check wheter selected",
"read_pack_solution(self.pack_solution_msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) self.set_status('INFO', 'Islands aligned') class UVP2_OT_ScaleIslands(bpy.types.Operator): bl_options = {'UNDO'} @classmethod def",
"pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.VALIDATE_UVS)] return uvp_args class UVP2_OT_ProcessSimilar(UVP2_OT_PackOperatorGeneric): def validate_pack_params(self):",
"0 while True: try: item = self.progress_queue.get_nowait() except queue.Empty as ex: break if",
"mode if self.p_context.context.tool_settings.use_uv_select_sync: self.p_context.context.tool_settings.mesh_select_mode = (False, False, True) else: self.p_context.context.tool_settings.uv_select_mode = 'FACE' self.p_context.select_all_faces(False)",
"# modify it under the terms of the GNU General Public License #",
"close to 0, self-intersecting faces, faces overlapping each other' def get_confirmation_msg(self): if self.prefs.FEATURE_demo:",
"None: self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg) overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags) if self.area is not",
"the selected islands. Check the Help panel to learn more\" elif code ==",
"when 'Pixel Padding' is set to a small value and the 'Adjustment Time'",
"RuntimeError('Selected packing mode is not supported in this engine edition') if self.grouping_enabled(): if",
"def process_result(self): if self.similar_islands_msg is None: self.raiseUnexpectedOutputError() similar_island_count = force_read_int(self.similar_islands_msg) similar_islands = read_int_array(self.similar_islands_msg)",
"target_box): prec = 4 return \"{}:{}:{}:{}\".format( round(target_box[0].x, prec), round(target_box[0].y, prec), round(target_box[1].x, prec), round(target_box[1].y,",
"# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General",
"self.curr_phase == UvPackingPhaseCode.RENDER_PRESENTATION: return 'Close the demo window to finish' if self.curr_phase ==",
"if self.progress_sec_left >= 0: time_left_str = \"Time left: {} sec. \".format(self.progress_sec_left) else: time_left_str",
"return self.prefs.grouping_enabled(self.scene_props) def get_group_method(self): return self.scene_props.group_method def send_rot_step(self): return self.prefs.FEATURE_island_rotation_step and self.scene_props.rot_enable and",
"= False @classmethod def poll(cls, context): prefs = get_prefs() return prefs.uvp_initialized and context.active_object",
"a hang was detected if self.hang_detected and event.type == 'ESC': raise OpAbortedException() if",
"overlap each other' def process_result(self): if self.island_flags_msg is None: self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg)",
"elif msg_code == UvPackMessageCode.SIMILAR_ISLANDS: if self.similar_islands_msg is not None: self.raiseUnexpectedOutputError() self.similar_islands_msg = msg",
"uvp_args = ['-o', str(UvPackerOpcode.PACK), '-i', str(self.scene_props.precision), '-m', str(self.scene_props.margin)] uvp_args += ['-d', self.prefs.dev_array[self.prefs.sel_dev_idx].id] if",
"self.process_result() if self.finish_after_op_done(): raise OpFinishedException() def finish(self, context): self.exit_common() return {'FINISHED', 'PASS_THROUGH'} def",
"return (ratio, 1.0) class UVP2_OT_Help(bpy.types.Operator): bl_label = 'Help' def execute(self, context): webbrowser.open(UvpLabels.HELP_BASEURL +",
"uvp_args += ['-q', str(self.pack_ratio)] if self.target_box is not None: self.target_box[0].x *= self.pack_ratio self.target_box[1].x",
"def handle_progress_msg(self): if self.op_done: return msg_refresh_interval = 2.0 new_progress_msg = self.get_progress_msg() if not",
"handle_event_spec(self, event): return False def handle_progress_msg(self): if self.op_done: return msg_refresh_interval = 2.0 new_progress_msg",
"context.window_manager if self.confirmation_msg != '': pix_per_char = 5 dialog_width = pix_per_char * len(self.confirmation_msg)",
"bl_label = 'UVP Setup Help' bl_idname = 'uvpackmaster2.uv_uvp_setup_help' bl_description = \"Show help for",
"'Pack' bl_description = 'Pack selected UV islands' def __init__(self): self.cancel_sig_sent = False self.area",
"raise RuntimeError('Unexpected output from the connection thread') msg_received += 1 curr_time = time.time()",
"str(self.scene_props.pixel_margin_adjust_time)] if self.prefs.fixed_scale_enabled(self.scene_props): uvp_args += ['-O'] uvp_args += ['-F', self.scene_props.fixed_scale_strategy] if self.prefs.FEATURE_island_rotation: if",
"if not self.op_done: # Special value indicating a crash self.prefs.uvp_retcode = -1 raise",
"if event.type == 'ESC': if not self.cancel_sig_sent: self.uvp_proc.send_signal(os_cancel_sig()) self.cancel_sig_sent = True return True",
"time_left_str = \"Time left: {} sec. \".format(self.progress_sec_left) else: time_left_str = '' percent_progress_str =",
"if len(invalid_islands) == 0: self.raiseUnexpectedOutputError() self.p_context.handle_invalid_islands(invalid_islands) if code == UvInvalidIslandCode.TOPOLOGY: error_msg = \"Invalid",
"output from the pack process') def set_status(self, status_type, status): self.op_status_type = status_type self.op_status",
"window=context.window) wm.modal_handler_add(self) return {'RUNNING_MODAL'} class FakeTimerEvent: def __init__(self): self.type = 'TIMER' self.value =",
"['-a', str(to_uvp_group_method(self.get_group_method()))] if self.send_rot_step(): uvp_args_final += ['-R'] if self.lock_groups_enabled(): uvp_args_final += ['-Q'] if",
"None) if self.require_selection(): if selected_cnt == 0: raise NoUvFaceError('No UV face selected') else:",
"UVP2_OT_ProcessSimilar(UVP2_OT_PackOperatorGeneric): def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(self.get_uvp_opcode()), '-I', str(self.scene_props.similarity_threshold)] uvp_args",
"+= 1 curr_time = time.time() if msg_received > 0: self.last_msg_time = curr_time self.hang_detected",
"were detected after packing (check the selected islands). Consider increasing the 'Precision' parameter.",
"def set_status(self, status_type, status): self.op_status_type = status_type self.op_status = status def add_warning(self, warn_msg):",
"return 'Similar islands aligning (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.RENDER_PRESENTATION: return",
"return msg_received = 0 while True: try: item = self.progress_queue.get_nowait() except queue.Empty as",
"InvalidIslandsError(Exception): pass class NoUvFaceError(Exception): pass class UVP2_OT_PackOperatorGeneric(bpy.types.Operator): bl_options = {'UNDO'} MODAL_INTERVAL_S = 0.1",
"and/or # modify it under the terms of the GNU General Public License",
"1.0 self.target_box = None self.op_status_type = None self.op_status = None self.op_warnings = []",
"0: self.raiseUnexpectedOutputError() if invalid_face_count > 0: self.set_status('WARNING', 'Number of invalid faces found: '",
"= force_read_int(msg) if self.handle_uvp_msg_spec(msg_code, msg): return if msg_code == UvPackMessageCode.PROGRESS_REPORT: self.curr_phase = force_read_int(msg)",
"send_unselected_islands(self): return True def get_uvp_opcode(self): return UvPackerOpcode.SELECT_SIMILAR def process_result(self): if self.similar_islands_msg is None:",
"import * from .os_iface import * from .island_params import * from .labels import",
"and self.uvp_proc.poll() is not None: # It should not be required to but",
"None: self.raiseUnexpectedOutputError() pack_solution = read_pack_solution(self.pack_solution_msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) self.set_status('INFO', 'Islands aligned') class UVP2_OT_ScaleIslands(bpy.types.Operator): bl_options",
"__init__(self): self.cancel_sig_sent = False self.area = None def get_confirmation_msg(self): if platform.system() == 'Darwin':",
"similar shape to islands which are already selected. For more info regarding similarity",
"is not None: self.prefs['op_status'] = self.op_status op_status_type = self.op_status_type if self.op_status_type is not",
"item = self.progress_queue.get_nowait() except queue.Empty as ex: break if isinstance(item, str): raise RuntimeError(item)",
"the active texture. CAUTION: this operator should be used only when packing to",
"class UVP2_OT_PackOperatorGeneric(bpy.types.Operator): bl_options = {'UNDO'} MODAL_INTERVAL_S = 0.1 interactive = False @classmethod def",
"NoUvFaceError('No UV face selected') else: if selected_cnt + unselected_cnt == 0: raise NoUvFaceError('No",
"= False self.hang_timeout = 10.0 # Start progress monitor thread self.progress_queue = queue.Queue()",
"def get_confirmation_msg(self): if platform.system() == 'Darwin': active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array)",
"islands. Check the Help panel to learn more\" elif code == UvInvalidIslandCode.INT_PARAM: param_array",
"'Pre-validation failed. Number of invalid faces found: ' + str(invalid_face_count) + '. Packing",
"+= ['-Y', str(self.scene_props.pixel_margin_adjust_time)] if self.prefs.fixed_scale_enabled(self.scene_props): uvp_args += ['-O'] uvp_args += ['-F', self.scene_props.fixed_scale_strategy] if",
"similar islands found is reported, islands will not be selected. Click OK to",
"active_dev is not None and active_dev.id.startswith('cuda'): return UvpLabels.CUDA_MACOS_CONFIRM_MSG if self.prefs.pack_groups_together(self.scene_props) and not self.prefs.heuristic_enabled(self.scene_props):",
"if self.prefs.pack_to_tiles(self.scene_props): uvp_args += ['-V', str(tile_count)] if self.prefs.tiles_enabled(self.scene_props): uvp_args += ['-C', str(tiles_in_row)] if",
"BLOCK ##### import subprocess import queue import threading import signal import webbrowser from",
"Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK",
"output from the connection thread') msg_received += 1 curr_time = time.time() if msg_received",
"'Unexpected error') cancel = True if self.p_context is not None: self.p_context.update_meshes() if cancel:",
"not None: self.raiseUnexpectedOutputError() self.invalid_faces_msg = msg elif msg_code == UvPackMessageCode.SIMILAR_ISLANDS: if self.similar_islands_msg is",
"cancel: if self.uvp_proc is not None: self.uvp_proc.terminate() self.report_status() return {'FINISHED'} if self.interactive: wm",
"if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: validate_target_box(self.scene_props) def get_target_box_string(self, target_box): prec = 4 return \"{}:{}:{}:{}\".format(",
"try: self.handle_event(event) # Check whether the uvp process is alive if not self.op_done",
"GPL LICENSE BLOCK ##### # # This program is free software; you can",
"self.curr_phase in { UvPackingPhaseCode.PACKING, UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT }: if self.curr_phase == UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT: header_str = 'Pixel",
"enabled, but no unselected island found in the packing box\") if retcode ==",
"unselected_cnt == 0: raise NoUvFaceError('No UV face visible') self.validate_pack_params() if self.prefs.write_to_file: out_filepath =",
"x in uvp_args_final)) creation_flags = os_uvp_creation_flags() popen_args = dict() if creation_flags is not",
"'EDIT' def execute(self, context): try: self.p_context = PackContext(context) ratio = get_active_image_ratio(self.p_context.context) self.p_context.scale_selected_faces(self.get_scale_factors()) except",
"= \"Undo adjustment performed by the 'Adjust Islands To Texture' operator so islands",
"Help' bl_idname = 'uvpackmaster2.uv_manual_grouping_help' bl_description = \"Show help for manual grouping\" URL_SUFFIX =",
"True: try: item = self.progress_queue.get_nowait() except queue.Empty as ex: break if isinstance(item, str):",
"class UVP2_OT_InvalidTopologyHelp(UVP2_OT_Help): bl_label = 'Invalid Topology Help' bl_idname = 'uvpackmaster2.uv_invalid_topology_help' bl_description = \"Show",
"'Pack selected UV islands' def __init__(self): self.cancel_sig_sent = False self.area = None def",
"elif self.prefs.heuristic_enabled(self.scene_props): header_str = 'Current area: {}. '.format(self.area if self.area is not None",
"class UVP2_OT_ScaleIslands(bpy.types.Operator): bl_options = {'UNDO'} @classmethod def poll(cls, context): return context.active_object is not",
"== UvPackingPhaseCode.DONE: self.handle_op_done() elif msg_code == UvPackMessageCode.INVALID_ISLANDS: if self.invalid_islands_msg is not None: self.raiseUnexpectedOutputError()",
"self.modal(context, event) if ret.intersection({'FINISHED', 'CANCELLED'}): return ret time.sleep(self.MODAL_INTERVAL_S) def invoke(self, context, event): self.interactive",
"'': pix_per_char = 5 dialog_width = pix_per_char * len(self.confirmation_msg) + 50 return wm.invoke_props_dialog(self,",
"get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.PACK), '-i', str(self.scene_props.precision), '-m', str(self.scene_props.margin)] uvp_args += ['-d', self.prefs.dev_array[self.prefs.sel_dev_idx].id]",
"self.invalid_faces_msg is None: self.raiseUnexpectedOutputError() invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces = read_int_array(self.invalid_faces_msg) if not self.prefs.FEATURE_demo:",
"# of the License, or (at your option) any later version. # #",
"self.connection_thread.daemon = True self.connection_thread.start() self.progress_array = [0] self.progress_msg = '' self.progress_sec_left = -1",
"URL_SUFFIX = \"similarity-detection\" class UVP2_OT_InvalidTopologyHelp(UVP2_OT_Help): bl_label = 'Invalid Topology Help' bl_idname = 'uvpackmaster2.uv_invalid_topology_help'",
"faces found: ' + str(invalid_face_count) + '. Packing aborted') return if not self.prefs.FEATURE_demo:",
"'uvpackmaster2.uv_udim_support_help' bl_description = \"Show help for UDIM support\" URL_SUFFIX = \"udim-support\" class UVP2_OT_ManualGroupingHelp(UVP2_OT_Help):",
"the pack process') def set_status(self, status_type, status): self.op_status_type = status_type self.op_status = status",
"webbrowser from .utils import * from .pack_context import * from .connection import *",
"UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT: header_str = 'Pixel margin adjustment. ' elif self.prefs.heuristic_enabled(self.scene_props): header_str = 'Current area:",
"by similarity\") if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: validate_target_box(self.scene_props) def get_target_box_string(self, target_box): prec = 4",
"if self.prefs.FEATURE_validation and self.scene_props.pre_validate: uvp_args.append('-v') if self.prefs.normalize_islands_enabled(self.scene_props): uvp_args.append('-L') if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: self.target_box",
"self.raiseUnexpectedOutputError() if invalid_face_count > 0: # Switch to the face selection mode if",
"only on the islands which were packed\") else: op_status = 'Packing done' if",
"self.prefs.write_to_file: out_filepath = os.path.join(tempfile.gettempdir(), 'uv_islands.data') out_file = open(out_filepath, 'wb') out_file.write(self.p_context.serialized_maps) out_file.close() uvp_args_final =",
"== UvPackingPhaseCode.TOPOLOGY_ANALYSIS: return \"Topology analysis: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase ==",
"len(self.op_warnings) > 0: if op_status_type == 'INFO': op_status_type = 'WARNING' op_status += '.",
"'Islands aligned') class UVP2_OT_ScaleIslands(bpy.types.Operator): bl_options = {'UNDO'} @classmethod def poll(cls, context): return context.active_object",
"2.0 new_progress_msg = self.get_progress_msg() if not new_progress_msg: return now = time.time() if now",
"overlapping islands detected') def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.OVERLAP_CHECK)] return",
"crash self.prefs.uvp_retcode = -1 raise RuntimeError('Packer process died unexpectedly') self.handle_progress_msg() except OpFinishedException: finish",
"is not None and active_dev.id.startswith('cuda'): return UvpLabels.CUDA_MACOS_CONFIRM_MSG if self.prefs.pack_groups_together(self.scene_props) and not self.prefs.heuristic_enabled(self.scene_props): return",
"info regarding similarity detection click the help button\" def get_uvp_opcode(self): return UvPackerOpcode.ALIGN_SIMILAR def",
"uvp_args += ['-C', str(tiles_in_row)] if self.grouping_enabled(): if to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.SIMILARITY: uvp_args += ['-I',",
"print_backtrace(ex) self.set_status('ERROR', 'Unexpected error') cancel = True if self.p_context is not None: self.p_context.update_meshes()",
"'uvpackmaster2.uv_nonsquare_packing_help' bl_description = \"Show help for non-square packing\" URL_SUFFIX = \"non-square-packing\" class UVP2_OT_SimilarityDetectionHelp(UVP2_OT_Help):",
"msg): return if msg_code == UvPackMessageCode.PROGRESS_REPORT: self.curr_phase = force_read_int(msg) progress_size = force_read_int(msg) if",
"is None: self.raiseUnexpectedOutputError() code = force_read_int(self.invalid_islands_msg) subcode = force_read_int(self.invalid_islands_msg) invalid_islands = read_int_array(self.invalid_islands_msg) if",
"self.confirmation_msg != '': pix_per_char = 5 dialog_width = pix_per_char * len(self.confirmation_msg) + 50",
"False outside_detected = False if self.invalid_faces_msg is not None: invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces",
"= ['-o', str(UvPackerOpcode.PACK), '-i', str(self.scene_props.precision), '-m', str(self.scene_props.margin)] uvp_args += ['-d', self.prefs.dev_array[self.prefs.sel_dev_idx].id] if self.prefs.pixel_margin_enabled(self.scene_props):",
"{} values found in the selected islands\".format(param_array[subcode].NAME) else: self.raiseUnexpectedOutputError() raise InvalidIslandsError(error_msg) def require_selection(self):",
"context): prefs = get_prefs() return prefs.uvp_initialized and context.active_object is not None and context.active_object.mode",
"open(out_filepath, 'wb') out_file.write(self.p_context.serialized_maps) out_file.close() uvp_args_final = [get_uvp_execpath(), '-E', '-e', str(UvTopoAnalysisLevel.FORCE_EXTENDED), '-t', str(self.prefs.thread_count)] +",
"tile_count, tiles_in_row = self.prefs.tile_grid_config(self.scene_props, self.p_context.context) if self.prefs.pack_to_tiles(self.scene_props): uvp_args += ['-V', str(tile_count)] if self.prefs.tiles_enabled(self.scene_props):",
"self.raiseUnexpectedOutputError() pack_solution = read_pack_solution(self.pack_solution_msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) self.set_status('INFO', 'Islands aligned') class UVP2_OT_ScaleIslands(bpy.types.Operator): bl_options =",
"self.connection_thread.start() self.progress_array = [0] self.progress_msg = '' self.progress_sec_left = -1 self.progress_iter_done = -1",
"the help button\" def get_confirmation_msg(self): if self.prefs.FEATURE_demo: return 'WARNING: in the demo mode",
"(press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_ANALYSIS: return \"Topology analysis: {:3}% (press",
"return False def read_area(self, area_msg): return round(force_read_float(area_msg) / self.pack_ratio, 3) class UVP2_OT_PackOperator(UVP2_OT_PackOperatorGeneric): bl_idname",
"= 'Similarity Detection Help' bl_idname = 'uvpackmaster2.uv_similarity_detection_help' bl_description = \"Show help for similarity",
"cancel = True except InvalidIslandsError as err: self.set_status('ERROR', str(err)) cancel = True except",
"is not None: popen_args['creationflags'] = creation_flags self.uvp_proc = subprocess.Popen(uvp_args_final, stdin=subprocess.PIPE, stdout=subprocess.PIPE, **popen_args) out_stream",
"raise RuntimeError(\"Selected device doesn't support packing groups together\") raise RuntimeError('Pack process returned an",
"self.op_done: # Special value indicating a crash self.prefs.uvp_retcode = -1 raise RuntimeError('Packer process",
"if creation_flags is not None: popen_args['creationflags'] = creation_flags self.uvp_proc = subprocess.Popen(uvp_args_final, stdin=subprocess.PIPE, stdout=subprocess.PIPE,",
"else: rot_step_value = -1 uvp_args += ['-r', str(rot_step_value)] if self.prefs.heuristic_enabled(self.scene_props): uvp_args += ['-h',",
"Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,",
"subcode = force_read_int(self.invalid_islands_msg) invalid_islands = read_int_array(self.invalid_islands_msg) if len(invalid_islands) == 0: self.raiseUnexpectedOutputError() self.p_context.handle_invalid_islands(invalid_islands) if",
"= True self.connection_thread.start() self.progress_array = [0] self.progress_msg = '' self.progress_sec_left = -1 self.progress_iter_done",
"bl_description = 'Measure area of selected UV islands' def process_result(self): if self.area_msg is",
"UvPackerOpcode.SELECT_SIMILAR def process_result(self): if self.similar_islands_msg is None: self.raiseUnexpectedOutputError() similar_island_count = force_read_int(self.similar_islands_msg) similar_islands =",
"if self.area is not None: self.prefs.stats_area = self.area if self.uvp_proc.returncode == UvPackerErrorCode.NO_SPACE: op_status",
"for i in range(progress_size): self.progress_array[i] = force_read_int(msg) self.progress_sec_left = force_read_int(msg) self.progress_iter_done = force_read_int(msg)",
"* from .labels import UvpLabels from .register import check_uvp, unregister_uvp import bmesh import",
"return '' def send_unselected_islands(self): return False def grouping_enabled(self): return False def get_group_method(self): raise",
"str(self.prefs.pixel_margin_tex_size(self.scene_props, self.p_context.context))] if self.prefs.pixel_padding_enabled(self.scene_props): uvp_args += ['-N', str(self.scene_props.pixel_padding)] uvp_args += ['-W', self.scene_props.pixel_margin_method] uvp_args",
"regarding similarity detection click the help button\" def get_confirmation_msg(self): if self.prefs.FEATURE_demo: return 'WARNING:",
"= 'Iter. done: {}. '.format(self.progress_iter_done) else: iter_str = '' if self.progress_sec_left >= 0:",
"new_progress_msg = self.get_progress_msg() if not new_progress_msg: return now = time.time() if now -",
"'FEATURE_' + pack_mode.req_feature): raise RuntimeError('Selected packing mode is not supported in this engine",
"or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License",
"self.grouping_enabled(): if to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.SIMILARITY: uvp_args += ['-I', str(self.scene_props.similarity_threshold)] if self.prefs.pack_groups_together(self.scene_props): uvp_args +=",
"self.pre_op_initialize() send_unselected = self.send_unselected_islands() send_rot_step = self.send_rot_step() send_groups = self.grouping_enabled() and (to_uvp_group_method(self.get_group_method()) ==",
"raise RuntimeError(\"'Pre-Rotation Disable' option must be off in order to group by similarity\")",
"\"Show help for similarity detection\" URL_SUFFIX = \"similarity-detection\" class UVP2_OT_InvalidTopologyHelp(UVP2_OT_Help): bl_label = 'Invalid",
"not None: self.raiseUnexpectedOutputError() self.similar_islands_msg = msg elif msg_code == UvPackMessageCode.ISLANDS: self.read_islands(msg) elif msg_code",
"bl_description = \"Show help for heuristic search\" URL_SUFFIX = \"heuristic-search\" class UVP2_OT_NonSquarePackingHelp(UVP2_OT_Help): bl_label",
"'(press ESC to cancel) ' return header_str + iter_str + time_left_str + progress_str",
"'ESC': if not self.cancel_sig_sent: self.uvp_proc.send_signal(os_cancel_sig()) self.cancel_sig_sent = True return True return False def",
"bl_idname = 'uvpackmaster2.uv_overlap_check' bl_label = 'Overlap Check' bl_description = 'Check wheter selected UV",
"grouping requested') def send_rot_step(self): return False def lock_groups_enabled(self): return False def send_verts_3d(self): return",
"on per-island level\" URL_SUFFIX = \"island-rotation-step\" class UVP2_OT_UdimSupportHelp(UVP2_OT_Help): bl_label = 'UDIM Support Help'",
"self.raiseUnexpectedOutputError() self.set_status('INFO', 'Similar islands found: ' + str(similar_island_count)) class UVP2_OT_AlignSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_align_similar'",
"= \"Show help for heuristic search\" URL_SUFFIX = \"heuristic-search\" class UVP2_OT_NonSquarePackingHelp(UVP2_OT_Help): bl_label =",
"URL_SUFFIX = \"non-square-packing\" class UVP2_OT_SimilarityDetectionHelp(UVP2_OT_Help): bl_label = 'Similarity Detection Help' bl_idname = 'uvpackmaster2.uv_similarity_detection_help'",
"UVP2_OT_PackOperatorGeneric(bpy.types.Operator): bl_options = {'UNDO'} MODAL_INTERVAL_S = 0.1 interactive = False @classmethod def poll(cls,",
"force_read_int(msg) stats.avg_time = force_read_int(msg) return True return False def handle_event_spec(self, event): if event.type",
"if self.get_group_method() == UvGroupingMethod.SIMILARITY.code: if self.prefs.pack_to_others_enabled(self.scene_props): raise RuntimeError(\"'Pack To Others' is not supported",
"self.p_context is not None: self.p_context.update_meshes() if cancel: if self.uvp_proc is not None: self.uvp_proc.terminate()",
"if self.uvp_proc is not None: self.uvp_proc.terminate() self.report_status() return {'FINISHED'} if self.interactive: wm =",
"if self.scene_props.rot_enable: rot_step_value = self.scene_props.rot_step if self.scene_props.prerot_disable: uvp_args += ['-w'] else: rot_step_value =",
"= creation_flags self.uvp_proc = subprocess.Popen(uvp_args_final, stdin=subprocess.PIPE, stdout=subprocess.PIPE, **popen_args) out_stream = self.uvp_proc.stdin out_stream.write(self.p_context.serialized_maps) out_stream.flush()",
"bl_label = 'Manual Grouping Help' bl_idname = 'uvpackmaster2.uv_manual_grouping_help' bl_description = \"Show help for",
"self.invalid_faces_msg = None self.similar_islands_msg = None self.islands_metadata_msg = None except NoUvFaceError as ex:",
"each other' def get_confirmation_msg(self): if self.prefs.FEATURE_demo: return 'WARNING: in the demo mode only",
"the demo mode only the number of similar islands found is reported, islands",
"in the selected islands\".format(param_array[subcode].NAME) else: self.raiseUnexpectedOutputError() raise InvalidIslandsError(error_msg) def require_selection(self): return True def",
"and context.active_object.mode == 'EDIT' def check_uvp_retcode(self, retcode): self.prefs.uvp_retcode = retcode if retcode in",
"order to group by similarity\") if self.scene_props.prerot_disable: raise RuntimeError(\"'Pre-Rotation Disable' option must be",
"self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) return True elif msg_code == UvPackMessageCode.BENCHMARK: stats = self.prefs.stats_array.add() dev_name_len =",
"time.time() if now - self.progress_last_update_time > msg_refresh_interval or new_progress_msg != self.progress_msg: self.progress_last_update_time =",
"cancel = True except Exception as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', 'Unexpected error')",
"program is distributed in the hope that it will be useful, # but",
"are outside their packing box after packing (check the selected islands). This usually",
"bl_idname = 'uvpackmaster2.uv_invalid_topology_help' bl_description = \"Show help for handling invalid topology errors\" URL_SUFFIX",
"self.prefs.FEATURE_target_box and self.prefs.target_box_enable: self.target_box = self.prefs.target_box(self.scene_props) if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio = get_active_image_ratio(self.p_context.context) if self.pack_ratio",
"bl_idname = 'uvpackmaster2.uv_pixel_margin_help' bl_description = \"Show help for setting margin in pixels\" URL_SUFFIX",
"distributed in the hope that it will be useful, # but WITHOUT ANY",
"return header_str + iter_str + time_left_str + progress_str + end_str return False def",
"prec), round(target_box[1].x, prec), round(target_box[1].y, prec)) def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.PACK), '-i', str(self.scene_props.precision),",
"Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # #####",
"texture. CAUTION: this operator should be used only when packing to a non-square",
"prefs = get_prefs() return prefs.uvp_initialized and context.active_object is not None and context.active_object.mode ==",
"time: ' + str(time.time() - self.start_time)) def read_islands(self, islands_msg): islands = [] island_cnt",
"read_int_array(self.invalid_islands_msg) if len(invalid_islands) == 0: self.raiseUnexpectedOutputError() self.p_context.handle_invalid_islands(invalid_islands) if code == UvInvalidIslandCode.TOPOLOGY: error_msg =",
"def execute(self, context): webbrowser.open(UvpLabels.HELP_BASEURL + self.URL_SUFFIX) return {'FINISHED'} class UVP2_OT_UvpSetupHelp(UVP2_OT_Help): bl_label = 'UVP",
"def finish(self, context): self.exit_common() return {'FINISHED', 'PASS_THROUGH'} def cancel(self, context): self.uvp_proc.terminate() # self.progress_thread.terminate()",
"time.time() self.last_msg_time = self.start_time self.hang_detected = False self.hang_timeout = 10.0 # Start progress",
"def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.VALIDATE_UVS)] return uvp_args class UVP2_OT_ProcessSimilar(UVP2_OT_PackOperatorGeneric): def validate_pack_params(self): pass",
"= None except NoUvFaceError as ex: self.set_status('WARNING', str(ex)) cancel = True except RuntimeError",
"return now = time.time() if now - self.progress_last_update_time > msg_refresh_interval or new_progress_msg !=",
"= self.p_context.handle_island_flags(island_flags) if self.area is not None: self.prefs.stats_area = self.area if self.uvp_proc.returncode ==",
"dialog_width = pix_per_char * len(self.confirmation_msg) + 50 return wm.invoke_props_dialog(self, width=dialog_width) return self.execute(context) def",
"if self.target_box is not None: uvp_args += ['-B', self.get_target_box_string(self.target_box)] uvp_args.append('-b') return uvp_args class",
"any later version. # # This program is distributed in the hope that",
"unconditionally if a hang was detected if self.hang_detected and event.type == 'ESC': raise",
"['-Q'] if in_debug_mode(): if self.prefs.seed > 0: uvp_args_final += ['-S', str(self.prefs.seed)] if self.prefs.wait_for_debugger:",
"if a hang was detected if self.hang_detected and event.type == 'ESC': raise OpAbortedException()",
"CAUTION: this operator should be used only when packing to a non-square texture.",
"= time.time() if now - self.progress_last_update_time > msg_refresh_interval or new_progress_msg != self.progress_msg: self.progress_last_update_time",
"send_groups, send_rot_step, send_lock_groups, send_verts_3d, self.get_group_method() if send_groups else None) if self.require_selection(): if selected_cnt",
"send_unselected: uvp_args_final.append('-s') if self.grouping_enabled(): uvp_args_final += ['-a', str(to_uvp_group_method(self.get_group_method()))] if self.send_rot_step(): uvp_args_final += ['-R']",
"##### import subprocess import queue import threading import signal import webbrowser from .utils",
"To Others' is not supported with grouping by similarity\") if not self.scene_props.rot_enable: raise",
"1.0) class UVP2_OT_AdjustIslandsToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_adjust_islands_to_texture' bl_label = 'Adjust Islands To Texture' bl_description",
"self.area = self.read_area(msg) return True elif msg_code == UvPackMessageCode.PACK_SOLUTION: pack_solution = read_pack_solution(msg) self.p_context.apply_pack_solution(self.pack_ratio,",
"device doesn't support packing groups together\") raise RuntimeError('Pack process returned an error') def",
"from .connection import * from .prefs import * from .os_iface import * from",
"1.0: uvp_args += ['-q', str(self.pack_ratio)] if self.target_box is not None: self.target_box[0].x *= self.pack_ratio",
"errors\" URL_SUFFIX = \"invalid-topology-issues\" class UVP2_OT_PixelMarginHelp(UVP2_OT_Help): bl_label = 'Pixel Margin Help' bl_idname =",
"\"{}:{}:{}:{}\".format( round(target_box[0].x, prec), round(target_box[0].y, prec), round(target_box[1].x, prec), round(target_box[1].y, prec)) def get_uvp_args(self): uvp_args =",
"for heuristic search\" URL_SUFFIX = \"heuristic-search\" class UVP2_OT_NonSquarePackingHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing Help'",
"mode only the number of invalid faces found is reported, invalid faces will",
"subprocess.Popen(uvp_args_final, stdin=subprocess.PIPE, stdout=subprocess.PIPE, **popen_args) out_stream = self.uvp_proc.stdin out_stream.write(self.p_context.serialized_maps) out_stream.flush() self.start_time = time.time() self.last_msg_time",
"faces i.e. faces with area close to 0, self-intersecting faces, faces overlapping each",
"This program is free software; you can redistribute it and/or # modify it",
"used only when packing to a non-square texture. For for info regarding non-square",
"RuntimeError as ex: if in_debug_mode(): print_backtrace(ex) self.set_status('ERROR', str(ex)) cancel = True except Exception",
"'uvpackmaster2.uv_validate' bl_label = 'Validate UVs' bl_description = 'Validate selected UV faces. The validation",
"= msg elif msg_code == UvPackMessageCode.ISLANDS: self.read_islands(msg) elif msg_code == UvPackMessageCode.ISLANDS_METADATA: if self.islands_metadata_msg",
"@classmethod def poll(cls, context): prefs = get_prefs() return prefs.uvp_initialized and context.active_object is not",
"self.prefs = get_prefs() self.scene_props = context.scene.uvp2_props self.p_context = None self.pack_ratio = 1.0 self.target_box",
"Exception as ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, 'Unexpected error') self.p_context.update_meshes() return {'FINISHED'} def",
"exceeded\") if retcode == UvPackerErrorCode.DEVICE_NOT_SUPPORTED: raise RuntimeError(\"Selected device is not supported\") if retcode",
"self.handle_event_spec(event): return # Generic event processing code if event.type == 'ESC': raise OpCancelledException()",
"True if self.p_context is not None: self.p_context.update_meshes() if cancel: if self.uvp_proc is not",
"+= ['-V', str(tile_count)] if self.prefs.tiles_enabled(self.scene_props): uvp_args += ['-C', str(tiles_in_row)] if self.grouping_enabled(): if to_uvp_group_method(self.get_group_method())",
"= pix_per_char * len(self.confirmation_msg) + 50 return wm.invoke_props_dialog(self, width=dialog_width) return self.execute(context) def draw(self,",
"UVP setup\" URL_SUFFIX = \"uvp-setup\" class UVP2_OT_HeuristicSearchHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing Help' bl_idname",
"for invalid UV faces i.e. faces with area close to 0, self-intersecting faces,",
"new_progress_msg: return now = time.time() if now - self.progress_last_update_time > msg_refresh_interval or new_progress_msg",
"the face selection mode if self.p_context.context.tool_settings.use_uv_select_sync: self.p_context.context.tool_settings.mesh_select_mode = (False, False, True) else: self.p_context.context.tool_settings.uv_select_mode",
"to the face selection mode if self.p_context.context.tool_settings.use_uv_select_sync: self.p_context.context.tool_settings.mesh_select_mode = (False, False, True) else:",
"connection thread') msg_received += 1 curr_time = time.time() if msg_received > 0: self.last_msg_time",
"def get_group_method(self): raise RuntimeError('Unexpected grouping requested') def send_rot_step(self): return False def lock_groups_enabled(self): return",
"['-o', str(self.get_uvp_opcode()), '-I', str(self.scene_props.similarity_threshold)] uvp_args += ['-i', str(self.scene_props.precision)] uvp_args += ['-r', str(90)] if",
"uvp_args += ['-d', self.prefs.dev_array[self.prefs.sel_dev_idx].id] if self.prefs.pixel_margin_enabled(self.scene_props): uvp_args += ['-M', str(self.scene_props.pixel_margin)] uvp_args += ['-y',",
"again to be on the safe side self.handle_communication() if not self.op_done: # Special",
"+ ' '.join(x for x in uvp_args_final)) creation_flags = os_uvp_creation_flags() popen_args = dict()",
"once again to be on the safe side self.handle_communication() if not self.op_done: #",
"help button\" def get_uvp_opcode(self): return UvPackerOpcode.ALIGN_SIMILAR def process_result(self): if self.prefs.FEATURE_demo: return if self.pack_solution_msg",
"self.raiseUnexpectedOutputError() self.area_msg = msg elif msg_code == UvPackMessageCode.INVALID_FACES: if self.invalid_faces_msg is not None:",
"'uv_islands.data') out_file = open(out_filepath, 'wb') out_file.write(self.p_context.serialized_maps) out_file.close() uvp_args_final = [get_uvp_execpath(), '-E', '-e', str(UvTopoAnalysisLevel.FORCE_EXTENDED),",
"') + '%, ' percent_progress_str = percent_progress_str[:-2] progress_str = 'Pack progress: {} '.format(percent_progress_str)",
"face selection mode if self.p_context.context.tool_settings.use_uv_select_sync: self.p_context.context.tool_settings.mesh_select_mode = (False, False, True) else: self.p_context.context.tool_settings.uv_select_mode =",
"= self.send_verts_3d() selected_cnt, unselected_cnt = self.p_context.serialize_uv_maps(send_unselected, send_groups, send_rot_step, send_lock_groups, send_verts_3d, self.get_group_method() if send_groups",
"cancel) ' return header_str + iter_str + time_left_str + progress_str + end_str return",
"self.cancel(context) return {'RUNNING_MODAL'} if not self.op_done else {'PASS_THROUGH'} def pre_op_initialize(self): pass def execute(self,",
"bl_label = 'Help' def execute(self, context): webbrowser.open(UvpLabels.HELP_BASEURL + self.URL_SUFFIX) return {'FINISHED'} class UVP2_OT_UvpSetupHelp(UVP2_OT_Help):",
"['-I', str(self.scene_props.similarity_threshold)] if self.prefs.pack_groups_together(self.scene_props): uvp_args += ['-U', str(self.scene_props.group_compactness)] if self.prefs.multi_device_enabled(self.scene_props): uvp_args.append('-u') if self.prefs.lock_overlap_enabled(self.scene_props):",
"= True if cancel: return self.cancel(context) return {'RUNNING_MODAL'} if not self.op_done else {'PASS_THROUGH'}",
"on the islands which were packed\") else: op_status = 'Packing done' if self.area",
"* from .pack_context import * from .connection import * from .prefs import *",
"= \"Show help for setting margin in pixels\" URL_SUFFIX = \"pixel-margin\" class UVP2_OT_IslandRotStepHelp(UVP2_OT_Help):",
"UV islands' def process_result(self): if self.area_msg is None: self.raiseUnexpectedOutputError() area = self.read_area(self.area_msg) self.prefs.stats_area",
"(ratio, 1.0) class UVP2_OT_Help(bpy.types.Operator): bl_label = 'Help' def execute(self, context): webbrowser.open(UvpLabels.HELP_BASEURL + self.URL_SUFFIX)",
"not None: self.raiseUnexpectedOutputError() self.pack_solution_msg = msg elif msg_code == UvPackMessageCode.AREA: if self.area_msg is",
"learn more\" elif code == UvInvalidIslandCode.INT_PARAM: param_array = IslandParamInfo.get_param_info_array() error_msg = \"Faces with",
"raise RuntimeError(\"Island rotations must be enabled in order to group by similarity\") if",
"self.raiseUnexpectedOutputError() self.pack_solution_msg = msg elif msg_code == UvPackMessageCode.AREA: if self.area_msg is not None:",
"area_msg): return round(force_read_float(area_msg) / self.pack_ratio, 3) class UVP2_OT_PackOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_pack' bl_label =",
"code = force_read_int(self.invalid_islands_msg) subcode = force_read_int(self.invalid_islands_msg) invalid_islands = read_int_array(self.invalid_islands_msg) if len(invalid_islands) == 0:",
"end_str = '(press ESC to cancel) ' return header_str + iter_str + time_left_str",
"'Non-Square Packing Help' bl_idname = 'uvpackmaster2.uv_heuristic_search_help' bl_description = \"Show help for heuristic search\"",
"self.progress_array = [0] * (progress_size) for i in range(progress_size): self.progress_array[i] = force_read_int(msg) self.progress_sec_left",
"self.hang_detected and event.type == 'ESC': raise OpAbortedException() if self.handle_event_spec(event): return # Generic event",
"top of each other. For more info regarding similarity detection click the help",
"None: self.target_box[0].x *= self.pack_ratio self.target_box[1].x *= self.pack_ratio else: self.target_box = (Vector((0.0, 0.0)), Vector((self.pack_ratio,",
"of selected islands so they are suitable for packing into the active texture.",
"an error') def raiseUnexpectedOutputError(self): raise RuntimeError('Unexpected output from the pack process') def set_status(self,",
"self.area is not None: end_str = '(press ESC to apply result) ' else:",
"return True return False def handle_event_spec(self, event): if event.type == 'ESC': if not",
"if self.curr_phase == UvPackingPhaseCode.TOPOLOGY_VALIDATION: return \"Topology validation: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) if",
"out_stream.write(self.p_context.serialized_maps) out_stream.flush() self.start_time = time.time() self.last_msg_time = self.start_time self.hang_detected = False self.hang_timeout =",
"similarity\") if not self.scene_props.rot_enable: raise RuntimeError(\"Island rotations must be enabled in order to",
"self.island_flags_msg is None: self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg) overlap_detected, outside_detected = self.p_context.handle_island_flags(island_flags) if self.area",
"round(target_box[1].y, prec)) def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.PACK), '-i', str(self.scene_props.precision), '-m', str(self.scene_props.margin)] uvp_args",
"interactive = False @classmethod def poll(cls, context): prefs = get_prefs() return prefs.uvp_initialized and",
"= self.get_confirmation_msg() wm = context.window_manager if self.confirmation_msg != '': pix_per_char = 5 dialog_width",
"in_debug_mode(): print('UVP operation time: ' + str(time.time() - self.start_time)) def read_islands(self, islands_msg): islands",
"if retcode in {UvPackerErrorCode.SUCCESS, UvPackerErrorCode.INVALID_ISLANDS, UvPackerErrorCode.NO_SPACE, UvPackerErrorCode.PRE_VALIDATION_FAILED}: return if retcode == UvPackerErrorCode.CANCELLED: raise",
"pix_per_char * len(self.confirmation_msg) + 50 return wm.invoke_props_dialog(self, width=dialog_width) return self.execute(context) def draw(self, context):",
"draw(self, context): layout = self.layout col = layout.column() col.label(text=self.confirmation_msg) def get_confirmation_msg(self): return ''",
"bl_label = 'Undo Islands Adjustment' bl_description = \"Undo adjustment performed by the 'Adjust",
"pack mode pack_mode = UvPackingMode.get_mode(self.scene_props.pack_mode) if pack_mode.req_feature != '' and not getattr(self.prefs, 'FEATURE_'",
"if not active_dev.supported: raise RuntimeError('Selected packing device is not supported in this engine",
"bl_idname = 'uvpackmaster2.uv_validate' bl_label = 'Validate UVs' bl_description = 'Validate selected UV faces.",
"else: self.raiseUnexpectedOutputError() def handle_communication(self): if self.op_done: return msg_received = 0 while True: try:",
"else None) if self.require_selection(): if selected_cnt == 0: raise NoUvFaceError('No UV face selected')",
"if to_uvp_group_method(self.get_group_method()) == UvGroupingMethodUvp.SIMILARITY: uvp_args += ['-I', str(self.scene_props.similarity_threshold)] if self.prefs.pack_groups_together(self.scene_props): uvp_args += ['-U',",
"= 5 dialog_width = pix_per_char * len(self.confirmation_msg) + 50 return wm.invoke_props_dialog(self, width=dialog_width) return",
"UvpLabels.GROUPS_TOGETHER_CONFIRM_MSG return '' def send_unselected_islands(self): return self.prefs.pack_to_others_enabled(self.scene_props) def grouping_enabled(self): return self.prefs.grouping_enabled(self.scene_props) def get_group_method(self):",
"get_active_image_ratio(self.p_context.context) return (1.0 / ratio, 1.0) class UVP2_OT_UndoIslandsAdjustemntToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_undo_islands_adjustment_to_texture' bl_label =",
"UvPackerErrorCode.DEVICE_DOESNT_SUPPORT_GROUPS_TOGETHER: raise RuntimeError(\"Selected device doesn't support packing groups together\") raise RuntimeError('Pack process returned",
"active_dev = self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None if active_dev is None:",
"wm.invoke_props_dialog(self, width=dialog_width) return self.execute(context) def draw(self, context): layout = self.layout col = layout.column()",
"islands). This usually happens when 'Pixel Padding' is set to a small value",
"return uvp_args class UVP2_OT_SelectSimilar(UVP2_OT_ProcessSimilar): bl_idname = 'uvpackmaster2.uv_select_similar' bl_label = 'Select Similar' bl_description =",
"Help' bl_idname = 'uvpackmaster2.uv_pixel_margin_help' bl_description = \"Show help for setting margin in pixels\"",
"(press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_SELECTION: return 'Searching for similar islands",
"+= ['-g', self.scene_props.pack_mode] tile_count, tiles_in_row = self.prefs.tile_grid_config(self.scene_props, self.p_context.context) if self.prefs.pack_to_tiles(self.scene_props): uvp_args += ['-V',",
"self.prefs.pack_groups_together(self.scene_props): uvp_args += ['-U', str(self.scene_props.group_compactness)] if self.prefs.multi_device_enabled(self.scene_props): uvp_args.append('-u') if self.prefs.lock_overlap_enabled(self.scene_props): uvp_args += ['-l',",
"out_file.close() uvp_args_final = [get_uvp_execpath(), '-E', '-e', str(UvTopoAnalysisLevel.FORCE_EXTENDED), '-t', str(self.prefs.thread_count)] + self.get_uvp_args() if send_unselected:",
"self.pack_ratio self.target_box[1].x *= self.pack_ratio else: self.target_box = (Vector((0.0, 0.0)), Vector((self.pack_ratio, 1.0))) if self.target_box",
"self.op_status op_status_type = self.op_status_type if self.op_status_type is not None else 'INFO' op_status =",
"'Overlapping islands detected') else: self.set_status('INFO', 'No overlapping islands detected') def validate_pack_params(self): pass def",
"= self.op_status if len(self.op_warnings) > 0: if op_status_type == 'INFO': op_status_type = 'WARNING'",
"self.curr_phase == UvPackingPhaseCode.AREA_MEASUREMENT: return 'Area measurement in progress (press ESC to cancel)' if",
"self.op_warnings # self.prefs.stats_op_warnings.add(warning_msg) def exit_common(self): if self.interactive: wm = self.p_context.context.window_manager wm.event_timer_remove(self._timer) self.p_context.update_meshes() self.report_status()",
"validation procedure looks for invalid UV faces i.e. faces with area close to",
"Similar' bl_description = \"Align selected islands, so islands which are similar are placed",
"return \"Topology analysis: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.OVERLAP_CHECK: return",
"if self.handle_uvp_msg_spec(msg_code, msg): return if msg_code == UvPackMessageCode.PROGRESS_REPORT: self.curr_phase = force_read_int(msg) progress_size =",
"to group by similarity\") if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: validate_target_box(self.scene_props) def get_target_box_string(self, target_box): prec",
"if msg_received > 0: self.last_msg_time = curr_time self.hang_detected = False else: if self.curr_phase",
"'uvpackmaster2.uv_pixel_margin_help' bl_description = \"Show help for setting margin in pixels\" URL_SUFFIX = \"pixel-margin\"",
"uvp_args += ['-N', str(self.scene_props.pixel_padding)] uvp_args += ['-W', self.scene_props.pixel_margin_method] uvp_args += ['-Y', str(self.scene_props.pixel_margin_adjust_time)] if",
"msg_code == UvPackMessageCode.ISLANDS: self.read_islands(msg) elif msg_code == UvPackMessageCode.ISLANDS_METADATA: if self.islands_metadata_msg is not None:",
"stats.total_time = force_read_int(msg) stats.avg_time = force_read_int(msg) return True return False def handle_event_spec(self, event):",
"bl_idname = 'uvpackmaster2.uv_nonsquare_packing_help' bl_description = \"Show help for non-square packing\" URL_SUFFIX = \"non-square-packing\"",
"= open(out_filepath, 'wb') out_file.write(self.p_context.serialized_maps) out_file.close() uvp_args_final = [get_uvp_execpath(), '-E', '-e', str(UvTopoAnalysisLevel.FORCE_EXTENDED), '-t', str(self.prefs.thread_count)]",
"str(self.prefs.test_param)] print('Pakcer args: ' + ' '.join(x for x in uvp_args_final)) creation_flags =",
"faces found: ' + str(invalid_face_count)) else: self.set_status('INFO', 'No invalid faces found') def validate_pack_params(self):",
"True return True return False def process_result(self): overlap_detected = False outside_detected = False",
"'Adjust Islands To Texture' operator so islands are again suitable for packing into",
"5 dialog_width = pix_per_char * len(self.confirmation_msg) + 50 return wm.invoke_props_dialog(self, width=dialog_width) return self.execute(context)",
"= 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) if invalid_face_count > 0: self.set_status('WARNING', 'Pre-validation failed. Number",
"self.progress_msg: self.progress_last_update_time = now self.progress_msg = new_progress_msg self.report({'INFO'}, self.progress_msg) def handle_uvp_msg(self, msg): msg_code",
"self.report({'INFO'}, self.progress_msg) def handle_uvp_msg(self, msg): msg_code = force_read_int(msg) if self.handle_uvp_msg_spec(msg_code, msg): return if",
"islands' def __init__(self): self.cancel_sig_sent = False self.area = None def get_confirmation_msg(self): if platform.system()",
"upper layer wheter it should finish if self.curr_phase == UvPackingPhaseCode.DONE: self.handle_op_done() elif msg_code",
"msg_received > 0: self.last_msg_time = curr_time self.hang_detected = False else: if self.curr_phase !=",
"> 0: uvp_args_final += ['-S', str(self.prefs.seed)] if self.prefs.wait_for_debugger: uvp_args_final.append('-G') uvp_args_final += ['-T', str(self.prefs.test_param)]",
"def lock_groups_enabled(self): return self.prefs.FEATURE_lock_overlapping and self.scene_props.lock_groups_enable def send_verts_3d(self): return self.scene_props.normalize_islands def get_progress_msg_spec(self): if",
"Inform the upper layer wheter it should finish if self.curr_phase == UvPackingPhaseCode.DONE: self.handle_op_done()",
"faces found is reported, invalid faces will not be selected. Click OK to",
"selected_cnt == 0: raise NoUvFaceError('No UV face selected') else: if selected_cnt + unselected_cnt",
".prefs import * from .os_iface import * from .island_params import * from .labels",
"uvp_args += ['-l', self.scene_props.lock_overlapping_mode] if self.prefs.pack_to_others_enabled(self.scene_props): uvp_args += ['-x'] if self.prefs.FEATURE_validation and self.scene_props.pre_validate:",
"'' and not getattr(self.prefs, 'FEATURE_' + pack_mode.req_feature): raise RuntimeError('Selected packing mode is not",
"msg_received = 0 while True: try: item = self.progress_queue.get_nowait() except queue.Empty as ex:",
"must be enabled in order to group by similarity\") if self.scene_props.prerot_disable: raise RuntimeError(\"'Pre-Rotation",
"self.uvp_proc is not None: self.uvp_proc.terminate() self.report_status() return {'FINISHED'} if self.interactive: wm = context.window_manager",
"overlap_detected: self.set_status('WARNING', 'Overlapping islands detected') else: self.set_status('INFO', 'No overlapping islands detected') def validate_pack_params(self):",
"+ progress_str + end_str return False def handle_uvp_msg_spec(self, msg_code, msg): if msg_code ==",
"islands = [] island_cnt = force_read_int(islands_msg) selected_cnt = force_read_int(islands_msg) for i in range(island_cnt):",
"self.progress_sec_left = force_read_int(msg) self.progress_iter_done = force_read_int(msg) # Inform the upper layer wheter it",
"# This program is free software; you can redistribute it and/or # modify",
"= '' if self.progress_sec_left >= 0: time_left_str = \"Time left: {} sec. \".format(self.progress_sec_left)",
"return '' def process_result(self): if self.invalid_faces_msg is None: self.raiseUnexpectedOutputError() invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces",
"Check the Help panel to learn more\" elif code == UvInvalidIslandCode.INT_PARAM: param_array =",
"'NOTHING' self.ctrl = False while True: event = FakeTimerEvent() ret = self.modal(context, event)",
"non-square packing click the help icon\" def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return (1.0",
"not None and context.active_object.mode == 'EDIT' def check_uvp_retcode(self, retcode): self.prefs.uvp_retcode = retcode if",
"to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston,",
"self.lock_groups_enabled(): uvp_args_final += ['-Q'] if in_debug_mode(): if self.prefs.seed > 0: uvp_args_final += ['-S',",
"Padding' is set to a small value and the 'Adjustment Time' is not",
"self.set_status('WARNING', 'Number of invalid faces found: ' + str(invalid_face_count)) else: self.set_status('INFO', 'No invalid",
"col = layout.column() col.label(text=self.confirmation_msg) def get_confirmation_msg(self): return '' def send_unselected_islands(self): return False def",
"return ret time.sleep(self.MODAL_INTERVAL_S) def invoke(self, context, event): self.interactive = True self.prefs = get_prefs()",
"# This program is distributed in the hope that it will be useful,",
"self.exit_common() return {'FINISHED', 'PASS_THROUGH'} def cancel(self, context): self.uvp_proc.terminate() # self.progress_thread.terminate() self.exit_common() return {'FINISHED'}",
"-1 self.progress_last_update_time = 0.0 self.curr_phase = UvPackingPhaseCode.INITIALIZATION self.invalid_islands_msg = None self.island_flags_msg = None",
"'' if self.progress_sec_left >= 0: time_left_str = \"Time left: {} sec. \".format(self.progress_sec_left) else:",
"self.island_flags_msg = None self.pack_solution_msg = None self.area_msg = None self.invalid_faces_msg = None self.similar_islands_msg",
"= msg elif msg_code == UvPackMessageCode.SIMILAR_ISLANDS: if self.similar_islands_msg is not None: self.raiseUnexpectedOutputError() self.similar_islands_msg",
"not None: uvp_args += ['-B', self.get_target_box_string(self.target_box)] uvp_args.append('-b') return uvp_args class UVP2_OT_OverlapCheckOperator(UVP2_OT_PackOperatorGeneric): bl_idname =",
"self.hang_detected = True def handle_event(self, event): # Kill the UVP process unconditionally if",
"{ UvPackingPhaseCode.PACKING, UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT }: if self.curr_phase == UvPackingPhaseCode.PIXEL_MARGIN_ADJUSTMENT: header_str = 'Pixel margin adjustment.",
"cancel = True if self.p_context is not None: self.p_context.update_meshes() if cancel: if self.uvp_proc",
"+ str(invalid_face_count)) else: self.set_status('INFO', 'No invalid faces found') def validate_pack_params(self): pass def get_uvp_args(self):",
"process died unexpectedly') self.handle_progress_msg() except OpFinishedException: finish = True except: raise if finish:",
"= 2.0 new_progress_msg = self.get_progress_msg() if not new_progress_msg: return now = time.time() if",
"FakeTimerEvent() ret = self.modal(context, event) if ret.intersection({'FINISHED', 'CANCELLED'}): return ret time.sleep(self.MODAL_INTERVAL_S) def invoke(self,",
"if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, 'Unexpected error') self.p_context.update_meshes() return {'FINISHED'} def get_scale_factors(self): return (1.0,",
"were packed\") else: op_status = 'Packing done' if self.area is not None: op_status",
"None: # It should not be required to but check once again to",
"uvp_args.append('-v') if self.prefs.normalize_islands_enabled(self.scene_props): uvp_args.append('-L') if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: self.target_box = self.prefs.target_box(self.scene_props) if self.prefs.pack_ratio_enabled(self.scene_props):",
"['-r', str(rot_step_value)] if self.prefs.heuristic_enabled(self.scene_props): uvp_args += ['-h', str(self.scene_props.heuristic_search_time), '-j', str(self.scene_props.heuristic_max_wait_time)] if self.prefs.FEATURE_advanced_heuristic and",
"regarding non-square packing read the documentation\" def get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return (ratio,",
"51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END",
"None: self.raiseUnexpectedOutputError() similar_island_count = force_read_int(self.similar_islands_msg) similar_islands = read_int_array(self.similar_islands_msg) if not self.prefs.FEATURE_demo: if len(similar_islands)",
"not self.op_done: # Special value indicating a crash self.prefs.uvp_retcode = -1 raise RuntimeError('Packer",
"else: if self.curr_phase != UvPackingPhaseCode.RENDER_PRESENTATION and curr_time - self.last_msg_time > self.hang_timeout: self.hang_detected =",
"= threading.Thread(target=connection_thread_func, args=(self.uvp_proc.stdout, self.progress_queue)) self.connection_thread.daemon = True self.connection_thread.start() self.progress_array = [0] self.progress_msg =",
"else: op_status = 'Packing done' if self.area is not None: op_status += ',",
"elif msg_code == UvPackMessageCode.PACK_SOLUTION: if self.pack_solution_msg is not None: self.raiseUnexpectedOutputError() self.pack_solution_msg = msg",
"General Public License # as published by the Free Software Foundation; either version",
"time.time() if msg_received > 0: self.last_msg_time = curr_time self.hang_detected = False else: if",
"unregister_uvp import bmesh import bpy import mathutils import tempfile class InvalidIslandsError(Exception): pass class",
"return False def send_verts_3d(self): return False def read_area(self, area_msg): return round(force_read_float(area_msg) / self.pack_ratio,",
"return False def handle_event_spec(self, event): if event.type == 'ESC': if not self.cancel_sig_sent: self.uvp_proc.send_signal(os_cancel_sig())",
"demo mode only the number of invalid faces found is reported, invalid faces",
"For for info regarding non-square packing click the help icon\" def get_scale_factors(self): ratio",
"= 'uvpackmaster2.uv_uvp_setup_help' bl_description = \"Show help for UVP setup\" URL_SUFFIX = \"uvp-setup\" class",
"RuntimeError('The UVP process wait timeout reached') self.connection_thread.join() self.check_uvp_retcode(self.uvp_proc.returncode) if not self.p_context.islands_received(): self.raiseUnexpectedOutputError() self.process_invalid_islands()",
"UVP2_OT_ManualGroupingHelp(UVP2_OT_Help): bl_label = 'Manual Grouping Help' bl_idname = 'uvpackmaster2.uv_manual_grouping_help' bl_description = \"Show help",
"reported, invalid faces will not be selected. Click OK to continue' return ''",
"UvPackingPhaseCode.TOPOLOGY_VALIDATION: return \"Topology validation: {:3}% (press ESC to cancel)\".format(self.progress_array[0]) if self.curr_phase == UvPackingPhaseCode.VALIDATION:",
"Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL",
"from .labels import UvpLabels from .register import check_uvp, unregister_uvp import bmesh import bpy",
"== UvGroupingMethod.SIMILARITY.code: if self.prefs.pack_to_others_enabled(self.scene_props): raise RuntimeError(\"'Pack To Others' is not supported with grouping",
"self.set_status('INFO', 'No overlapping islands detected') def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o',",
"= self.prefs.dev_array[self.prefs.sel_dev_idx] if self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None if active_dev is not None",
"bl_description = \"Adjust scale of selected islands so they are suitable for packing",
"handle_progress_msg(self): if self.op_done: return msg_refresh_interval = 2.0 new_progress_msg = self.get_progress_msg() if not new_progress_msg:",
"return False def handle_progress_msg(self): if self.op_done: return msg_refresh_interval = 2.0 new_progress_msg = self.get_progress_msg()",
"None: self.prefs['op_status'] = self.op_status op_status_type = self.op_status_type if self.op_status_type is not None else",
"= False while True: event = FakeTimerEvent() ret = self.modal(context, event) if ret.intersection({'FINISHED',",
"in progress (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_SELECTION: return 'Searching for",
"return wm.invoke_props_dialog(self, width=dialog_width) return self.execute(context) def draw(self, context): layout = self.layout col =",
"to learn more\" elif code == UvInvalidIslandCode.INT_PARAM: param_array = IslandParamInfo.get_param_info_array() error_msg = \"Faces",
"not supported with grouping by similarity\") if not self.scene_props.rot_enable: raise RuntimeError(\"Island rotations must",
"RuntimeError(\"Island rotations must be enabled in order to group by similarity\") if self.scene_props.prerot_disable:",
"= layout.column() col.label(text=self.confirmation_msg) def get_confirmation_msg(self): return '' def send_unselected_islands(self): return False def grouping_enabled(self):",
"is None: self.raiseUnexpectedOutputError() pack_solution = read_pack_solution(self.pack_solution_msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) self.set_status('INFO', 'Islands aligned') class UVP2_OT_ScaleIslands(bpy.types.Operator):",
"overlapping each other' def get_confirmation_msg(self): if self.prefs.FEATURE_demo: return 'WARNING: in the demo mode",
"bmesh import bpy import mathutils import tempfile class InvalidIslandsError(Exception): pass class NoUvFaceError(Exception): pass",
"count exceeded\") if retcode == UvPackerErrorCode.DEVICE_NOT_SUPPORTED: raise RuntimeError(\"Selected device is not supported\") if",
"== 'TIMER': self.handle_communication() def modal(self, context, event): cancel = False finish = False",
"elif msg_code == UvPackMessageCode.ISLANDS_METADATA: if self.islands_metadata_msg is not None: self.raiseUnexpectedOutputError() self.islands_metadata_msg = msg",
"else 'none') else: header_str = '' if self.progress_iter_done >= 0: iter_str = 'Iter.",
"self.p_context.update_meshes() self.report_status() if in_debug_mode(): print('UVP operation time: ' + str(time.time() - self.start_time)) def",
"and not self.prefs.heuristic_enabled(self.scene_props): return UvpLabels.GROUPS_TOGETHER_CONFIRM_MSG return '' def send_unselected_islands(self): return self.prefs.pack_to_others_enabled(self.scene_props) def grouping_enabled(self):",
"= 0.1 interactive = False @classmethod def poll(cls, context): prefs = get_prefs() return",
"mode pack_mode = UvPackingMode.get_mode(self.scene_props.pack_mode) if pack_mode.req_feature != '' and not getattr(self.prefs, 'FEATURE_' +",
"self.p_context.context.tool_settings.mesh_select_mode = (False, False, True) else: self.p_context.context.tool_settings.uv_select_mode = 'FACE' self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) else:",
"self.curr_phase is None: return False progress_msg_spec = self.get_progress_msg_spec() if progress_msg_spec: return progress_msg_spec if",
"OpCancelledException() if retcode == UvPackerErrorCode.NO_VALID_STATIC_ISLAND: raise RuntimeError(\"'Pack To Others' option enabled, but no",
"ex: if in_debug_mode(): print_backtrace(ex) self.report({'ERROR'}, str(ex)) except Exception as ex: if in_debug_mode(): print_backtrace(ex)",
"to islands which are already selected. For more info regarding similarity detection click",
"cancel)\".format(self.progress_array[0]) raise RuntimeError('Unexpected packing phase encountered') def handle_uvp_msg_spec(self, msg_code, msg): return False def",
"UV islands overlap each other' def process_result(self): if self.island_flags_msg is None: self.raiseUnexpectedOutputError() island_flags",
"islands found is reported, islands will not be selected. Click OK to continue'",
"False self.uvp_proc = None self.prefs = get_prefs() self.scene_props = context.scene.uvp2_props self.p_context = None",
"To Texture' operator so islands are again suitable for packing into a square",
"= True if self.p_context is not None: self.p_context.update_meshes() if cancel: if self.uvp_proc is",
"'PASS_THROUGH'} def cancel(self, context): self.uvp_proc.terminate() # self.progress_thread.terminate() self.exit_common() return {'FINISHED'} def get_progress_msg_spec(self): return",
"area = self.read_area(self.area_msg) self.prefs.stats_area = area self.set_status('INFO', 'Islands area: ' + str(area)) def",
"'uvpackmaster2.uv_undo_islands_adjustment_to_texture' bl_label = 'Undo Islands Adjustment' bl_description = \"Undo adjustment performed by the",
"time (press ESC to abort)' if self.curr_phase is None: return False progress_msg_spec =",
"packing into a square texture. For for info regarding non-square packing read the",
"iter_str + time_left_str + progress_str + end_str return False def handle_uvp_msg_spec(self, msg_code, msg):",
"= wm.event_timer_add(self.MODAL_INTERVAL_S, window=context.window) wm.modal_handler_add(self) return {'RUNNING_MODAL'} class FakeTimerEvent: def __init__(self): self.type = 'TIMER'",
"invalid faces will not be selected. Click OK to continue' return '' def",
"= os.path.join(tempfile.gettempdir(), 'uv_islands.data') out_file = open(out_filepath, 'wb') out_file.write(self.p_context.serialized_maps) out_file.close() uvp_args_final = [get_uvp_execpath(), '-E',",
"self.interactive: wm = context.window_manager self._timer = wm.event_timer_add(self.MODAL_INTERVAL_S, window=context.window) wm.modal_handler_add(self) return {'RUNNING_MODAL'} class FakeTimerEvent:",
"See the # GNU General Public License for more details. # # You",
"supported with grouping by similarity\") if not self.scene_props.rot_enable: raise RuntimeError(\"Island rotations must be",
"# self.progress_thread.terminate() self.exit_common() return {'FINISHED'} def get_progress_msg_spec(self): return False def get_progress_msg(self): if self.hang_detected:",
"self.p_context.update_meshes() return {'FINISHED'} def get_scale_factors(self): return (1.0, 1.0) class UVP2_OT_AdjustIslandsToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_adjust_islands_to_texture'",
"return uvp_args class UVP2_OT_MeasureAreaOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_measure_area' bl_label = 'Measure Area' bl_description =",
"UvPackerErrorCode.NO_SPACE: op_status = 'Packing stopped - no space to pack all islands' self.add_warning(\"Overlap",
"return uvp_args class UVP2_OT_ProcessSimilar(UVP2_OT_PackOperatorGeneric): def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(self.get_uvp_opcode()),",
"face visible') self.validate_pack_params() if self.prefs.write_to_file: out_filepath = os.path.join(tempfile.gettempdir(), 'uv_islands.data') out_file = open(out_filepath, 'wb')",
"and self.scene_props.pre_validate: uvp_args.append('-v') if self.prefs.normalize_islands_enabled(self.scene_props): uvp_args.append('-L') if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: self.target_box = self.prefs.target_box(self.scene_props)",
"len(self.prefs.dev_array) else None if active_dev is not None and active_dev.id.startswith('cuda'): return UvpLabels.CUDA_MACOS_CONFIRM_MSG if",
"context): layout = self.layout col = layout.column() col.label(text=self.confirmation_msg) def get_confirmation_msg(self): return '' def",
"from .register import check_uvp, unregister_uvp import bmesh import bpy import mathutils import tempfile",
"RuntimeError(\"Selected device is not supported\") if retcode == UvPackerErrorCode.DEVICE_DOESNT_SUPPORT_GROUPS_TOGETHER: raise RuntimeError(\"Selected device doesn't",
"== UvPackerErrorCode.DEVICE_DOESNT_SUPPORT_GROUPS_TOGETHER: raise RuntimeError(\"Selected device doesn't support packing groups together\") raise RuntimeError('Pack process",
"your option) any later version. # # This program is distributed in the",
"get_scale_factors(self): ratio = get_active_image_ratio(self.p_context.context) return (1.0 / ratio, 1.0) class UVP2_OT_UndoIslandsAdjustemntToTexture(UVP2_OT_ScaleIslands): bl_idname =",
"no space to pack all islands' self.add_warning(\"Overlap check was performed only on the",
"if self.invalid_islands_msg is None: self.raiseUnexpectedOutputError() code = force_read_int(self.invalid_islands_msg) subcode = force_read_int(self.invalid_islands_msg) invalid_islands =",
"self.op_warnings.append(warn_msg) def report_status(self): if self.op_status is not None: self.prefs['op_status'] = self.op_status op_status_type =",
"UvPackingPhaseCode.AREA_MEASUREMENT: return 'Area measurement in progress (press ESC to cancel)' if self.curr_phase ==",
"== UvPackMessageCode.PACK_SOLUTION: pack_solution = read_pack_solution(msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) return True elif msg_code == UvPackMessageCode.BENCHMARK:",
"None and context.active_object.mode == 'EDIT' def check_uvp_retcode(self, retcode): self.prefs.uvp_retcode = retcode if retcode",
"if self.area_msg is None: self.raiseUnexpectedOutputError() area = self.read_area(self.area_msg) self.prefs.stats_area = area self.set_status('INFO', 'Islands",
"UVP2_OT_NonSquarePackingHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing Help' bl_idname = 'uvpackmaster2.uv_nonsquare_packing_help' bl_description = \"Show help",
"out_stream = self.uvp_proc.stdin out_stream.write(self.p_context.serialized_maps) out_stream.flush() self.start_time = time.time() self.last_msg_time = self.start_time self.hang_detected =",
"len(invalid_faces) != invalid_face_count: self.raiseUnexpectedOutputError() if invalid_face_count > 0: # Switch to the face",
"retcode == UvPackerErrorCode.DEVICE_NOT_SUPPORTED: raise RuntimeError(\"Selected device is not supported\") if retcode == UvPackerErrorCode.DEVICE_DOESNT_SUPPORT_GROUPS_TOGETHER:",
"{'FINISHED'} if self.interactive: wm = context.window_manager self._timer = wm.event_timer_add(self.MODAL_INTERVAL_S, window=context.window) wm.modal_handler_add(self) return {'RUNNING_MODAL'}",
"islands detected') def validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(UvPackerOpcode.OVERLAP_CHECK)] return uvp_args",
"if self.uvp_proc.returncode == UvPackerErrorCode.NO_SPACE: op_status = 'Packing stopped - no space to pack",
"of invalid faces found: ' + str(invalid_face_count) + '. Packing aborted') return if",
"validate_pack_params(self): pass def get_uvp_args(self): uvp_args = ['-o', str(self.get_uvp_opcode()), '-I', str(self.scene_props.similarity_threshold)] uvp_args += ['-i',",
"to but check once again to be on the safe side self.handle_communication() if",
"more\" elif code == UvInvalidIslandCode.INT_PARAM: param_array = IslandParamInfo.get_param_info_array() error_msg = \"Faces with inconsistent",
"None self.op_status = None self.op_warnings = [] try: if not check_uvp(): unregister_uvp() redraw_ui(context)",
"def add_warning(self, warn_msg): self.op_warnings.append(warn_msg) def report_status(self): if self.op_status is not None: self.prefs['op_status'] =",
"self.progress_msg) def handle_uvp_msg(self, msg): msg_code = force_read_int(msg) if self.handle_uvp_msg_spec(msg_code, msg): return if msg_code",
"phase encountered') def handle_uvp_msg_spec(self, msg_code, msg): return False def handle_event_spec(self, event): return False",
"if now - self.progress_last_update_time > msg_refresh_interval or new_progress_msg != self.progress_msg: self.progress_last_update_time = now",
"bl_label = 'Pack' bl_description = 'Pack selected UV islands' def __init__(self): self.cancel_sig_sent =",
"def lock_groups_enabled(self): return False def send_verts_3d(self): return False def read_area(self, area_msg): return round(force_read_float(area_msg)",
"None: self.raiseUnexpectedOutputError() invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces = read_int_array(self.invalid_faces_msg) if not self.prefs.FEATURE_demo: if len(invalid_faces)",
"self.prefs.sel_dev_idx < len(self.prefs.dev_array) else None if active_dev is not None and active_dev.id.startswith('cuda'): return",
"and self.scene_props.advanced_heuristic: uvp_args.append('-H') uvp_args += ['-g', self.scene_props.pack_mode] tile_count, tiles_in_row = self.prefs.tile_grid_config(self.scene_props, self.p_context.context) if",
"op_status += '. (WARNINGS were reported - check the UVP tab for details)'",
"island_idx in similar_islands: self.p_context.select_island_faces(island_idx, self.p_context.uv_island_faces_list[island_idx], True) else: if len(similar_islands) > 0: self.raiseUnexpectedOutputError() self.set_status('INFO',",
"'Select Similar' bl_description = \"Selects all islands which have similar shape to islands",
"self.op_warnings = [] try: if not check_uvp(): unregister_uvp() redraw_ui(context) raise RuntimeError(\"UVP engine broken\")",
"user') cancel = True except InvalidIslandsError as err: self.set_status('ERROR', str(err)) cancel = True",
"self.prefs.stats_area = area self.set_status('INFO', 'Islands area: ' + str(area)) def validate_pack_params(self): pass def",
"FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more",
"self.p_context.select_all_faces(False) self.p_context.select_faces(list(invalid_faces), True) else: if len(invalid_faces) > 0: self.raiseUnexpectedOutputError() if invalid_face_count > 0:",
"self.prefs['op_status'] = self.op_status op_status_type = self.op_status_type if self.op_status_type is not None else 'INFO'",
"be used only when packing to a non-square texture. For for info regarding",
"send_lock_groups = self.lock_groups_enabled() send_verts_3d = self.send_verts_3d() selected_cnt, unselected_cnt = self.p_context.serialize_uv_maps(send_unselected, send_groups, send_rot_step, send_lock_groups,",
"area: ' + str(self.area) self.set_status('INFO', op_status) if overlap_detected: self.add_warning(\"Overlapping islands were detected after",
"import bmesh import bpy import mathutils import tempfile class InvalidIslandsError(Exception): pass class NoUvFaceError(Exception):",
"pack_solution = read_pack_solution(msg) self.p_context.apply_pack_solution(self.pack_ratio, pack_solution) return True elif msg_code == UvPackMessageCode.BENCHMARK: stats =",
"finish if self.curr_phase == UvPackingPhaseCode.DONE: self.handle_op_done() elif msg_code == UvPackMessageCode.INVALID_ISLANDS: if self.invalid_islands_msg is",
"self.p_context = PackContext(context) ratio = get_active_image_ratio(self.p_context.context) self.p_context.scale_selected_faces(self.get_scale_factors()) except RuntimeError as ex: if in_debug_mode():",
"self.set_status('INFO', 'Islands aligned') class UVP2_OT_ScaleIslands(bpy.types.Operator): bl_options = {'UNDO'} @classmethod def poll(cls, context): return",
"self.prefs.stats_op_warnings.add(warning_msg) def exit_common(self): if self.interactive: wm = self.p_context.context.window_manager wm.event_timer_remove(self._timer) self.p_context.update_meshes() self.report_status() if in_debug_mode():",
"Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK #####",
"is set to a small value and the 'Adjustment Time' is not long",
"force_read_int(self.invalid_islands_msg) invalid_islands = read_int_array(self.invalid_islands_msg) if len(invalid_islands) == 0: self.raiseUnexpectedOutputError() self.p_context.handle_invalid_islands(invalid_islands) if code ==",
">= 0: time_left_str = \"Time left: {} sec. \".format(self.progress_sec_left) else: time_left_str = ''",
"self.raiseUnexpectedOutputError() if invalid_face_count > 0: self.set_status('WARNING', 'Number of invalid faces found: ' +",
"if len(invalid_faces) > 0: self.raiseUnexpectedOutputError() if invalid_face_count > 0: self.set_status('WARNING', 'Number of invalid",
"Special value indicating a crash self.prefs.uvp_retcode = -1 raise RuntimeError('Packer process died unexpectedly')",
"if self.scene_props.prerot_disable: uvp_args += ['-w'] else: rot_step_value = -1 uvp_args += ['-r', str(rot_step_value)]",
"self.target_box = (Vector((0.0, 0.0)), Vector((self.pack_ratio, 1.0))) if self.target_box is not None: uvp_args +=",
"= msg elif msg_code == UvPackMessageCode.ISLAND_FLAGS: if self.island_flags_msg is not None: self.raiseUnexpectedOutputError() self.island_flags_msg",
"returned an error') def raiseUnexpectedOutputError(self): raise RuntimeError('Unexpected output from the pack process') def",
"License, or (at your option) any later version. # # This program is",
"op_status_type = 'WARNING' op_status += '. (WARNINGS were reported - check the UVP",
"' '.join(x for x in uvp_args_final)) creation_flags = os_uvp_creation_flags() popen_args = dict() if",
"event = FakeTimerEvent() ret = self.modal(context, event) if ret.intersection({'FINISHED', 'CANCELLED'}): return ret time.sleep(self.MODAL_INTERVAL_S)",
"self.area_msg is None: self.raiseUnexpectedOutputError() area = self.read_area(self.area_msg) self.prefs.stats_area = area self.set_status('INFO', 'Islands area:",
"if self.prefs.normalize_islands_enabled(self.scene_props): uvp_args.append('-L') if self.prefs.FEATURE_target_box and self.prefs.target_box_enable: self.target_box = self.prefs.target_box(self.scene_props) if self.prefs.pack_ratio_enabled(self.scene_props): self.pack_ratio",
"the user') cancel = True except InvalidIslandsError as err: self.set_status('ERROR', str(err)) cancel =",
"the 'Adjust Islands To Texture' operator so islands are again suitable for packing",
"get_confirmation_msg(self): if self.prefs.FEATURE_demo: return 'WARNING: in the demo mode only the number of",
"= get_active_image_ratio(self.p_context.context) if self.pack_ratio != 1.0: uvp_args += ['-q', str(self.pack_ratio)] if self.target_box is",
"str(UvPackerOpcode.MEASURE_AREA)] return uvp_args class UVP2_OT_ValidateOperator(UVP2_OT_PackOperatorGeneric): bl_idname = 'uvpackmaster2.uv_validate' bl_label = 'Validate UVs' bl_description",
"aligning (press ESC to cancel)' if self.curr_phase == UvPackingPhaseCode.RENDER_PRESENTATION: return 'Close the demo",
"= get_active_image_ratio(self.p_context.context) return (ratio, 1.0) class UVP2_OT_Help(bpy.types.Operator): bl_label = 'Help' def execute(self, context):",
"UvPackMessageCode.AREA: if self.area_msg is not None: self.raiseUnexpectedOutputError() self.area_msg = msg elif msg_code ==",
"modal(self, context, event): cancel = False finish = False try: try: self.handle_event(event) #",
"self.add_warning(\"Overlapping islands were detected after packing (check the selected islands). Consider increasing the",
"context.active_object.mode == 'EDIT' def check_uvp_retcode(self, retcode): self.prefs.uvp_retcode = retcode if retcode in {UvPackerErrorCode.SUCCESS,",
"suitable for packing into the active texture. CAUTION: this operator should be used",
"= context.window_manager self._timer = wm.event_timer_add(self.MODAL_INTERVAL_S, window=context.window) wm.modal_handler_add(self) return {'RUNNING_MODAL'} class FakeTimerEvent: def __init__(self):",
"UvInvalidIslandCode.TOPOLOGY: error_msg = \"Invalid topology encountered in the selected islands. Check the Help",
"ESC to apply result) ' else: end_str = '(press ESC to cancel) '",
"RuntimeError(\"'Pack To Others' option enabled, but no unselected island found in the packing",
"General Public License # along with this program; if not, write to the",
"'Precision' parameter. Sometimes increasing the 'Adjustment Time' may solve the problem (if used",
"help for heuristic search\" URL_SUFFIX = \"heuristic-search\" class UVP2_OT_NonSquarePackingHelp(UVP2_OT_Help): bl_label = 'Non-Square Packing",
"if len(invalid_faces) != invalid_face_count: self.raiseUnexpectedOutputError() if invalid_face_count > 0: # Switch to the",
"if self.hang_detected: return 'Packer process not responding for a longer time (press ESC",
"if retcode == UvPackerErrorCode.DEVICE_DOESNT_SUPPORT_GROUPS_TOGETHER: raise RuntimeError(\"Selected device doesn't support packing groups together\") raise",
"\"Show help for non-square packing\" URL_SUFFIX = \"non-square-packing\" class UVP2_OT_SimilarityDetectionHelp(UVP2_OT_Help): bl_label = 'Similarity",
"time_left_str = '' percent_progress_str = '' for prog in self.progress_array: percent_progress_str += str(prog).rjust(3,",
"import * from .labels import UvpLabels from .register import check_uvp, unregister_uvp import bmesh",
"UVP2_OT_ScaleIslands(bpy.types.Operator): bl_options = {'UNDO'} @classmethod def poll(cls, context): return context.active_object is not None",
"context.active_object is not None and context.active_object.mode == 'EDIT' def execute(self, context): try: self.p_context",
"OpAbortedException() if self.handle_event_spec(event): return # Generic event processing code if event.type == 'ESC':",
"not None: self.target_box[0].x *= self.pack_ratio self.target_box[1].x *= self.pack_ratio else: self.target_box = (Vector((0.0, 0.0)),",
"self.invalid_faces_msg is not None: invalid_face_count = force_read_int(self.invalid_faces_msg) invalid_faces = read_int_array(self.invalid_faces_msg) if not self.prefs.FEATURE_demo:",
"if invalid_face_count > 0: self.set_status('WARNING', 'Pre-validation failed. Number of invalid faces found: '",
"/ ratio, 1.0) class UVP2_OT_UndoIslandsAdjustemntToTexture(UVP2_OT_ScaleIslands): bl_idname = 'uvpackmaster2.uv_undo_islands_adjustment_to_texture' bl_label = 'Undo Islands Adjustment'",
"else: if selected_cnt + unselected_cnt == 0: raise NoUvFaceError('No UV face visible') self.validate_pack_params()",
"to cancel)' if self.curr_phase == UvPackingPhaseCode.SIMILAR_SELECTION: return 'Searching for similar islands (press ESC",
"def handle_uvp_msg(self, msg): msg_code = force_read_int(msg) if self.handle_uvp_msg_spec(msg_code, msg): return if msg_code ==",
"return if not self.prefs.FEATURE_demo: if self.island_flags_msg is None: self.raiseUnexpectedOutputError() island_flags = read_int_array(self.island_flags_msg) overlap_detected,",
"isinstance(item, str): raise RuntimeError(item) elif isinstance(item, io.BytesIO): self.handle_uvp_msg(item) else: raise RuntimeError('Unexpected output from",
"from .island_params import * from .labels import UvpLabels from .register import check_uvp, unregister_uvp",
"+ self.get_uvp_args() if send_unselected: uvp_args_final.append('-s') if self.grouping_enabled(): uvp_args_final += ['-a', str(to_uvp_group_method(self.get_group_method()))] if self.send_rot_step():",
"monitor thread self.progress_queue = queue.Queue() self.connection_thread = threading.Thread(target=connection_thread_func, args=(self.uvp_proc.stdout, self.progress_queue)) self.connection_thread.daemon = True",
"UVP2_OT_UvpSetupHelp(UVP2_OT_Help): bl_label = 'UVP Setup Help' bl_idname = 'uvpackmaster2.uv_uvp_setup_help' bl_description = \"Show help",
"# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY",
"\"Show help for handling invalid topology errors\" URL_SUFFIX = \"invalid-topology-issues\" class UVP2_OT_PixelMarginHelp(UVP2_OT_Help): bl_label",
"grouping_enabled(self): return self.prefs.grouping_enabled(self.scene_props) def get_group_method(self): return self.scene_props.group_method def send_rot_step(self): return self.prefs.FEATURE_island_rotation_step and self.scene_props.rot_enable",
"popen_args['creationflags'] = creation_flags self.uvp_proc = subprocess.Popen(uvp_args_final, stdin=subprocess.PIPE, stdout=subprocess.PIPE, **popen_args) out_stream = self.uvp_proc.stdin out_stream.write(self.p_context.serialized_maps)",
"a longer time (press ESC to abort)' if self.curr_phase is None: return False",
"= read_int_array(self.invalid_faces_msg) if not self.prefs.FEATURE_demo: if len(invalid_faces) != invalid_face_count: self.raiseUnexpectedOutputError() if invalid_face_count >",
"def get_uvp_opcode(self): return UvPackerOpcode.SELECT_SIMILAR def process_result(self): if self.similar_islands_msg is None: self.raiseUnexpectedOutputError() similar_island_count ="
] |
[
"as ByteLevelDecoder from tokenizers.models import BPE from tokenizers.normalizers import Lowercase, NFKC, Sequence from",
"trainers, processors def get_smi_files(directory): files = [] for filename in os.listdir(directory): if filename.endswith(\".smi\"):",
"__name__ == '__main__': parser = argparse.ArgumentParser(description='Generate a smiles tokenizer given candidate files and",
"filename.endswith(\".smi\"): files.append(os.path.join(directory, filename)) else: continue return files def main(args): if args.do_train: # Initialize",
"tokenizers.models import BPE from tokenizers.normalizers import Lowercase, NFKC, Sequence from tokenizers.pre_tokenizers import ByteLevel",
"encoding = tokenizer.encode(args.test_string) print(\"Encoded string: {}\".format(encoding.tokens)) print(encoding.ids) decoded = tokenizer.decode(encoding.ids) print(\"Decoded string: {}\".format(decoded))",
"smiles tokenizer given candidate files and target configs.') parser.add_argument('--training_files', type=str, default='data/', help='source of",
"default=2000, help='Size of the vocab to rain') parser.add_argument('--min_frequency', type=int, default=2, help='min fequency of",
"length=args.pad_len) tokenizer.enable_truncation(max_length=args.pad_len,strategy='only_first') tokenizer.normalizer = Sequence([NFKC()]) tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) tokenizer.decoder = decoders.ByteLevel() tokenizer.post_processor =",
"pad tokenized input') parser.add_argument('--do_train', action='store_true', help='Train a tokenizer' ) parser.add_argument('--do_test', action='store_true', help='Test the",
"default='CC(C)CCNc1cnnc(NCCc2ccc(S(N)(=O)=O)cc2)n1', help='a SMILES string to test tokenizer with') parser.add_argument('--tokenizer_name', type=str, default='tokenizer_vocab_2000.json') parser.add_argument('--vocab_size', type=int,",
"print(encoding.ids) decoded = tokenizer.decode(encoding.ids) print(\"Decoded string: {}\".format(decoded)) if __name__ == '__main__': parser =",
"to test tokenizer with') parser.add_argument('--tokenizer_name', type=str, default='tokenizer_vocab_2000.json') parser.add_argument('--vocab_size', type=int, default=2000, help='Size of the",
"string: {}\".format(encoding.tokens)) print(encoding.ids) decoded = tokenizer.decode(encoding.ids) print(\"Decoded string: {}\".format(decoded)) if __name__ == '__main__':",
"parser = argparse.ArgumentParser(description='Generate a smiles tokenizer given candidate files and target configs.') parser.add_argument('--training_files',",
"{}\".format(decoded)) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Generate a smiles tokenizer given candidate",
"the following files:{}\".format(files)) tokenizer = Tokenizer(models.BPE(unk_token=\"<unk>\")) tokenizer.enable_padding(pad_id=args.vocab_size+2, pad_token=\"<pad>\", length=args.pad_len) tokenizer.enable_truncation(max_length=args.pad_len,strategy='only_first') tokenizer.normalizer = Sequence([NFKC()])",
"rain') parser.add_argument('--min_frequency', type=int, default=2, help='min fequency of word in corpus') args = parser.parse_args()",
"tokenizers.decoders import ByteLevel as ByteLevelDecoder from tokenizers.models import BPE from tokenizers.normalizers import Lowercase,",
"a tokenizer files = get_smi_files(args.training_files) print(\"Training BPE tokenizer using the following files:{}\".format(files)) tokenizer",
"pad_token=\"<pad>\", length=args.pad_len) tokenizer.enable_truncation(max_length=args.pad_len,strategy='only_first') tokenizer.normalizer = Sequence([NFKC()]) tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) tokenizer.decoder = decoders.ByteLevel() tokenizer.post_processor",
"action='store_true', help='Train a tokenizer' ) parser.add_argument('--do_test', action='store_true', help='Test the tokenizer found in tokenizer",
"following files:{}\".format(files)) tokenizer = Tokenizer(models.BPE(unk_token=\"<unk>\")) tokenizer.enable_padding(pad_id=args.vocab_size+2, pad_token=\"<pad>\", length=args.pad_len) tokenizer.enable_truncation(max_length=args.pad_len,strategy='only_first') tokenizer.normalizer = Sequence([NFKC()]) tokenizer.pre_tokenizer",
"parser.add_argument('--test_string', type=str, default='CC(C)CCNc1cnnc(NCCc2ccc(S(N)(=O)=O)cc2)n1', help='a SMILES string to test tokenizer with') parser.add_argument('--tokenizer_name', type=str, default='tokenizer_vocab_2000.json')",
"NFKC, Sequence from tokenizers.pre_tokenizers import ByteLevel from tokenizers.trainers import BpeTrainer from tokenizers import",
"if args.do_train: # Initialize a tokenizer files = get_smi_files(args.training_files) print(\"Training BPE tokenizer using",
"vocab size: {}\".format(tokenizer.get_vocab_size())) if args.do_test: # Test the tokenizer tokenizer = Tokenizer.from_file(os.path.join('tokenizers',args.tokenizer_name)) print(\"Testing",
"files def main(args): if args.do_train: # Initialize a tokenizer files = get_smi_files(args.training_files) print(\"Training",
"of the vocab to rain') parser.add_argument('--min_frequency', type=int, default=2, help='min fequency of word in",
"Initialize a tokenizer files = get_smi_files(args.training_files) print(\"Training BPE tokenizer using the following files:{}\".format(files))",
"import Tokenizer, models, pre_tokenizers, decoders, trainers, processors def get_smi_files(directory): files = [] for",
"pre_tokenizers.ByteLevel(add_prefix_space=False) tokenizer.decoder = decoders.ByteLevel() tokenizer.post_processor = processors.ByteLevel(trim_offsets=True) # Train the tokenizer trainer =",
"tokenizer.normalizer = Sequence([NFKC()]) tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) tokenizer.decoder = decoders.ByteLevel() tokenizer.post_processor = processors.ByteLevel(trim_offsets=True) #",
"with SMILES String: {}\".format(args.test_string)) encoding = tokenizer.encode(args.test_string) print(\"Encoded string: {}\".format(encoding.tokens)) print(encoding.ids) decoded =",
"from tokenizers import Tokenizer, models, pre_tokenizers, decoders, trainers, processors def get_smi_files(directory): files =",
"== '__main__': parser = argparse.ArgumentParser(description='Generate a smiles tokenizer given candidate files and target",
"type=str, default='CC(C)CCNc1cnnc(NCCc2ccc(S(N)(=O)=O)cc2)n1', help='a SMILES string to test tokenizer with') parser.add_argument('--tokenizer_name', type=str, default='tokenizer_vocab_2000.json') parser.add_argument('--vocab_size',",
"parser.add_argument('--pad_len', type=int, default=150, help='how much to pad tokenized input') parser.add_argument('--do_train', action='store_true', help='Train a",
"ByteLevel from tokenizers.trainers import BpeTrainer from tokenizers import Tokenizer, models, pre_tokenizers, decoders, trainers,",
"tokenized input') parser.add_argument('--do_train', action='store_true', help='Train a tokenizer' ) parser.add_argument('--do_test', action='store_true', help='Test the tokenizer",
"type=int, default=2000, help='Size of the vocab to rain') parser.add_argument('--min_frequency', type=int, default=2, help='min fequency",
"to rain') parser.add_argument('--min_frequency', type=int, default=2, help='min fequency of word in corpus') args =",
"from tokenizers.models import BPE from tokenizers.normalizers import Lowercase, NFKC, Sequence from tokenizers.pre_tokenizers import",
"main(args): if args.do_train: # Initialize a tokenizer files = get_smi_files(args.training_files) print(\"Training BPE tokenizer",
"else: continue return files def main(args): if args.do_train: # Initialize a tokenizer files",
"decoders, trainers, processors def get_smi_files(directory): files = [] for filename in os.listdir(directory): if",
"dir file') parser.add_argument('--test_string', type=str, default='CC(C)CCNc1cnnc(NCCc2ccc(S(N)(=O)=O)cc2)n1', help='a SMILES string to test tokenizer with') parser.add_argument('--tokenizer_name',",
"file') parser.add_argument('--test_string', type=str, default='CC(C)CCNc1cnnc(NCCc2ccc(S(N)(=O)=O)cc2)n1', help='a SMILES string to test tokenizer with') parser.add_argument('--tokenizer_name', type=str,",
"using the following files:{}\".format(files)) tokenizer = Tokenizer(models.BPE(unk_token=\"<unk>\")) tokenizer.enable_padding(pad_id=args.vocab_size+2, pad_token=\"<pad>\", length=args.pad_len) tokenizer.enable_truncation(max_length=args.pad_len,strategy='only_first') tokenizer.normalizer =",
"os import argparse from tokenizers.decoders import ByteLevel as ByteLevelDecoder from tokenizers.models import BPE",
"pretty=True) print(\"Trained vocab size: {}\".format(tokenizer.get_vocab_size())) if args.do_test: # Test the tokenizer tokenizer =",
"parser.add_argument('--training_files', type=str, default='data/', help='source of input smiles data') parser.add_argument('--pad_len', type=int, default=150, help='how much",
"{}\".format(args.test_string)) encoding = tokenizer.encode(args.test_string) print(\"Encoded string: {}\".format(encoding.tokens)) print(encoding.ids) decoded = tokenizer.decode(encoding.ids) print(\"Decoded string:",
"ByteLevelDecoder from tokenizers.models import BPE from tokenizers.normalizers import Lowercase, NFKC, Sequence from tokenizers.pre_tokenizers",
"= Tokenizer.from_file(os.path.join('tokenizers',args.tokenizer_name)) print(\"Testing with SMILES String: {}\".format(args.test_string)) encoding = tokenizer.encode(args.test_string) print(\"Encoded string: {}\".format(encoding.tokens))",
"tokenizer.enable_truncation(max_length=args.pad_len,strategy='only_first') tokenizer.normalizer = Sequence([NFKC()]) tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) tokenizer.decoder = decoders.ByteLevel() tokenizer.post_processor = processors.ByteLevel(trim_offsets=True)",
"tokenizer files = get_smi_files(args.training_files) print(\"Training BPE tokenizer using the following files:{}\".format(files)) tokenizer =",
"help='a SMILES string to test tokenizer with') parser.add_argument('--tokenizer_name', type=str, default='tokenizer_vocab_2000.json') parser.add_argument('--vocab_size', type=int, default=2000,",
"filename)) else: continue return files def main(args): if args.do_train: # Initialize a tokenizer",
"files = get_smi_files(args.training_files) print(\"Training BPE tokenizer using the following files:{}\".format(files)) tokenizer = Tokenizer(models.BPE(unk_token=\"<unk>\"))",
"import BPE from tokenizers.normalizers import Lowercase, NFKC, Sequence from tokenizers.pre_tokenizers import ByteLevel from",
"from tokenizers.trainers import BpeTrainer from tokenizers import Tokenizer, models, pre_tokenizers, decoders, trainers, processors",
"of input smiles data') parser.add_argument('--pad_len', type=int, default=150, help='how much to pad tokenized input')",
"tokenizer.train(files, trainer=trainer) tokenizer.add_tokens([\"<start>\", \"<end>\" ]) tokenizer.save(os.path.join('tokenizers',args.tokenizer_name), pretty=True) print(\"Trained vocab size: {}\".format(tokenizer.get_vocab_size())) if args.do_test:",
"Train the tokenizer trainer = trainers.BpeTrainer(show_progress=True, vocab_size=args.vocab_size, min_frequency=args.min_frequency) tokenizer.train(files, trainer=trainer) tokenizer.add_tokens([\"<start>\", \"<end>\" ])",
"tokenizer found in tokenizer dir file') parser.add_argument('--test_string', type=str, default='CC(C)CCNc1cnnc(NCCc2ccc(S(N)(=O)=O)cc2)n1', help='a SMILES string to",
"tokenizer tokenizer = Tokenizer.from_file(os.path.join('tokenizers',args.tokenizer_name)) print(\"Testing with SMILES String: {}\".format(args.test_string)) encoding = tokenizer.encode(args.test_string) print(\"Encoded",
"import BpeTrainer from tokenizers import Tokenizer, models, pre_tokenizers, decoders, trainers, processors def get_smi_files(directory):",
"files:{}\".format(files)) tokenizer = Tokenizer(models.BPE(unk_token=\"<unk>\")) tokenizer.enable_padding(pad_id=args.vocab_size+2, pad_token=\"<pad>\", length=args.pad_len) tokenizer.enable_truncation(max_length=args.pad_len,strategy='only_first') tokenizer.normalizer = Sequence([NFKC()]) tokenizer.pre_tokenizer =",
"type=int, default=150, help='how much to pad tokenized input') parser.add_argument('--do_train', action='store_true', help='Train a tokenizer'",
"decoders.ByteLevel() tokenizer.post_processor = processors.ByteLevel(trim_offsets=True) # Train the tokenizer trainer = trainers.BpeTrainer(show_progress=True, vocab_size=args.vocab_size, min_frequency=args.min_frequency)",
"processors.ByteLevel(trim_offsets=True) # Train the tokenizer trainer = trainers.BpeTrainer(show_progress=True, vocab_size=args.vocab_size, min_frequency=args.min_frequency) tokenizer.train(files, trainer=trainer) tokenizer.add_tokens([\"<start>\",",
"get_smi_files(directory): files = [] for filename in os.listdir(directory): if filename.endswith(\".smi\"): files.append(os.path.join(directory, filename)) else:",
"pre_tokenizers, decoders, trainers, processors def get_smi_files(directory): files = [] for filename in os.listdir(directory):",
"the tokenizer trainer = trainers.BpeTrainer(show_progress=True, vocab_size=args.vocab_size, min_frequency=args.min_frequency) tokenizer.train(files, trainer=trainer) tokenizer.add_tokens([\"<start>\", \"<end>\" ]) tokenizer.save(os.path.join('tokenizers',args.tokenizer_name),",
"input smiles data') parser.add_argument('--pad_len', type=int, default=150, help='how much to pad tokenized input') parser.add_argument('--do_train',",
"much to pad tokenized input') parser.add_argument('--do_train', action='store_true', help='Train a tokenizer' ) parser.add_argument('--do_test', action='store_true',",
"= [] for filename in os.listdir(directory): if filename.endswith(\".smi\"): files.append(os.path.join(directory, filename)) else: continue return",
"given candidate files and target configs.') parser.add_argument('--training_files', type=str, default='data/', help='source of input smiles",
") parser.add_argument('--do_test', action='store_true', help='Test the tokenizer found in tokenizer dir file') parser.add_argument('--test_string', type=str,",
"tokenizer trainer = trainers.BpeTrainer(show_progress=True, vocab_size=args.vocab_size, min_frequency=args.min_frequency) tokenizer.train(files, trainer=trainer) tokenizer.add_tokens([\"<start>\", \"<end>\" ]) tokenizer.save(os.path.join('tokenizers',args.tokenizer_name), pretty=True)",
"= trainers.BpeTrainer(show_progress=True, vocab_size=args.vocab_size, min_frequency=args.min_frequency) tokenizer.train(files, trainer=trainer) tokenizer.add_tokens([\"<start>\", \"<end>\" ]) tokenizer.save(os.path.join('tokenizers',args.tokenizer_name), pretty=True) print(\"Trained vocab",
"tokenizer.decode(encoding.ids) print(\"Decoded string: {}\".format(decoded)) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Generate a smiles",
"def get_smi_files(directory): files = [] for filename in os.listdir(directory): if filename.endswith(\".smi\"): files.append(os.path.join(directory, filename))",
"ByteLevel as ByteLevelDecoder from tokenizers.models import BPE from tokenizers.normalizers import Lowercase, NFKC, Sequence",
"tokenizers.pre_tokenizers import ByteLevel from tokenizers.trainers import BpeTrainer from tokenizers import Tokenizer, models, pre_tokenizers,",
"= Tokenizer(models.BPE(unk_token=\"<unk>\")) tokenizer.enable_padding(pad_id=args.vocab_size+2, pad_token=\"<pad>\", length=args.pad_len) tokenizer.enable_truncation(max_length=args.pad_len,strategy='only_first') tokenizer.normalizer = Sequence([NFKC()]) tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) tokenizer.decoder",
"print(\"Decoded string: {}\".format(decoded)) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Generate a smiles tokenizer",
"Test the tokenizer tokenizer = Tokenizer.from_file(os.path.join('tokenizers',args.tokenizer_name)) print(\"Testing with SMILES String: {}\".format(args.test_string)) encoding =",
"the vocab to rain') parser.add_argument('--min_frequency', type=int, default=2, help='min fequency of word in corpus')",
"= decoders.ByteLevel() tokenizer.post_processor = processors.ByteLevel(trim_offsets=True) # Train the tokenizer trainer = trainers.BpeTrainer(show_progress=True, vocab_size=args.vocab_size,",
"tokenizers.trainers import BpeTrainer from tokenizers import Tokenizer, models, pre_tokenizers, decoders, trainers, processors def",
"os.listdir(directory): if filename.endswith(\".smi\"): files.append(os.path.join(directory, filename)) else: continue return files def main(args): if args.do_train:",
"configs.') parser.add_argument('--training_files', type=str, default='data/', help='source of input smiles data') parser.add_argument('--pad_len', type=int, default=150, help='how",
"print(\"Trained vocab size: {}\".format(tokenizer.get_vocab_size())) if args.do_test: # Test the tokenizer tokenizer = Tokenizer.from_file(os.path.join('tokenizers',args.tokenizer_name))",
"tokenizer.add_tokens([\"<start>\", \"<end>\" ]) tokenizer.save(os.path.join('tokenizers',args.tokenizer_name), pretty=True) print(\"Trained vocab size: {}\".format(tokenizer.get_vocab_size())) if args.do_test: # Test",
"trainer=trainer) tokenizer.add_tokens([\"<start>\", \"<end>\" ]) tokenizer.save(os.path.join('tokenizers',args.tokenizer_name), pretty=True) print(\"Trained vocab size: {}\".format(tokenizer.get_vocab_size())) if args.do_test: #",
"Tokenizer(models.BPE(unk_token=\"<unk>\")) tokenizer.enable_padding(pad_id=args.vocab_size+2, pad_token=\"<pad>\", length=args.pad_len) tokenizer.enable_truncation(max_length=args.pad_len,strategy='only_first') tokenizer.normalizer = Sequence([NFKC()]) tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) tokenizer.decoder =",
"\"<end>\" ]) tokenizer.save(os.path.join('tokenizers',args.tokenizer_name), pretty=True) print(\"Trained vocab size: {}\".format(tokenizer.get_vocab_size())) if args.do_test: # Test the",
"= tokenizer.decode(encoding.ids) print(\"Decoded string: {}\".format(decoded)) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Generate a",
"args.do_train: # Initialize a tokenizer files = get_smi_files(args.training_files) print(\"Training BPE tokenizer using the",
"and target configs.') parser.add_argument('--training_files', type=str, default='data/', help='source of input smiles data') parser.add_argument('--pad_len', type=int,",
"string to test tokenizer with') parser.add_argument('--tokenizer_name', type=str, default='tokenizer_vocab_2000.json') parser.add_argument('--vocab_size', type=int, default=2000, help='Size of",
"parser.add_argument('--do_test', action='store_true', help='Test the tokenizer found in tokenizer dir file') parser.add_argument('--test_string', type=str, default='CC(C)CCNc1cnnc(NCCc2ccc(S(N)(=O)=O)cc2)n1',",
"parser.add_argument('--min_frequency', type=int, default=2, help='min fequency of word in corpus') args = parser.parse_args() main(args)",
"filename in os.listdir(directory): if filename.endswith(\".smi\"): files.append(os.path.join(directory, filename)) else: continue return files def main(args):",
"tokenizer.encode(args.test_string) print(\"Encoded string: {}\".format(encoding.tokens)) print(encoding.ids) decoded = tokenizer.decode(encoding.ids) print(\"Decoded string: {}\".format(decoded)) if __name__",
"Tokenizer.from_file(os.path.join('tokenizers',args.tokenizer_name)) print(\"Testing with SMILES String: {}\".format(args.test_string)) encoding = tokenizer.encode(args.test_string) print(\"Encoded string: {}\".format(encoding.tokens)) print(encoding.ids)",
"SMILES string to test tokenizer with') parser.add_argument('--tokenizer_name', type=str, default='tokenizer_vocab_2000.json') parser.add_argument('--vocab_size', type=int, default=2000, help='Size",
"Sequence from tokenizers.pre_tokenizers import ByteLevel from tokenizers.trainers import BpeTrainer from tokenizers import Tokenizer,",
"get_smi_files(args.training_files) print(\"Training BPE tokenizer using the following files:{}\".format(files)) tokenizer = Tokenizer(models.BPE(unk_token=\"<unk>\")) tokenizer.enable_padding(pad_id=args.vocab_size+2, pad_token=\"<pad>\",",
"to pad tokenized input') parser.add_argument('--do_train', action='store_true', help='Train a tokenizer' ) parser.add_argument('--do_test', action='store_true', help='Test",
"print(\"Training BPE tokenizer using the following files:{}\".format(files)) tokenizer = Tokenizer(models.BPE(unk_token=\"<unk>\")) tokenizer.enable_padding(pad_id=args.vocab_size+2, pad_token=\"<pad>\", length=args.pad_len)",
"for filename in os.listdir(directory): if filename.endswith(\".smi\"): files.append(os.path.join(directory, filename)) else: continue return files def",
"SMILES String: {}\".format(args.test_string)) encoding = tokenizer.encode(args.test_string) print(\"Encoded string: {}\".format(encoding.tokens)) print(encoding.ids) decoded = tokenizer.decode(encoding.ids)",
"tokenizers.normalizers import Lowercase, NFKC, Sequence from tokenizers.pre_tokenizers import ByteLevel from tokenizers.trainers import BpeTrainer",
"default=150, help='how much to pad tokenized input') parser.add_argument('--do_train', action='store_true', help='Train a tokenizer' )",
"the tokenizer found in tokenizer dir file') parser.add_argument('--test_string', type=str, default='CC(C)CCNc1cnnc(NCCc2ccc(S(N)(=O)=O)cc2)n1', help='a SMILES string",
"with') parser.add_argument('--tokenizer_name', type=str, default='tokenizer_vocab_2000.json') parser.add_argument('--vocab_size', type=int, default=2000, help='Size of the vocab to rain')",
"parser.add_argument('--vocab_size', type=int, default=2000, help='Size of the vocab to rain') parser.add_argument('--min_frequency', type=int, default=2, help='min",
"trainer = trainers.BpeTrainer(show_progress=True, vocab_size=args.vocab_size, min_frequency=args.min_frequency) tokenizer.train(files, trainer=trainer) tokenizer.add_tokens([\"<start>\", \"<end>\" ]) tokenizer.save(os.path.join('tokenizers',args.tokenizer_name), pretty=True) print(\"Trained",
"tokenizers import Tokenizer, models, pre_tokenizers, decoders, trainers, processors def get_smi_files(directory): files = []",
"tokenizer with') parser.add_argument('--tokenizer_name', type=str, default='tokenizer_vocab_2000.json') parser.add_argument('--vocab_size', type=int, default=2000, help='Size of the vocab to",
"from tokenizers.normalizers import Lowercase, NFKC, Sequence from tokenizers.pre_tokenizers import ByteLevel from tokenizers.trainers import",
"= get_smi_files(args.training_files) print(\"Training BPE tokenizer using the following files:{}\".format(files)) tokenizer = Tokenizer(models.BPE(unk_token=\"<unk>\")) tokenizer.enable_padding(pad_id=args.vocab_size+2,",
"BpeTrainer from tokenizers import Tokenizer, models, pre_tokenizers, decoders, trainers, processors def get_smi_files(directory): files",
"the tokenizer tokenizer = Tokenizer.from_file(os.path.join('tokenizers',args.tokenizer_name)) print(\"Testing with SMILES String: {}\".format(args.test_string)) encoding = tokenizer.encode(args.test_string)",
"import os import argparse from tokenizers.decoders import ByteLevel as ByteLevelDecoder from tokenizers.models import",
"vocab to rain') parser.add_argument('--min_frequency', type=int, default=2, help='min fequency of word in corpus') args",
"in os.listdir(directory): if filename.endswith(\".smi\"): files.append(os.path.join(directory, filename)) else: continue return files def main(args): if",
"files = [] for filename in os.listdir(directory): if filename.endswith(\".smi\"): files.append(os.path.join(directory, filename)) else: continue",
"in tokenizer dir file') parser.add_argument('--test_string', type=str, default='CC(C)CCNc1cnnc(NCCc2ccc(S(N)(=O)=O)cc2)n1', help='a SMILES string to test tokenizer",
"tokenizer.post_processor = processors.ByteLevel(trim_offsets=True) # Train the tokenizer trainer = trainers.BpeTrainer(show_progress=True, vocab_size=args.vocab_size, min_frequency=args.min_frequency) tokenizer.train(files,",
"test tokenizer with') parser.add_argument('--tokenizer_name', type=str, default='tokenizer_vocab_2000.json') parser.add_argument('--vocab_size', type=int, default=2000, help='Size of the vocab",
"tokenizer = Tokenizer(models.BPE(unk_token=\"<unk>\")) tokenizer.enable_padding(pad_id=args.vocab_size+2, pad_token=\"<pad>\", length=args.pad_len) tokenizer.enable_truncation(max_length=args.pad_len,strategy='only_first') tokenizer.normalizer = Sequence([NFKC()]) tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)",
"String: {}\".format(args.test_string)) encoding = tokenizer.encode(args.test_string) print(\"Encoded string: {}\".format(encoding.tokens)) print(encoding.ids) decoded = tokenizer.decode(encoding.ids) print(\"Decoded",
"parser.add_argument('--do_train', action='store_true', help='Train a tokenizer' ) parser.add_argument('--do_test', action='store_true', help='Test the tokenizer found in",
"size: {}\".format(tokenizer.get_vocab_size())) if args.do_test: # Test the tokenizer tokenizer = Tokenizer.from_file(os.path.join('tokenizers',args.tokenizer_name)) print(\"Testing with",
"# Train the tokenizer trainer = trainers.BpeTrainer(show_progress=True, vocab_size=args.vocab_size, min_frequency=args.min_frequency) tokenizer.train(files, trainer=trainer) tokenizer.add_tokens([\"<start>\", \"<end>\"",
"<filename>src/data_gen/train_tokenizer.py import os import argparse from tokenizers.decoders import ByteLevel as ByteLevelDecoder from tokenizers.models",
"def main(args): if args.do_train: # Initialize a tokenizer files = get_smi_files(args.training_files) print(\"Training BPE",
"decoded = tokenizer.decode(encoding.ids) print(\"Decoded string: {}\".format(decoded)) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Generate",
"a tokenizer' ) parser.add_argument('--do_test', action='store_true', help='Test the tokenizer found in tokenizer dir file')",
"tokenizer.enable_padding(pad_id=args.vocab_size+2, pad_token=\"<pad>\", length=args.pad_len) tokenizer.enable_truncation(max_length=args.pad_len,strategy='only_first') tokenizer.normalizer = Sequence([NFKC()]) tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) tokenizer.decoder = decoders.ByteLevel()",
"argparse.ArgumentParser(description='Generate a smiles tokenizer given candidate files and target configs.') parser.add_argument('--training_files', type=str, default='data/',",
"a smiles tokenizer given candidate files and target configs.') parser.add_argument('--training_files', type=str, default='data/', help='source",
"[] for filename in os.listdir(directory): if filename.endswith(\".smi\"): files.append(os.path.join(directory, filename)) else: continue return files",
"files and target configs.') parser.add_argument('--training_files', type=str, default='data/', help='source of input smiles data') parser.add_argument('--pad_len',",
"]) tokenizer.save(os.path.join('tokenizers',args.tokenizer_name), pretty=True) print(\"Trained vocab size: {}\".format(tokenizer.get_vocab_size())) if args.do_test: # Test the tokenizer",
"args.do_test: # Test the tokenizer tokenizer = Tokenizer.from_file(os.path.join('tokenizers',args.tokenizer_name)) print(\"Testing with SMILES String: {}\".format(args.test_string))",
"continue return files def main(args): if args.do_train: # Initialize a tokenizer files =",
"help='how much to pad tokenized input') parser.add_argument('--do_train', action='store_true', help='Train a tokenizer' ) parser.add_argument('--do_test',",
"files.append(os.path.join(directory, filename)) else: continue return files def main(args): if args.do_train: # Initialize a",
"tokenizer dir file') parser.add_argument('--test_string', type=str, default='CC(C)CCNc1cnnc(NCCc2ccc(S(N)(=O)=O)cc2)n1', help='a SMILES string to test tokenizer with')",
"tokenizer = Tokenizer.from_file(os.path.join('tokenizers',args.tokenizer_name)) print(\"Testing with SMILES String: {}\".format(args.test_string)) encoding = tokenizer.encode(args.test_string) print(\"Encoded string:",
"from tokenizers.pre_tokenizers import ByteLevel from tokenizers.trainers import BpeTrainer from tokenizers import Tokenizer, models,",
"'__main__': parser = argparse.ArgumentParser(description='Generate a smiles tokenizer given candidate files and target configs.')",
"= tokenizer.encode(args.test_string) print(\"Encoded string: {}\".format(encoding.tokens)) print(encoding.ids) decoded = tokenizer.decode(encoding.ids) print(\"Decoded string: {}\".format(decoded)) if",
"default='data/', help='source of input smiles data') parser.add_argument('--pad_len', type=int, default=150, help='how much to pad",
"= pre_tokenizers.ByteLevel(add_prefix_space=False) tokenizer.decoder = decoders.ByteLevel() tokenizer.post_processor = processors.ByteLevel(trim_offsets=True) # Train the tokenizer trainer",
"min_frequency=args.min_frequency) tokenizer.train(files, trainer=trainer) tokenizer.add_tokens([\"<start>\", \"<end>\" ]) tokenizer.save(os.path.join('tokenizers',args.tokenizer_name), pretty=True) print(\"Trained vocab size: {}\".format(tokenizer.get_vocab_size())) if",
"processors def get_smi_files(directory): files = [] for filename in os.listdir(directory): if filename.endswith(\".smi\"): files.append(os.path.join(directory,",
"tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) tokenizer.decoder = decoders.ByteLevel() tokenizer.post_processor = processors.ByteLevel(trim_offsets=True) # Train the tokenizer",
"Sequence([NFKC()]) tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) tokenizer.decoder = decoders.ByteLevel() tokenizer.post_processor = processors.ByteLevel(trim_offsets=True) # Train the",
"tokenizer given candidate files and target configs.') parser.add_argument('--training_files', type=str, default='data/', help='source of input",
"data') parser.add_argument('--pad_len', type=int, default=150, help='how much to pad tokenized input') parser.add_argument('--do_train', action='store_true', help='Train",
"{}\".format(tokenizer.get_vocab_size())) if args.do_test: # Test the tokenizer tokenizer = Tokenizer.from_file(os.path.join('tokenizers',args.tokenizer_name)) print(\"Testing with SMILES",
"argparse from tokenizers.decoders import ByteLevel as ByteLevelDecoder from tokenizers.models import BPE from tokenizers.normalizers",
"BPE from tokenizers.normalizers import Lowercase, NFKC, Sequence from tokenizers.pre_tokenizers import ByteLevel from tokenizers.trainers",
"models, pre_tokenizers, decoders, trainers, processors def get_smi_files(directory): files = [] for filename in",
"candidate files and target configs.') parser.add_argument('--training_files', type=str, default='data/', help='source of input smiles data')",
"{}\".format(encoding.tokens)) print(encoding.ids) decoded = tokenizer.decode(encoding.ids) print(\"Decoded string: {}\".format(decoded)) if __name__ == '__main__': parser",
"parser.add_argument('--tokenizer_name', type=str, default='tokenizer_vocab_2000.json') parser.add_argument('--vocab_size', type=int, default=2000, help='Size of the vocab to rain') parser.add_argument('--min_frequency',",
"BPE tokenizer using the following files:{}\".format(files)) tokenizer = Tokenizer(models.BPE(unk_token=\"<unk>\")) tokenizer.enable_padding(pad_id=args.vocab_size+2, pad_token=\"<pad>\", length=args.pad_len) tokenizer.enable_truncation(max_length=args.pad_len,strategy='only_first')",
"type=str, default='data/', help='source of input smiles data') parser.add_argument('--pad_len', type=int, default=150, help='how much to",
"vocab_size=args.vocab_size, min_frequency=args.min_frequency) tokenizer.train(files, trainer=trainer) tokenizer.add_tokens([\"<start>\", \"<end>\" ]) tokenizer.save(os.path.join('tokenizers',args.tokenizer_name), pretty=True) print(\"Trained vocab size: {}\".format(tokenizer.get_vocab_size()))",
"# Initialize a tokenizer files = get_smi_files(args.training_files) print(\"Training BPE tokenizer using the following",
"= Sequence([NFKC()]) tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) tokenizer.decoder = decoders.ByteLevel() tokenizer.post_processor = processors.ByteLevel(trim_offsets=True) # Train",
"if args.do_test: # Test the tokenizer tokenizer = Tokenizer.from_file(os.path.join('tokenizers',args.tokenizer_name)) print(\"Testing with SMILES String:",
"tokenizer.decoder = decoders.ByteLevel() tokenizer.post_processor = processors.ByteLevel(trim_offsets=True) # Train the tokenizer trainer = trainers.BpeTrainer(show_progress=True,",
"if __name__ == '__main__': parser = argparse.ArgumentParser(description='Generate a smiles tokenizer given candidate files",
"found in tokenizer dir file') parser.add_argument('--test_string', type=str, default='CC(C)CCNc1cnnc(NCCc2ccc(S(N)(=O)=O)cc2)n1', help='a SMILES string to test",
"tokenizer.save(os.path.join('tokenizers',args.tokenizer_name), pretty=True) print(\"Trained vocab size: {}\".format(tokenizer.get_vocab_size())) if args.do_test: # Test the tokenizer tokenizer",
"target configs.') parser.add_argument('--training_files', type=str, default='data/', help='source of input smiles data') parser.add_argument('--pad_len', type=int, default=150,",
"tokenizer using the following files:{}\".format(files)) tokenizer = Tokenizer(models.BPE(unk_token=\"<unk>\")) tokenizer.enable_padding(pad_id=args.vocab_size+2, pad_token=\"<pad>\", length=args.pad_len) tokenizer.enable_truncation(max_length=args.pad_len,strategy='only_first') tokenizer.normalizer",
"default='tokenizer_vocab_2000.json') parser.add_argument('--vocab_size', type=int, default=2000, help='Size of the vocab to rain') parser.add_argument('--min_frequency', type=int, default=2,",
"input') parser.add_argument('--do_train', action='store_true', help='Train a tokenizer' ) parser.add_argument('--do_test', action='store_true', help='Test the tokenizer found",
"tokenizer' ) parser.add_argument('--do_test', action='store_true', help='Test the tokenizer found in tokenizer dir file') parser.add_argument('--test_string',",
"help='source of input smiles data') parser.add_argument('--pad_len', type=int, default=150, help='how much to pad tokenized",
"import argparse from tokenizers.decoders import ByteLevel as ByteLevelDecoder from tokenizers.models import BPE from",
"# Test the tokenizer tokenizer = Tokenizer.from_file(os.path.join('tokenizers',args.tokenizer_name)) print(\"Testing with SMILES String: {}\".format(args.test_string)) encoding",
"Tokenizer, models, pre_tokenizers, decoders, trainers, processors def get_smi_files(directory): files = [] for filename",
"trainers.BpeTrainer(show_progress=True, vocab_size=args.vocab_size, min_frequency=args.min_frequency) tokenizer.train(files, trainer=trainer) tokenizer.add_tokens([\"<start>\", \"<end>\" ]) tokenizer.save(os.path.join('tokenizers',args.tokenizer_name), pretty=True) print(\"Trained vocab size:",
"= argparse.ArgumentParser(description='Generate a smiles tokenizer given candidate files and target configs.') parser.add_argument('--training_files', type=str,",
"help='Test the tokenizer found in tokenizer dir file') parser.add_argument('--test_string', type=str, default='CC(C)CCNc1cnnc(NCCc2ccc(S(N)(=O)=O)cc2)n1', help='a SMILES",
"if filename.endswith(\".smi\"): files.append(os.path.join(directory, filename)) else: continue return files def main(args): if args.do_train: #",
"string: {}\".format(decoded)) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Generate a smiles tokenizer given",
"help='Train a tokenizer' ) parser.add_argument('--do_test', action='store_true', help='Test the tokenizer found in tokenizer dir",
"import Lowercase, NFKC, Sequence from tokenizers.pre_tokenizers import ByteLevel from tokenizers.trainers import BpeTrainer from",
"Lowercase, NFKC, Sequence from tokenizers.pre_tokenizers import ByteLevel from tokenizers.trainers import BpeTrainer from tokenizers",
"= processors.ByteLevel(trim_offsets=True) # Train the tokenizer trainer = trainers.BpeTrainer(show_progress=True, vocab_size=args.vocab_size, min_frequency=args.min_frequency) tokenizer.train(files, trainer=trainer)",
"import ByteLevel as ByteLevelDecoder from tokenizers.models import BPE from tokenizers.normalizers import Lowercase, NFKC,",
"action='store_true', help='Test the tokenizer found in tokenizer dir file') parser.add_argument('--test_string', type=str, default='CC(C)CCNc1cnnc(NCCc2ccc(S(N)(=O)=O)cc2)n1', help='a",
"from tokenizers.decoders import ByteLevel as ByteLevelDecoder from tokenizers.models import BPE from tokenizers.normalizers import",
"print(\"Encoded string: {}\".format(encoding.tokens)) print(encoding.ids) decoded = tokenizer.decode(encoding.ids) print(\"Decoded string: {}\".format(decoded)) if __name__ ==",
"import ByteLevel from tokenizers.trainers import BpeTrainer from tokenizers import Tokenizer, models, pre_tokenizers, decoders,",
"smiles data') parser.add_argument('--pad_len', type=int, default=150, help='how much to pad tokenized input') parser.add_argument('--do_train', action='store_true',",
"return files def main(args): if args.do_train: # Initialize a tokenizer files = get_smi_files(args.training_files)",
"type=str, default='tokenizer_vocab_2000.json') parser.add_argument('--vocab_size', type=int, default=2000, help='Size of the vocab to rain') parser.add_argument('--min_frequency', type=int,",
"help='Size of the vocab to rain') parser.add_argument('--min_frequency', type=int, default=2, help='min fequency of word",
"print(\"Testing with SMILES String: {}\".format(args.test_string)) encoding = tokenizer.encode(args.test_string) print(\"Encoded string: {}\".format(encoding.tokens)) print(encoding.ids) decoded"
] |
[
"= self.custom_link._meta.get_field('url').verbose_name max_length = self.custom_link._meta.get_field('url').max_length self.assertEquals(field_label, 'url') self.assertEquals(max_length, 255) def test_field_order_id(self): field_label =",
"setUp(self): self.custom_link = CustomLink.objects.create(name='Google', url='https://www.google.com', order_id=1) def test_new_object(self): self.assertEquals(self.custom_link.name, 'Google') self.assertEquals(self.custom_link.url, 'https://www.google.com') self.assertEquals(self.custom_link.order_id,",
"self.assertEquals(field_label, 'name') self.assertEquals(max_length, 50) self.assertEquals(unique, True) def test_field_url(self): field_label = self.custom_link._meta.get_field('url').verbose_name max_length =",
"'name') self.assertEquals(max_length, 50) self.assertEquals(unique, True) def test_field_url(self): field_label = self.custom_link._meta.get_field('url').verbose_name max_length = self.custom_link._meta.get_field('url').max_length",
"django.test import TestCase from ..models import CustomLink class CustomLinkModelTests(TestCase): def setUp(self): self.custom_link =",
"def test_field_name(self): field_label = self.custom_link._meta.get_field('name').verbose_name max_length = self.custom_link._meta.get_field('name').max_length unique = self.custom_link._meta.get_field('name').unique self.assertEquals(field_label, 'name')",
"import TestCase from ..models import CustomLink class CustomLinkModelTests(TestCase): def setUp(self): self.custom_link = CustomLink.objects.create(name='Google',",
"True) def test_field_url(self): field_label = self.custom_link._meta.get_field('url').verbose_name max_length = self.custom_link._meta.get_field('url').max_length self.assertEquals(field_label, 'url') self.assertEquals(max_length, 255)",
"= self.custom_link._meta.get_field('url').max_length self.assertEquals(field_label, 'url') self.assertEquals(max_length, 255) def test_field_order_id(self): field_label = self.custom_link._meta.get_field('order_id').verbose_name max_length =",
"unique = self.custom_link._meta.get_field('name').unique self.assertEquals(field_label, 'name') self.assertEquals(max_length, 50) self.assertEquals(unique, True) def test_field_url(self): field_label =",
"self.custom_link._meta.get_field('url').max_length self.assertEquals(field_label, 'url') self.assertEquals(max_length, 255) def test_field_order_id(self): field_label = self.custom_link._meta.get_field('order_id').verbose_name max_length = self.custom_link._meta.get_field('order_id').default",
"= self.custom_link._meta.get_field('name').unique self.assertEquals(field_label, 'name') self.assertEquals(max_length, 50) self.assertEquals(unique, True) def test_field_url(self): field_label = self.custom_link._meta.get_field('url').verbose_name",
"field_label = self.custom_link._meta.get_field('order_id').verbose_name max_length = self.custom_link._meta.get_field('order_id').default self.assertEquals(field_label, 'order id') self.assertEquals(max_length, 0) def test_object_presentation(self):",
"self.custom_link = CustomLink.objects.create(name='Google', url='https://www.google.com', order_id=1) def test_new_object(self): self.assertEquals(self.custom_link.name, 'Google') self.assertEquals(self.custom_link.url, 'https://www.google.com') self.assertEquals(self.custom_link.order_id, 1)",
"= CustomLink.objects.create(name='Google', url='https://www.google.com', order_id=1) def test_new_object(self): self.assertEquals(self.custom_link.name, 'Google') self.assertEquals(self.custom_link.url, 'https://www.google.com') self.assertEquals(self.custom_link.order_id, 1) def",
"'url') self.assertEquals(max_length, 255) def test_field_order_id(self): field_label = self.custom_link._meta.get_field('order_id').verbose_name max_length = self.custom_link._meta.get_field('order_id').default self.assertEquals(field_label, 'order",
"max_length = self.custom_link._meta.get_field('name').max_length unique = self.custom_link._meta.get_field('name').unique self.assertEquals(field_label, 'name') self.assertEquals(max_length, 50) self.assertEquals(unique, True) def",
"CustomLink.objects.create(name='Google', url='https://www.google.com', order_id=1) def test_new_object(self): self.assertEquals(self.custom_link.name, 'Google') self.assertEquals(self.custom_link.url, 'https://www.google.com') self.assertEquals(self.custom_link.order_id, 1) def test_field_name(self):",
"url='https://www.google.com', order_id=1) def test_new_object(self): self.assertEquals(self.custom_link.name, 'Google') self.assertEquals(self.custom_link.url, 'https://www.google.com') self.assertEquals(self.custom_link.order_id, 1) def test_field_name(self): field_label",
"'order id') self.assertEquals(max_length, 0) def test_object_presentation(self): expected_presentation = f\"[{self.custom_link.name}]: {self.custom_link.url}\" self.assertEquals(expected_presentation, str(self.custom_link)) def",
"self.assertEquals(field_label, 'order id') self.assertEquals(max_length, 0) def test_object_presentation(self): expected_presentation = f\"[{self.custom_link.name}]: {self.custom_link.url}\" self.assertEquals(expected_presentation, str(self.custom_link))",
"<reponame>yevgenykuz/dev-team-hub from django.test import TestCase from ..models import CustomLink class CustomLinkModelTests(TestCase): def setUp(self):",
"class CustomLinkModelTests(TestCase): def setUp(self): self.custom_link = CustomLink.objects.create(name='Google', url='https://www.google.com', order_id=1) def test_new_object(self): self.assertEquals(self.custom_link.name, 'Google')",
"def test_new_object(self): self.assertEquals(self.custom_link.name, 'Google') self.assertEquals(self.custom_link.url, 'https://www.google.com') self.assertEquals(self.custom_link.order_id, 1) def test_field_name(self): field_label = self.custom_link._meta.get_field('name').verbose_name",
"self.custom_link._meta.get_field('url').verbose_name max_length = self.custom_link._meta.get_field('url').max_length self.assertEquals(field_label, 'url') self.assertEquals(max_length, 255) def test_field_order_id(self): field_label = self.custom_link._meta.get_field('order_id').verbose_name",
"def test_field_url(self): field_label = self.custom_link._meta.get_field('url').verbose_name max_length = self.custom_link._meta.get_field('url').max_length self.assertEquals(field_label, 'url') self.assertEquals(max_length, 255) def",
"order_id=1) def test_new_object(self): self.assertEquals(self.custom_link.name, 'Google') self.assertEquals(self.custom_link.url, 'https://www.google.com') self.assertEquals(self.custom_link.order_id, 1) def test_field_name(self): field_label =",
"self.assertEquals(self.custom_link.order_id, 1) def test_field_name(self): field_label = self.custom_link._meta.get_field('name').verbose_name max_length = self.custom_link._meta.get_field('name').max_length unique = self.custom_link._meta.get_field('name').unique",
"from django.test import TestCase from ..models import CustomLink class CustomLinkModelTests(TestCase): def setUp(self): self.custom_link",
"test_new_object(self): self.assertEquals(self.custom_link.name, 'Google') self.assertEquals(self.custom_link.url, 'https://www.google.com') self.assertEquals(self.custom_link.order_id, 1) def test_field_name(self): field_label = self.custom_link._meta.get_field('name').verbose_name max_length",
"id') self.assertEquals(max_length, 0) def test_object_presentation(self): expected_presentation = f\"[{self.custom_link.name}]: {self.custom_link.url}\" self.assertEquals(expected_presentation, str(self.custom_link)) def test_object_ordering(self):",
"max_length = self.custom_link._meta.get_field('order_id').default self.assertEquals(field_label, 'order id') self.assertEquals(max_length, 0) def test_object_presentation(self): expected_presentation = f\"[{self.custom_link.name}]:",
"self.assertEquals(unique, True) def test_field_url(self): field_label = self.custom_link._meta.get_field('url').verbose_name max_length = self.custom_link._meta.get_field('url').max_length self.assertEquals(field_label, 'url') self.assertEquals(max_length,",
"= self.custom_link._meta.get_field('name').verbose_name max_length = self.custom_link._meta.get_field('name').max_length unique = self.custom_link._meta.get_field('name').unique self.assertEquals(field_label, 'name') self.assertEquals(max_length, 50) self.assertEquals(unique,",
"= self.custom_link._meta.get_field('order_id').verbose_name max_length = self.custom_link._meta.get_field('order_id').default self.assertEquals(field_label, 'order id') self.assertEquals(max_length, 0) def test_object_presentation(self): expected_presentation",
"TestCase from ..models import CustomLink class CustomLinkModelTests(TestCase): def setUp(self): self.custom_link = CustomLink.objects.create(name='Google', url='https://www.google.com',",
"= self.custom_link._meta.get_field('name').max_length unique = self.custom_link._meta.get_field('name').unique self.assertEquals(field_label, 'name') self.assertEquals(max_length, 50) self.assertEquals(unique, True) def test_field_url(self):",
"'Google') self.assertEquals(self.custom_link.url, 'https://www.google.com') self.assertEquals(self.custom_link.order_id, 1) def test_field_name(self): field_label = self.custom_link._meta.get_field('name').verbose_name max_length = self.custom_link._meta.get_field('name').max_length",
"255) def test_field_order_id(self): field_label = self.custom_link._meta.get_field('order_id').verbose_name max_length = self.custom_link._meta.get_field('order_id').default self.assertEquals(field_label, 'order id') self.assertEquals(max_length,",
"CustomLink class CustomLinkModelTests(TestCase): def setUp(self): self.custom_link = CustomLink.objects.create(name='Google', url='https://www.google.com', order_id=1) def test_new_object(self): self.assertEquals(self.custom_link.name,",
"def test_field_order_id(self): field_label = self.custom_link._meta.get_field('order_id').verbose_name max_length = self.custom_link._meta.get_field('order_id').default self.assertEquals(field_label, 'order id') self.assertEquals(max_length, 0)",
"self.assertEquals(field_label, 'url') self.assertEquals(max_length, 255) def test_field_order_id(self): field_label = self.custom_link._meta.get_field('order_id').verbose_name max_length = self.custom_link._meta.get_field('order_id').default self.assertEquals(field_label,",
"test_field_name(self): field_label = self.custom_link._meta.get_field('name').verbose_name max_length = self.custom_link._meta.get_field('name').max_length unique = self.custom_link._meta.get_field('name').unique self.assertEquals(field_label, 'name') self.assertEquals(max_length,",
"CustomLinkModelTests(TestCase): def setUp(self): self.custom_link = CustomLink.objects.create(name='Google', url='https://www.google.com', order_id=1) def test_new_object(self): self.assertEquals(self.custom_link.name, 'Google') self.assertEquals(self.custom_link.url,",
"self.assertEquals(self.custom_link.url, 'https://www.google.com') self.assertEquals(self.custom_link.order_id, 1) def test_field_name(self): field_label = self.custom_link._meta.get_field('name').verbose_name max_length = self.custom_link._meta.get_field('name').max_length unique",
"import CustomLink class CustomLinkModelTests(TestCase): def setUp(self): self.custom_link = CustomLink.objects.create(name='Google', url='https://www.google.com', order_id=1) def test_new_object(self):",
"field_label = self.custom_link._meta.get_field('name').verbose_name max_length = self.custom_link._meta.get_field('name').max_length unique = self.custom_link._meta.get_field('name').unique self.assertEquals(field_label, 'name') self.assertEquals(max_length, 50)",
"self.custom_link._meta.get_field('name').unique self.assertEquals(field_label, 'name') self.assertEquals(max_length, 50) self.assertEquals(unique, True) def test_field_url(self): field_label = self.custom_link._meta.get_field('url').verbose_name max_length",
"self.custom_link._meta.get_field('order_id').verbose_name max_length = self.custom_link._meta.get_field('order_id').default self.assertEquals(field_label, 'order id') self.assertEquals(max_length, 0) def test_object_presentation(self): expected_presentation =",
"self.assertEquals(max_length, 50) self.assertEquals(unique, True) def test_field_url(self): field_label = self.custom_link._meta.get_field('url').verbose_name max_length = self.custom_link._meta.get_field('url').max_length self.assertEquals(field_label,",
"self.assertEquals(max_length, 255) def test_field_order_id(self): field_label = self.custom_link._meta.get_field('order_id').verbose_name max_length = self.custom_link._meta.get_field('order_id').default self.assertEquals(field_label, 'order id')",
"..models import CustomLink class CustomLinkModelTests(TestCase): def setUp(self): self.custom_link = CustomLink.objects.create(name='Google', url='https://www.google.com', order_id=1) def",
"from ..models import CustomLink class CustomLinkModelTests(TestCase): def setUp(self): self.custom_link = CustomLink.objects.create(name='Google', url='https://www.google.com', order_id=1)",
"def setUp(self): self.custom_link = CustomLink.objects.create(name='Google', url='https://www.google.com', order_id=1) def test_new_object(self): self.assertEquals(self.custom_link.name, 'Google') self.assertEquals(self.custom_link.url, 'https://www.google.com')",
"self.assertEquals(self.custom_link.name, 'Google') self.assertEquals(self.custom_link.url, 'https://www.google.com') self.assertEquals(self.custom_link.order_id, 1) def test_field_name(self): field_label = self.custom_link._meta.get_field('name').verbose_name max_length =",
"self.custom_link._meta.get_field('name').verbose_name max_length = self.custom_link._meta.get_field('name').max_length unique = self.custom_link._meta.get_field('name').unique self.assertEquals(field_label, 'name') self.assertEquals(max_length, 50) self.assertEquals(unique, True)",
"max_length = self.custom_link._meta.get_field('url').max_length self.assertEquals(field_label, 'url') self.assertEquals(max_length, 255) def test_field_order_id(self): field_label = self.custom_link._meta.get_field('order_id').verbose_name max_length",
"test_field_order_id(self): field_label = self.custom_link._meta.get_field('order_id').verbose_name max_length = self.custom_link._meta.get_field('order_id').default self.assertEquals(field_label, 'order id') self.assertEquals(max_length, 0) def",
"= self.custom_link._meta.get_field('order_id').default self.assertEquals(field_label, 'order id') self.assertEquals(max_length, 0) def test_object_presentation(self): expected_presentation = f\"[{self.custom_link.name}]: {self.custom_link.url}\"",
"self.assertEquals(max_length, 0) def test_object_presentation(self): expected_presentation = f\"[{self.custom_link.name}]: {self.custom_link.url}\" self.assertEquals(expected_presentation, str(self.custom_link)) def test_object_ordering(self): self.assertEquals(self.custom_link._meta.ordering,",
"0) def test_object_presentation(self): expected_presentation = f\"[{self.custom_link.name}]: {self.custom_link.url}\" self.assertEquals(expected_presentation, str(self.custom_link)) def test_object_ordering(self): self.assertEquals(self.custom_link._meta.ordering, ['order_id'])",
"test_field_url(self): field_label = self.custom_link._meta.get_field('url').verbose_name max_length = self.custom_link._meta.get_field('url').max_length self.assertEquals(field_label, 'url') self.assertEquals(max_length, 255) def test_field_order_id(self):",
"1) def test_field_name(self): field_label = self.custom_link._meta.get_field('name').verbose_name max_length = self.custom_link._meta.get_field('name').max_length unique = self.custom_link._meta.get_field('name').unique self.assertEquals(field_label,",
"field_label = self.custom_link._meta.get_field('url').verbose_name max_length = self.custom_link._meta.get_field('url').max_length self.assertEquals(field_label, 'url') self.assertEquals(max_length, 255) def test_field_order_id(self): field_label",
"self.custom_link._meta.get_field('name').max_length unique = self.custom_link._meta.get_field('name').unique self.assertEquals(field_label, 'name') self.assertEquals(max_length, 50) self.assertEquals(unique, True) def test_field_url(self): field_label",
"'https://www.google.com') self.assertEquals(self.custom_link.order_id, 1) def test_field_name(self): field_label = self.custom_link._meta.get_field('name').verbose_name max_length = self.custom_link._meta.get_field('name').max_length unique =",
"50) self.assertEquals(unique, True) def test_field_url(self): field_label = self.custom_link._meta.get_field('url').verbose_name max_length = self.custom_link._meta.get_field('url').max_length self.assertEquals(field_label, 'url')",
"self.custom_link._meta.get_field('order_id').default self.assertEquals(field_label, 'order id') self.assertEquals(max_length, 0) def test_object_presentation(self): expected_presentation = f\"[{self.custom_link.name}]: {self.custom_link.url}\" self.assertEquals(expected_presentation,"
] |