code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
from collections import namedtuple from django.conf import settings from django.db.models import ExpressionWrapper, F, FloatField, IntegerField ReportColumnFormat = namedtuple('ReportColumnFormat', ['name', 'format', 'attr_name', 'order_field']) DEFAULTS = { 'SPEEDINFO_TESTS': False, 'SPEEDINFO_CACHED_RESPONSE_ATTR_NAME': 'is_cached', 'SPEEDINFO_PROFILING_CONDITIONS': [ 'speedinfo.conditions.exclude_urls.ExcludeURLCondition', ], 'SPEEDINFO_EXCLUDE_URLS': [], 'SPEEDINFO_REPORT_COLUMNS': ( 'view_name', 'method', 'anon_calls_ratio', 'cache_hits_ratio', 'sql_count_per_call', 'sql_time_ratio', 'total_calls', 'time_per_call', 'total_time'), 'SPEEDINFO_REPORT_COLUMNS_FORMAT': [ ReportColumnFormat('View name', '{}', 'view_name', 'view_name'), ReportColumnFormat('HTTP method', '{}', 'method', 'method'), ReportColumnFormat('Anonymous calls', '{:.1f}%', 'anon_calls_ratio', ExpressionWrapper(100.0 * F('anon_calls') / F('total_calls'), output_field=FloatField())), ReportColumnFormat('Cache hits', '{:.1f}%', 'cache_hits_ratio', ExpressionWrapper(100.0 * F('cache_hits') / F('total_calls'), output_field=FloatField())), ReportColumnFormat('SQL queries per call', '{}', 'sql_count_per_call', ExpressionWrapper(F('sql_total_count') / F('total_calls'), output_field=IntegerField())), ReportColumnFormat('SQL time', '{:.1f}%', 'sql_time_ratio', ExpressionWrapper(100.0 * F('sql_total_time') / F('total_time'), output_field=FloatField())), ReportColumnFormat('Total calls', '{}', 'total_calls', 'total_calls'), ReportColumnFormat('Time per call', '{:.8f}', 'time_per_call', ExpressionWrapper(F('total_time') / F('total_calls'), output_field=FloatField())), ReportColumnFormat('Total time', '{:.4f}', 'total_time', 'total_time'), ] } class SpeedinfoSettings: def __init__(self, defaults=None): self.defaults = defaults or DEFAULTS def __getattr__(self, name): if name not in self.defaults: raise AttributeError('Invalid setting: "{}"'.format(name)) return getattr(settings, name, self.defaults.get(name)) speedinfo_settings = SpeedinfoSettings()
speedinfo/settings.py
from collections import namedtuple from django.conf import settings from django.db.models import ExpressionWrapper, F, FloatField, IntegerField ReportColumnFormat = namedtuple('ReportColumnFormat', ['name', 'format', 'attr_name', 'order_field']) DEFAULTS = { 'SPEEDINFO_TESTS': False, 'SPEEDINFO_CACHED_RESPONSE_ATTR_NAME': 'is_cached', 'SPEEDINFO_PROFILING_CONDITIONS': [ 'speedinfo.conditions.exclude_urls.ExcludeURLCondition', ], 'SPEEDINFO_EXCLUDE_URLS': [], 'SPEEDINFO_REPORT_COLUMNS': ( 'view_name', 'method', 'anon_calls_ratio', 'cache_hits_ratio', 'sql_count_per_call', 'sql_time_ratio', 'total_calls', 'time_per_call', 'total_time'), 'SPEEDINFO_REPORT_COLUMNS_FORMAT': [ ReportColumnFormat('View name', '{}', 'view_name', 'view_name'), ReportColumnFormat('HTTP method', '{}', 'method', 'method'), ReportColumnFormat('Anonymous calls', '{:.1f}%', 'anon_calls_ratio', ExpressionWrapper(100.0 * F('anon_calls') / F('total_calls'), output_field=FloatField())), ReportColumnFormat('Cache hits', '{:.1f}%', 'cache_hits_ratio', ExpressionWrapper(100.0 * F('cache_hits') / F('total_calls'), output_field=FloatField())), ReportColumnFormat('SQL queries per call', '{}', 'sql_count_per_call', ExpressionWrapper(F('sql_total_count') / F('total_calls'), output_field=IntegerField())), ReportColumnFormat('SQL time', '{:.1f}%', 'sql_time_ratio', ExpressionWrapper(100.0 * F('sql_total_time') / F('total_time'), output_field=FloatField())), ReportColumnFormat('Total calls', '{}', 'total_calls', 'total_calls'), ReportColumnFormat('Time per call', '{:.8f}', 'time_per_call', ExpressionWrapper(F('total_time') / F('total_calls'), output_field=FloatField())), ReportColumnFormat('Total time', '{:.4f}', 'total_time', 'total_time'), ] } class SpeedinfoSettings: def __init__(self, defaults=None): self.defaults = defaults or DEFAULTS def __getattr__(self, name): if name not in self.defaults: raise AttributeError('Invalid setting: "{}"'.format(name)) return getattr(settings, name, self.defaults.get(name)) speedinfo_settings = SpeedinfoSettings()
0.72952
0.084531
import os import uuid import tempfile from pathlib import Path import pytest from cachetools import TTLCache boto3 = pytest.importorskip('boto3') moto = pytest.importorskip('moto') @pytest.fixture(autouse=True) def override_aws_credentials(monkeypatch): with monkeypatch.context() as m: m.setenv('AWS_ACCESS_KEY_ID', 'FakeKey') m.setenv('AWS_SECRET_ACCESS_KEY', 'FakeSecretKey') m.setenv('AWS_SESSION_TOKEN', '<PASSWORD>') yield class Timer: def __init__(self, auto=False): self.auto = auto self.time = 0 def __call__(self): if self.auto: self.time += 1 return self.time def tick(self): self.time += 1 @pytest.fixture() def s3_db_factory(tmpdir): bucketname = str(uuid.uuid4()) def _s3_db_factory(keys, datasets=None): from terracotta import get_driver with tempfile.TemporaryDirectory() as tmpdir: dbfile = Path(tmpdir) / 'tc.sqlite' driver = get_driver(dbfile) driver.create(keys) if datasets: for keys, path in datasets.items(): driver.insert(keys, path) with open(dbfile, 'rb') as f: db_bytes = f.read() conn = boto3.resource('s3') conn.create_bucket(Bucket=bucketname) s3 = boto3.client('s3') s3.put_object(Bucket=bucketname, Key='tc.sqlite', Body=db_bytes) return f's3://{bucketname}/tc.sqlite' return _s3_db_factory @moto.mock_s3 def test_remote_database(s3_db_factory): keys = ('some', 'keys') dbpath = s3_db_factory(keys) from terracotta import get_driver driver = get_driver(dbpath) assert driver.key_names == keys def test_invalid_url(): from terracotta import get_driver driver = get_driver('foo', provider='sqlite-remote') with pytest.raises(ValueError): with driver.connect(): pass def test_nonexisting_url(): from terracotta import get_driver, exceptions driver = get_driver('s3://foo/db.sqlite') with pytest.raises(exceptions.InvalidDatabaseError): with driver.connect(): pass @moto.mock_s3 def test_remote_database_cache(s3_db_factory, raster_file, monkeypatch): keys = ('some', 'keys') dbpath = s3_db_factory(keys) from terracotta import get_driver driver = get_driver(dbpath) with monkeypatch.context() as m: # replace TTL cache timer by manual timer m.setattr(driver, '_checkdb_cache', TTLCache(maxsize=1, ttl=1, timer=Timer())) assert len(driver._checkdb_cache) == 0 with driver.connect(): assert driver.key_names == keys assert driver.get_datasets() == {} modification_date = os.path.getmtime(driver.path) s3_db_factory(keys, datasets={('some', 'value'): str(raster_file)}) # no change yet assert driver.get_datasets() == {} assert os.path.getmtime(driver.path) == modification_date # check if remote db is cached after one tick driver._checkdb_cache.timer.tick() assert len(driver._checkdb_cache) == 1 with driver.connect(): # db connection is cached; so still no change assert driver.get_datasets() == {} assert os.path.getmtime(driver.path) == modification_date # TTL cache is invalidated after second tick driver._checkdb_cache.timer.tick() assert len(driver._checkdb_cache) == 0 with driver.connect(): # now db is updated on reconnect assert list(driver.get_datasets().keys()) == [('some', 'value')] assert os.path.getmtime(driver.path) != modification_date @moto.mock_s3 def test_immutability(s3_db_factory, raster_file): keys = ('some', 'keys') dbpath = s3_db_factory(keys, datasets={('some', 'value'): str(raster_file)}) from terracotta import get_driver driver = get_driver(dbpath) with pytest.raises(NotImplementedError): driver.create(keys) with pytest.raises(NotImplementedError): driver.insert(('some', 'value'), str(raster_file)) with pytest.raises(NotImplementedError): driver.delete(('some', 'value')) @moto.mock_s3 def test_destructor(s3_db_factory, raster_file, capsys): keys = ('some', 'keys') dbpath = s3_db_factory(keys, datasets={('some', 'value'): str(raster_file)}) from terracotta import get_driver driver = get_driver(dbpath) assert os.path.isfile(driver.path) driver.__del__() assert not os.path.isfile(driver.path) captured = capsys.readouterr() assert 'Exception ignored' not in captured.err # re-create file to prevent actual destructor from failing with open(driver.path, 'w'): pass
tests/drivers/test_sqlite_remote.py
import os import uuid import tempfile from pathlib import Path import pytest from cachetools import TTLCache boto3 = pytest.importorskip('boto3') moto = pytest.importorskip('moto') @pytest.fixture(autouse=True) def override_aws_credentials(monkeypatch): with monkeypatch.context() as m: m.setenv('AWS_ACCESS_KEY_ID', 'FakeKey') m.setenv('AWS_SECRET_ACCESS_KEY', 'FakeSecretKey') m.setenv('AWS_SESSION_TOKEN', '<PASSWORD>') yield class Timer: def __init__(self, auto=False): self.auto = auto self.time = 0 def __call__(self): if self.auto: self.time += 1 return self.time def tick(self): self.time += 1 @pytest.fixture() def s3_db_factory(tmpdir): bucketname = str(uuid.uuid4()) def _s3_db_factory(keys, datasets=None): from terracotta import get_driver with tempfile.TemporaryDirectory() as tmpdir: dbfile = Path(tmpdir) / 'tc.sqlite' driver = get_driver(dbfile) driver.create(keys) if datasets: for keys, path in datasets.items(): driver.insert(keys, path) with open(dbfile, 'rb') as f: db_bytes = f.read() conn = boto3.resource('s3') conn.create_bucket(Bucket=bucketname) s3 = boto3.client('s3') s3.put_object(Bucket=bucketname, Key='tc.sqlite', Body=db_bytes) return f's3://{bucketname}/tc.sqlite' return _s3_db_factory @moto.mock_s3 def test_remote_database(s3_db_factory): keys = ('some', 'keys') dbpath = s3_db_factory(keys) from terracotta import get_driver driver = get_driver(dbpath) assert driver.key_names == keys def test_invalid_url(): from terracotta import get_driver driver = get_driver('foo', provider='sqlite-remote') with pytest.raises(ValueError): with driver.connect(): pass def test_nonexisting_url(): from terracotta import get_driver, exceptions driver = get_driver('s3://foo/db.sqlite') with pytest.raises(exceptions.InvalidDatabaseError): with driver.connect(): pass @moto.mock_s3 def test_remote_database_cache(s3_db_factory, raster_file, monkeypatch): keys = ('some', 'keys') dbpath = s3_db_factory(keys) from terracotta import get_driver driver = get_driver(dbpath) with monkeypatch.context() as m: # replace TTL cache timer by manual timer m.setattr(driver, '_checkdb_cache', TTLCache(maxsize=1, ttl=1, timer=Timer())) assert len(driver._checkdb_cache) == 0 with driver.connect(): assert driver.key_names == keys assert driver.get_datasets() == {} modification_date = os.path.getmtime(driver.path) s3_db_factory(keys, datasets={('some', 'value'): str(raster_file)}) # no change yet assert driver.get_datasets() == {} assert os.path.getmtime(driver.path) == modification_date # check if remote db is cached after one tick driver._checkdb_cache.timer.tick() assert len(driver._checkdb_cache) == 1 with driver.connect(): # db connection is cached; so still no change assert driver.get_datasets() == {} assert os.path.getmtime(driver.path) == modification_date # TTL cache is invalidated after second tick driver._checkdb_cache.timer.tick() assert len(driver._checkdb_cache) == 0 with driver.connect(): # now db is updated on reconnect assert list(driver.get_datasets().keys()) == [('some', 'value')] assert os.path.getmtime(driver.path) != modification_date @moto.mock_s3 def test_immutability(s3_db_factory, raster_file): keys = ('some', 'keys') dbpath = s3_db_factory(keys, datasets={('some', 'value'): str(raster_file)}) from terracotta import get_driver driver = get_driver(dbpath) with pytest.raises(NotImplementedError): driver.create(keys) with pytest.raises(NotImplementedError): driver.insert(('some', 'value'), str(raster_file)) with pytest.raises(NotImplementedError): driver.delete(('some', 'value')) @moto.mock_s3 def test_destructor(s3_db_factory, raster_file, capsys): keys = ('some', 'keys') dbpath = s3_db_factory(keys, datasets={('some', 'value'): str(raster_file)}) from terracotta import get_driver driver = get_driver(dbpath) assert os.path.isfile(driver.path) driver.__del__() assert not os.path.isfile(driver.path) captured = capsys.readouterr() assert 'Exception ignored' not in captured.err # re-create file to prevent actual destructor from failing with open(driver.path, 'w'): pass
0.410047
0.22396
"""Holds the zazu repo subcommand.""" import zazu.imports zazu.imports.lazy_import(locals(), [ 'click', 'functools', 'git', 'os', 'semantic_version', 'socket', 'zazu.config', 'zazu.git_helper', 'zazu.github_helper', 'zazu.util', ]) __author__ = '<NAME>' __copyright__ = 'Copyright 2016' @click.group() def repo(): """Manage repository.""" pass @repo.command() @zazu.config.pass_config def init(config): """Install git hooks to repo.""" config.check_repo() zazu.git_helper.install_git_hooks(config.repo_root) def complete_repo(ctx, args, incomplete): """Completion function that completes repos from SCM hosts.""" paths = [] scm_hosts = zazu.config.Config().scm_hosts() for host_name in scm_hosts: host = scm_hosts[host_name] try: for r in host.repos(): path = '/'.join([host_name, r.id]) if incomplete in path: paths.append(path) except IOError: zazu.util.warn('unable to connect to "{}" SCM host.'.format(host_name)) return sorted(paths) @repo.command() @click.argument('repository', autocompletion=complete_repo) @click.argument('destination', required=False) @click.option('--nohooks', is_flag=True, help='does not install git hooks in the cloned repo') @click.option('--nosubmodules', is_flag=True, help='does not update submodules') @zazu.config.pass_config def clone(config, repository, destination, nohooks, nosubmodules): """Clone and initialize a repo. Args: repository (str): name or url of the repository to clone. destination (str): path to clone the repo to. nohooks (bool): if True, git hooks are not installed. nosubmodules (bool): if True submodules are not initialized. """ if os.path.isdir(repository) or ':' in repository: repository_url = repository elif config.scm_hosts(): scm_repo = config.scm_host_repo(repository) if scm_repo is None: raise click.ClickException('Unable to find hosted SCM repo {}'.format(repository)) repository_url = scm_repo.ssh_url else: raise click.ClickException('Unable to clone {}'.format(repository)) if destination is None: destination = repository_url.rsplit('/', 1)[-1].replace('.git', '') click.echo('Cloning {} into {}'.format(repository_url, destination)) try: repo = git.Repo.clone_from(repository_url, destination) click.echo('Repository successfully cloned') if not nohooks: click.echo('Installing Git Hooks') zazu.git_helper.install_git_hooks(repo.working_dir) if not nosubmodules: click.echo('Updating all submodules') repo.submodule_update(init=True, recursive=True) except git.GitCommandError as err: raise click.ClickException(str(err)) @repo.command() @click.option('-r', '--remote', is_flag=True, help='Also clean up remote branches') @click.option('-b', '--target_branch', default='origin/master', help='Delete branches merged with this branch') @click.option('-y', '--yes', is_flag=True, help='Don\'t ask to before deleting branches') @zazu.config.pass_config def cleanup(config, remote, target_branch, yes): """Clean up merged/closed branches.""" config.check_repo() repo_obj = config.repo develop_branch_name = config.develop_branch_name() try: repo_obj.heads[develop_branch_name].checkout() except IndexError: raise click.ClickException('unable to checkout "{}"'.format(develop_branch_name)) try: issue_tracker = config.issue_tracker() except click.ClickException: issue_tracker = None closed_branches = set() protected_branches = config.protected_branches() if remote: repo_obj.git.fetch('--prune') remote_branch_names = {b.name.replace('origin/', '') for b in repo_obj.remotes.origin.refs} - protected_branches if issue_tracker is not None: closed_branches = get_closed_branches(issue_tracker, remote_branch_names) merged_remote_branches = zazu.git_helper.merged_branches(repo_obj, target_branch, remote=True) merged_remote_branches = {b.replace('origin/', '') for b in merged_remote_branches} empty_branches = {b for b in remote_branch_names if branch_is_empty(repo_obj, 'origin/{}'.format(b), 'origin/{}'.format(develop_branch_name))} branches_to_delete = (merged_remote_branches | closed_branches | empty_branches) - protected_branches if branches_to_delete: confirmation = 'These remote branches will be deleted: {} Proceed?'.format(zazu.util.pprint_list(branches_to_delete)) if yes or click.confirm(confirmation): repo_obj.git.push('-df', 'origin', *branches_to_delete) merged_branches = zazu.git_helper.merged_branches(repo_obj, target_branch) - protected_branches local_branches = {b.name for b in repo_obj.heads} - protected_branches if issue_tracker is not None: branches_to_check = local_branches - closed_branches closed_branches |= get_closed_branches(issue_tracker, branches_to_check) empty_branches = {b for b in local_branches if branch_is_empty(repo_obj, b, develop_branch_name)} branches_to_delete = ((closed_branches & local_branches) | merged_branches | empty_branches) - protected_branches if branches_to_delete: confirmation = 'These local branches will be deleted: {}\n Proceed?'.format(zazu.util.pprint_list(branches_to_delete)) if yes or click.confirm(confirmation): repo_obj.git.branch('-D', *branches_to_delete) def tag_to_version(tag): """Convert a git tag into a semantic version string. i.e. R4.1 becomes 4.1.0. A leading 'r' or 'v' is optional on the tag. """ components = [] if tag is not None: if tag.lower().startswith('r') or tag.lower().startswith('v'): tag = tag[1:] components = tag.split('.') major = '0' minor = '0' patch = '0' try: major = components[0] minor = components[1] patch = components[2] except IndexError: pass return '.'.join([major, minor, patch]) def make_semver(repo_root, prerelease=None): """Parse SCM info and creates a semantic version.""" branch_name, sha, tags = parse_describe(repo_root) if tags: # There are git tags to consider. Parse them all then choose the one that is latest (sorted by semver rules). return sorted([make_version_number(branch_name, prerelease, tag, sha) for tag in tags])[-1] return make_version_number(branch_name, prerelease, None, sha) def parse_describe(repo_root): """Parse the results of git describe into branch name, sha, and tags.""" repo = git.Repo(repo_root) try: sha = 'g{}{}'.format(repo.git.rev_parse('HEAD')[:7], '-dirty' if repo.git.status(['--porcelain']) else '') branch_name = repo.git.rev_parse(['--abbrev-ref', 'HEAD']).strip() # Get the list of tags that point to HEAD tag_result = repo.git.tag(['--points-at', 'HEAD']) tags = [t for t in tag_result.strip().split('\n') if t] except git.GitCommandError as e: raise click.ClickException(str(e)) return branch_name, sha, tags def sanitize_branch_name(branch_name): """Replace punctuation that cannot be in semantic version from a branch name with dashes.""" return branch_name.replace('/', '-').replace('_', '-') def make_version_number(branch_name, prerelease, tag, sha): """Convert repo metadata and build version into a semantic version.""" branch_name_sanitized = sanitize_branch_name(branch_name) build_info = ['sha', sha, 'branch', branch_name_sanitized] prerelease_list = [str(prerelease)] if prerelease is not None else ['0'] if tag is not None: version = tag_to_version(tag) if prerelease is not None: raise click.ClickException('Pre-release specifier is not allowed on tagged commits') prerelease_list = [] elif branch_name.startswith('release/') or branch_name.startswith('hotfix/'): version = tag_to_version(branch_name.split('/', 1)[1]) else: version = '0.0.0' semver = semantic_version.Version(version) semver.prerelease = prerelease_list semver.build = build_info return semver def pep440_from_semver(semver): """Convert semantic version to PEP440 compliant version.""" segment = '' if semver.prerelease: segment = '.dev{}'.format('.'.join(semver.prerelease)) local_version = '.'.join(semver.build) local_version = local_version.replace('-', '.') version_str = '{}.{}.{}{}'.format(semver.major, semver.minor, semver.patch, segment) # Include the local version if we are not a true release if local_version and semver.prerelease: version_str = '{}+{}'.format(version_str, local_version) return version_str @repo.command() @click.option('--pep440', is_flag=True, help='Format the output as PEP 440 compliant') @click.option('--prerelease', type=int, help='Pre-release number (invalid for tagged commits)') @zazu.config.pass_config def describe(config, pep440, prerelease): """Get version string describing current commit.""" config.check_repo() version = make_semver(config.repo_root, prerelease) if pep440: version = pep440_from_semver(version) click.echo(str(version)) def descriptors_from_branches(branches, require_type=False): """Generate IssueDescriptors from a branch names.""" for b in branches: try: yield zazu.dev.commands.make_issue_descriptor(b, require_type) except click.ClickException: pass def get_closed_branches(issue_tracker, branches): """Get descriptors of branches that refer to closed branches.""" def descriptor_if_closed(descriptor): return descriptor if ticket_is_closed(issue_tracker, descriptor) else None work = [functools.partial(descriptor_if_closed, d) for d in descriptors_from_branches(branches)] closed_tickets = zazu.util.dispatch(work) return {t.get_branch_name() for t in closed_tickets if t is not None} def ticket_is_closed(issue_tracker, descriptor): """Determine if a ticket is closed or not, defaults to False in case the ticket isn't found by the issue tracker.""" try: return issue_tracker.issue(descriptor.id).closed except zazu.issue_tracker.IssueTrackerError: return False def branch_is_empty(repo, branch, base_branch): """Return True if branch has no commits newer than base_branch.""" try: return int(repo.git.rev_list('--count', branch, '^{}'.format(base_branch))) == 0 except git.GitCommandError: return False
zazu/repo/commands.py
"""Holds the zazu repo subcommand.""" import zazu.imports zazu.imports.lazy_import(locals(), [ 'click', 'functools', 'git', 'os', 'semantic_version', 'socket', 'zazu.config', 'zazu.git_helper', 'zazu.github_helper', 'zazu.util', ]) __author__ = '<NAME>' __copyright__ = 'Copyright 2016' @click.group() def repo(): """Manage repository.""" pass @repo.command() @zazu.config.pass_config def init(config): """Install git hooks to repo.""" config.check_repo() zazu.git_helper.install_git_hooks(config.repo_root) def complete_repo(ctx, args, incomplete): """Completion function that completes repos from SCM hosts.""" paths = [] scm_hosts = zazu.config.Config().scm_hosts() for host_name in scm_hosts: host = scm_hosts[host_name] try: for r in host.repos(): path = '/'.join([host_name, r.id]) if incomplete in path: paths.append(path) except IOError: zazu.util.warn('unable to connect to "{}" SCM host.'.format(host_name)) return sorted(paths) @repo.command() @click.argument('repository', autocompletion=complete_repo) @click.argument('destination', required=False) @click.option('--nohooks', is_flag=True, help='does not install git hooks in the cloned repo') @click.option('--nosubmodules', is_flag=True, help='does not update submodules') @zazu.config.pass_config def clone(config, repository, destination, nohooks, nosubmodules): """Clone and initialize a repo. Args: repository (str): name or url of the repository to clone. destination (str): path to clone the repo to. nohooks (bool): if True, git hooks are not installed. nosubmodules (bool): if True submodules are not initialized. """ if os.path.isdir(repository) or ':' in repository: repository_url = repository elif config.scm_hosts(): scm_repo = config.scm_host_repo(repository) if scm_repo is None: raise click.ClickException('Unable to find hosted SCM repo {}'.format(repository)) repository_url = scm_repo.ssh_url else: raise click.ClickException('Unable to clone {}'.format(repository)) if destination is None: destination = repository_url.rsplit('/', 1)[-1].replace('.git', '') click.echo('Cloning {} into {}'.format(repository_url, destination)) try: repo = git.Repo.clone_from(repository_url, destination) click.echo('Repository successfully cloned') if not nohooks: click.echo('Installing Git Hooks') zazu.git_helper.install_git_hooks(repo.working_dir) if not nosubmodules: click.echo('Updating all submodules') repo.submodule_update(init=True, recursive=True) except git.GitCommandError as err: raise click.ClickException(str(err)) @repo.command() @click.option('-r', '--remote', is_flag=True, help='Also clean up remote branches') @click.option('-b', '--target_branch', default='origin/master', help='Delete branches merged with this branch') @click.option('-y', '--yes', is_flag=True, help='Don\'t ask to before deleting branches') @zazu.config.pass_config def cleanup(config, remote, target_branch, yes): """Clean up merged/closed branches.""" config.check_repo() repo_obj = config.repo develop_branch_name = config.develop_branch_name() try: repo_obj.heads[develop_branch_name].checkout() except IndexError: raise click.ClickException('unable to checkout "{}"'.format(develop_branch_name)) try: issue_tracker = config.issue_tracker() except click.ClickException: issue_tracker = None closed_branches = set() protected_branches = config.protected_branches() if remote: repo_obj.git.fetch('--prune') remote_branch_names = {b.name.replace('origin/', '') for b in repo_obj.remotes.origin.refs} - protected_branches if issue_tracker is not None: closed_branches = get_closed_branches(issue_tracker, remote_branch_names) merged_remote_branches = zazu.git_helper.merged_branches(repo_obj, target_branch, remote=True) merged_remote_branches = {b.replace('origin/', '') for b in merged_remote_branches} empty_branches = {b for b in remote_branch_names if branch_is_empty(repo_obj, 'origin/{}'.format(b), 'origin/{}'.format(develop_branch_name))} branches_to_delete = (merged_remote_branches | closed_branches | empty_branches) - protected_branches if branches_to_delete: confirmation = 'These remote branches will be deleted: {} Proceed?'.format(zazu.util.pprint_list(branches_to_delete)) if yes or click.confirm(confirmation): repo_obj.git.push('-df', 'origin', *branches_to_delete) merged_branches = zazu.git_helper.merged_branches(repo_obj, target_branch) - protected_branches local_branches = {b.name for b in repo_obj.heads} - protected_branches if issue_tracker is not None: branches_to_check = local_branches - closed_branches closed_branches |= get_closed_branches(issue_tracker, branches_to_check) empty_branches = {b for b in local_branches if branch_is_empty(repo_obj, b, develop_branch_name)} branches_to_delete = ((closed_branches & local_branches) | merged_branches | empty_branches) - protected_branches if branches_to_delete: confirmation = 'These local branches will be deleted: {}\n Proceed?'.format(zazu.util.pprint_list(branches_to_delete)) if yes or click.confirm(confirmation): repo_obj.git.branch('-D', *branches_to_delete) def tag_to_version(tag): """Convert a git tag into a semantic version string. i.e. R4.1 becomes 4.1.0. A leading 'r' or 'v' is optional on the tag. """ components = [] if tag is not None: if tag.lower().startswith('r') or tag.lower().startswith('v'): tag = tag[1:] components = tag.split('.') major = '0' minor = '0' patch = '0' try: major = components[0] minor = components[1] patch = components[2] except IndexError: pass return '.'.join([major, minor, patch]) def make_semver(repo_root, prerelease=None): """Parse SCM info and creates a semantic version.""" branch_name, sha, tags = parse_describe(repo_root) if tags: # There are git tags to consider. Parse them all then choose the one that is latest (sorted by semver rules). return sorted([make_version_number(branch_name, prerelease, tag, sha) for tag in tags])[-1] return make_version_number(branch_name, prerelease, None, sha) def parse_describe(repo_root): """Parse the results of git describe into branch name, sha, and tags.""" repo = git.Repo(repo_root) try: sha = 'g{}{}'.format(repo.git.rev_parse('HEAD')[:7], '-dirty' if repo.git.status(['--porcelain']) else '') branch_name = repo.git.rev_parse(['--abbrev-ref', 'HEAD']).strip() # Get the list of tags that point to HEAD tag_result = repo.git.tag(['--points-at', 'HEAD']) tags = [t for t in tag_result.strip().split('\n') if t] except git.GitCommandError as e: raise click.ClickException(str(e)) return branch_name, sha, tags def sanitize_branch_name(branch_name): """Replace punctuation that cannot be in semantic version from a branch name with dashes.""" return branch_name.replace('/', '-').replace('_', '-') def make_version_number(branch_name, prerelease, tag, sha): """Convert repo metadata and build version into a semantic version.""" branch_name_sanitized = sanitize_branch_name(branch_name) build_info = ['sha', sha, 'branch', branch_name_sanitized] prerelease_list = [str(prerelease)] if prerelease is not None else ['0'] if tag is not None: version = tag_to_version(tag) if prerelease is not None: raise click.ClickException('Pre-release specifier is not allowed on tagged commits') prerelease_list = [] elif branch_name.startswith('release/') or branch_name.startswith('hotfix/'): version = tag_to_version(branch_name.split('/', 1)[1]) else: version = '0.0.0' semver = semantic_version.Version(version) semver.prerelease = prerelease_list semver.build = build_info return semver def pep440_from_semver(semver): """Convert semantic version to PEP440 compliant version.""" segment = '' if semver.prerelease: segment = '.dev{}'.format('.'.join(semver.prerelease)) local_version = '.'.join(semver.build) local_version = local_version.replace('-', '.') version_str = '{}.{}.{}{}'.format(semver.major, semver.minor, semver.patch, segment) # Include the local version if we are not a true release if local_version and semver.prerelease: version_str = '{}+{}'.format(version_str, local_version) return version_str @repo.command() @click.option('--pep440', is_flag=True, help='Format the output as PEP 440 compliant') @click.option('--prerelease', type=int, help='Pre-release number (invalid for tagged commits)') @zazu.config.pass_config def describe(config, pep440, prerelease): """Get version string describing current commit.""" config.check_repo() version = make_semver(config.repo_root, prerelease) if pep440: version = pep440_from_semver(version) click.echo(str(version)) def descriptors_from_branches(branches, require_type=False): """Generate IssueDescriptors from a branch names.""" for b in branches: try: yield zazu.dev.commands.make_issue_descriptor(b, require_type) except click.ClickException: pass def get_closed_branches(issue_tracker, branches): """Get descriptors of branches that refer to closed branches.""" def descriptor_if_closed(descriptor): return descriptor if ticket_is_closed(issue_tracker, descriptor) else None work = [functools.partial(descriptor_if_closed, d) for d in descriptors_from_branches(branches)] closed_tickets = zazu.util.dispatch(work) return {t.get_branch_name() for t in closed_tickets if t is not None} def ticket_is_closed(issue_tracker, descriptor): """Determine if a ticket is closed or not, defaults to False in case the ticket isn't found by the issue tracker.""" try: return issue_tracker.issue(descriptor.id).closed except zazu.issue_tracker.IssueTrackerError: return False def branch_is_empty(repo, branch, base_branch): """Return True if branch has no commits newer than base_branch.""" try: return int(repo.git.rev_list('--count', branch, '^{}'.format(base_branch))) == 0 except git.GitCommandError: return False
0.625896
0.143668
import math class QueueNode: def __init__(self, priority, data=None): assert type(priority) is int and priority >= 0 self.priority = priority self.data = data def __repr__(self): return str((self.priority, self.data)) class PriorityQueue: def __init__(self, capacity=100): self._capacity = capacity self._q = [] self._length = 0 def enqueue(self, priority, data=None): if self._length >= self._capacity: return False new_node = QueueNode(priority, data) self._q.append(new_node) self._length += 1 # update queue nn = self._length - 1 while nn > 0: p = (nn - 1) // 2 if self._q[nn].priority < self._q[p].priority: self._q[nn], self._q[p] = self._q[p], self._q[nn] nn = p else: break return True def dequeue(self): if self._length <= 0: raise Exception('the queue is empty....') self._q[0], self._q[-1] = self._q[-1], self._q[0] ret = self._q.pop() self._length -= 1 if self._length > 1: # update queue lp = (self._length - 2) // 2 idx = 0 while idx <= lp: lc = 2 * idx + 1 rc = lc + 1 if rc <= self._length - 1: tmp = lc if self._q[lc].priority < self._q[rc].priority else rc else: tmp = lc if self._q[tmp].priority < self._q[idx].priority: self._q[tmp], self._q[idx] = self._q[idx], self._q[tmp] idx = tmp else: break return ret def get_length(self): return self._length @staticmethod def _draw_heap(data): """ 格式化打印 :param data: :return: """ length = len(data) if length == 0: return 'empty' ret = '' for i, n in enumerate(data): ret += str(n) # 每行最后一个换行 if i == 2 ** int(math.log(i + 1, 2) + 1) - 2 or i == len(data) - 1: ret += '\n' else: ret += ', ' return ret def __repr__(self): def formater(node): assert type(node) is QueueNode return node.priority, node.data data = list(map(formater, self._q)) return self._draw_heap(data) if __name__ == '__main__': pq = PriorityQueue() pq.enqueue(5, 'Watch TV') pq.enqueue(2, 'Learning') pq.enqueue(10, 'Go Sleep') pq.enqueue(0, 'Go Home') pq.enqueue(7, 'Mobile Games') print(pq) while pq.get_length() > 0: print(pq.dequeue())
python/28_binary_heap/priority_queue.py
import math class QueueNode: def __init__(self, priority, data=None): assert type(priority) is int and priority >= 0 self.priority = priority self.data = data def __repr__(self): return str((self.priority, self.data)) class PriorityQueue: def __init__(self, capacity=100): self._capacity = capacity self._q = [] self._length = 0 def enqueue(self, priority, data=None): if self._length >= self._capacity: return False new_node = QueueNode(priority, data) self._q.append(new_node) self._length += 1 # update queue nn = self._length - 1 while nn > 0: p = (nn - 1) // 2 if self._q[nn].priority < self._q[p].priority: self._q[nn], self._q[p] = self._q[p], self._q[nn] nn = p else: break return True def dequeue(self): if self._length <= 0: raise Exception('the queue is empty....') self._q[0], self._q[-1] = self._q[-1], self._q[0] ret = self._q.pop() self._length -= 1 if self._length > 1: # update queue lp = (self._length - 2) // 2 idx = 0 while idx <= lp: lc = 2 * idx + 1 rc = lc + 1 if rc <= self._length - 1: tmp = lc if self._q[lc].priority < self._q[rc].priority else rc else: tmp = lc if self._q[tmp].priority < self._q[idx].priority: self._q[tmp], self._q[idx] = self._q[idx], self._q[tmp] idx = tmp else: break return ret def get_length(self): return self._length @staticmethod def _draw_heap(data): """ 格式化打印 :param data: :return: """ length = len(data) if length == 0: return 'empty' ret = '' for i, n in enumerate(data): ret += str(n) # 每行最后一个换行 if i == 2 ** int(math.log(i + 1, 2) + 1) - 2 or i == len(data) - 1: ret += '\n' else: ret += ', ' return ret def __repr__(self): def formater(node): assert type(node) is QueueNode return node.priority, node.data data = list(map(formater, self._q)) return self._draw_heap(data) if __name__ == '__main__': pq = PriorityQueue() pq.enqueue(5, 'Watch TV') pq.enqueue(2, 'Learning') pq.enqueue(10, 'Go Sleep') pq.enqueue(0, 'Go Home') pq.enqueue(7, 'Mobile Games') print(pq) while pq.get_length() > 0: print(pq.dequeue())
0.575469
0.376222
from datetime import datetime from django.core.management.base import BaseCommand, CommandError from legislators.models import State, CongressPerson, ExternalId, Term from legislators.importer import load_legislators_current, load_legislators_past date_format = '%Y-%m-%d' def make_person(bio, name): person = CongressPerson(first_name=name['first'], last_name=name['last']) if 'official_full' in name: person.official_full = name['official_full'] if 'middle' in name: person.middle_name = name['middle'] if 'suffix' in name: person.suffix = name['suffix'] if 'nickname' in name: person.nickname = name['nickname'] person.gender = bio['gender'] if 'religion' in bio: person.religion = bio['religion'] if 'birthday' in bio: person.birthday = bio['birthday'] person.save() return person def make_term(person, term): defaults = {} state = State.objects.get(short=term['state']) start = datetime.strptime(term['start'], date_format) end = datetime.strptime(term['end'], date_format) for p in ['party', 'state_rank', 'district', 'caucus', 'address', 'office', 'phone', 'fax', 'contact_form', 'rss_url', 'url']: if p in term: defaults[p] = term[p] if 'class' in term: defaults['election_class'] = term['class'] obj, created = person.terms.update_or_create( state=state, start_date=start, end_date=end, type=term['type'], defaults=defaults) def load_data(data, out): for rep in data: defaults = {} defaults.update(rep['name']) defaults.update(rep['bio']) print(rep['name']) obj, created = CongressPerson.objects.update_or_create( bioguide_id=rep['id']['bioguide'], defaults=defaults, ) for k, v in rep['id'].items(): obj.external_ids.update_or_create(type=k, value=v) for term in rep['terms']: make_term(obj, term) class Command(BaseCommand): help = 'Loads congress yaml files' def handle(self, *args, **options): data = load_legislators_current() self.stdout.write("Got data for current legislators") load_data(data, self.stdout) data = load_legislators_past() self.stdout.write("Got data for past legislators") load_data(data, self.stdout)
capitolweb/legislators/management/commands/loadcongress.py
from datetime import datetime from django.core.management.base import BaseCommand, CommandError from legislators.models import State, CongressPerson, ExternalId, Term from legislators.importer import load_legislators_current, load_legislators_past date_format = '%Y-%m-%d' def make_person(bio, name): person = CongressPerson(first_name=name['first'], last_name=name['last']) if 'official_full' in name: person.official_full = name['official_full'] if 'middle' in name: person.middle_name = name['middle'] if 'suffix' in name: person.suffix = name['suffix'] if 'nickname' in name: person.nickname = name['nickname'] person.gender = bio['gender'] if 'religion' in bio: person.religion = bio['religion'] if 'birthday' in bio: person.birthday = bio['birthday'] person.save() return person def make_term(person, term): defaults = {} state = State.objects.get(short=term['state']) start = datetime.strptime(term['start'], date_format) end = datetime.strptime(term['end'], date_format) for p in ['party', 'state_rank', 'district', 'caucus', 'address', 'office', 'phone', 'fax', 'contact_form', 'rss_url', 'url']: if p in term: defaults[p] = term[p] if 'class' in term: defaults['election_class'] = term['class'] obj, created = person.terms.update_or_create( state=state, start_date=start, end_date=end, type=term['type'], defaults=defaults) def load_data(data, out): for rep in data: defaults = {} defaults.update(rep['name']) defaults.update(rep['bio']) print(rep['name']) obj, created = CongressPerson.objects.update_or_create( bioguide_id=rep['id']['bioguide'], defaults=defaults, ) for k, v in rep['id'].items(): obj.external_ids.update_or_create(type=k, value=v) for term in rep['terms']: make_term(obj, term) class Command(BaseCommand): help = 'Loads congress yaml files' def handle(self, *args, **options): data = load_legislators_current() self.stdout.write("Got data for current legislators") load_data(data, self.stdout) data = load_legislators_past() self.stdout.write("Got data for past legislators") load_data(data, self.stdout)
0.370567
0.10725
import argparse import subprocess from pathlib import Path import os import fcntl import itertools import sys MODELS = { "south-onlp": ["goldstone-platform", "goldstone-component-connection"], "south-sonic": [ "goldstone-interfaces", "goldstone-sonic", "goldstone-vlan", "goldstone-uplink-failure-detection", "goldstone-ip", "goldstone-portchannel", "goldstone-component-connection", ], "south-tai": ["goldstone-transponder", "goldstone-component-connection"], "south-gearbox": [ "goldstone-interfaces", "goldstone-gearbox", "goldstone-component-connection", "goldstone-static-macsec", "goldstone-synce", "goldstone-dpll", ], "south-dpll": ["goldstone-dpll"], "south-system": [ "goldstone-aaa", "goldstone-mgmt-interfaces", "goldstone-ip", "goldstone-system", "goldstone-routing", ], "xlate-oc": [ "iana-if-type", "interfaces/openconfig-interfaces", "platform/openconfig-platform-types", "platform/openconfig-platform-port", "platform/openconfig-platform", ], } DEFAULT_YANG_DIR = "/var/lib/goldstone/yang" DEFAULT_PLATFORM_YANG_DIR = "/var/lib/goldstone/device/current/yang" def install_model(model_name: str, search_dirs: list[str] = []) -> None: with open("/run/gs-yang-lock", "wt") as f: try: fcntl.flock(f, fcntl.LOCK_EX) s = "--search-dirs " + ":".join(search_dirs) model = list( itertools.chain.from_iterable( [Path(d).rglob(f"{model_name}.yang") for d in search_dirs] ) ) if len(model) == 0: raise Exception(f"model {model_name} not found") elif len(model) > 1: raise Exception(f"multiple models named {model_name} found") model = model[0] print(model, search_dirs) command = f"sysrepoctl {s} --install {model}" print(f"run: {command}") subprocess.run(command.split(" "), stderr=subprocess.STDOUT) name, _ = os.path.splitext(os.path.basename(model)) command = f"sysrepoctl -c {name} -g gsmgmt -p 664" print(f"run: {command}") subprocess.run(command.split(" "), stderr=subprocess.STDOUT) finally: fcntl.flock(f, fcntl.LOCK_UN) def install_platform(yang_dir): if yang_dir == None: yang_dir = DEFAULT_PLATFORM_YANG_DIR path = Path(yang_dir) for m in path.glob("*.yang"): install_model(m, [yang_dir]) def install(name, yang_dir): if yang_dir == None: yang_dir = [DEFAULT_YANG_DIR] for model in MODELS[name]: install_model(model, yang_dir) def lint(daemons, search_dirs: list[str] = []): if not search_dirs: search_dirs = [DEFAULT_YANG_DIR, "/usr/local/share/yang/modules/ietf"] models = [] for model_name in set(itertools.chain.from_iterable(MODELS[d] for d in daemons)): model = list( itertools.chain.from_iterable( [Path(d).rglob(f"{model_name}.yang") for d in search_dirs] ) ) if len(model) == 0: raise Exception(f"model {model_name} not found") elif len(model) > 1: raise Exception(f"multiple models named {model_name} found") models.append(str(model[0])) path = "--path=" + ":".join(search_dirs) command = f"pyang {path} {' '.join(models)}" print(f"run: {command}") subprocess.run(command.split(" "), stderr=subprocess.STDOUT) def main(): parser = argparse.ArgumentParser() parser.add_argument("--install", nargs="+") parser.add_argument("--install-platform", action="store_true") parser.add_argument("--search-dirs", nargs="+") parser.add_argument("--lint", nargs="+") args = parser.parse_args() if args.install_platform: install_platform(args.search_dirs) if args.install: daemons = args.install choices = MODELS.keys() if not all(d in choices for d in daemons): print(f"choose from {', '.join(list(choices))}") sys.exit(1) for d in daemons: install(d, args.search_dirs) if args.lint: daemons = args.lint choices = MODELS.keys() if not all(d in choices for d in daemons): print(f"choose from {', '.join(list(choices))}") sys.exit(1) lint(daemons, args.search_dirs) if __name__ == "__main__": main()
scripts/gs-yang.py
import argparse import subprocess from pathlib import Path import os import fcntl import itertools import sys MODELS = { "south-onlp": ["goldstone-platform", "goldstone-component-connection"], "south-sonic": [ "goldstone-interfaces", "goldstone-sonic", "goldstone-vlan", "goldstone-uplink-failure-detection", "goldstone-ip", "goldstone-portchannel", "goldstone-component-connection", ], "south-tai": ["goldstone-transponder", "goldstone-component-connection"], "south-gearbox": [ "goldstone-interfaces", "goldstone-gearbox", "goldstone-component-connection", "goldstone-static-macsec", "goldstone-synce", "goldstone-dpll", ], "south-dpll": ["goldstone-dpll"], "south-system": [ "goldstone-aaa", "goldstone-mgmt-interfaces", "goldstone-ip", "goldstone-system", "goldstone-routing", ], "xlate-oc": [ "iana-if-type", "interfaces/openconfig-interfaces", "platform/openconfig-platform-types", "platform/openconfig-platform-port", "platform/openconfig-platform", ], } DEFAULT_YANG_DIR = "/var/lib/goldstone/yang" DEFAULT_PLATFORM_YANG_DIR = "/var/lib/goldstone/device/current/yang" def install_model(model_name: str, search_dirs: list[str] = []) -> None: with open("/run/gs-yang-lock", "wt") as f: try: fcntl.flock(f, fcntl.LOCK_EX) s = "--search-dirs " + ":".join(search_dirs) model = list( itertools.chain.from_iterable( [Path(d).rglob(f"{model_name}.yang") for d in search_dirs] ) ) if len(model) == 0: raise Exception(f"model {model_name} not found") elif len(model) > 1: raise Exception(f"multiple models named {model_name} found") model = model[0] print(model, search_dirs) command = f"sysrepoctl {s} --install {model}" print(f"run: {command}") subprocess.run(command.split(" "), stderr=subprocess.STDOUT) name, _ = os.path.splitext(os.path.basename(model)) command = f"sysrepoctl -c {name} -g gsmgmt -p 664" print(f"run: {command}") subprocess.run(command.split(" "), stderr=subprocess.STDOUT) finally: fcntl.flock(f, fcntl.LOCK_UN) def install_platform(yang_dir): if yang_dir == None: yang_dir = DEFAULT_PLATFORM_YANG_DIR path = Path(yang_dir) for m in path.glob("*.yang"): install_model(m, [yang_dir]) def install(name, yang_dir): if yang_dir == None: yang_dir = [DEFAULT_YANG_DIR] for model in MODELS[name]: install_model(model, yang_dir) def lint(daemons, search_dirs: list[str] = []): if not search_dirs: search_dirs = [DEFAULT_YANG_DIR, "/usr/local/share/yang/modules/ietf"] models = [] for model_name in set(itertools.chain.from_iterable(MODELS[d] for d in daemons)): model = list( itertools.chain.from_iterable( [Path(d).rglob(f"{model_name}.yang") for d in search_dirs] ) ) if len(model) == 0: raise Exception(f"model {model_name} not found") elif len(model) > 1: raise Exception(f"multiple models named {model_name} found") models.append(str(model[0])) path = "--path=" + ":".join(search_dirs) command = f"pyang {path} {' '.join(models)}" print(f"run: {command}") subprocess.run(command.split(" "), stderr=subprocess.STDOUT) def main(): parser = argparse.ArgumentParser() parser.add_argument("--install", nargs="+") parser.add_argument("--install-platform", action="store_true") parser.add_argument("--search-dirs", nargs="+") parser.add_argument("--lint", nargs="+") args = parser.parse_args() if args.install_platform: install_platform(args.search_dirs) if args.install: daemons = args.install choices = MODELS.keys() if not all(d in choices for d in daemons): print(f"choose from {', '.join(list(choices))}") sys.exit(1) for d in daemons: install(d, args.search_dirs) if args.lint: daemons = args.lint choices = MODELS.keys() if not all(d in choices for d in daemons): print(f"choose from {', '.join(list(choices))}") sys.exit(1) lint(daemons, args.search_dirs) if __name__ == "__main__": main()
0.180107
0.119382
import math import pickle import numpy as np from helper.utils import logger from tasks import register_task from tasks.base_task import BaseTask from dataclass.configs import BaseDataClass from dataclass.choices import BODY_CHOICES from dataclasses import dataclass,field from typing import Optional from helper.utils import compress_datatype,check_var @dataclass class BodyConfig(BaseDataClass): option: Optional[BODY_CHOICES] = field(default='extra',metadata={'help':'the set of data to build'}) task: str = field(default='build_body') def check_name(dc,key): if key in dc: value = dc[key] else: raise ValueError(f'{key} must be input') return value @register_task('build_body',dataclass=BodyConfig) class BuildBody(BaseTask): def __init__(self, args, train, test, model, arch, **kwargs): self.args = args self.train = train[:,1:-1] self.test = test[:,:-1] self.arch = arch self.columns = ["resource", "manager", "role1", "role2", "department", "title", "family_desc", "family"] dictionary_train = check_name(kwargs,'pivottable_train') dictionary_test = check_name(kwargs,'pivottable_test') dictionary = check_name(kwargs,'pivottable') self.dictionary_train = dictionary_train self.dictionary_test = dictionary_test self.dictionary = dictionary def gen_feature(self,data,feature_list): features = [] for row in data: features.append([]) for j in range(len(self.columns)): for func in feature_list: features[-1].append(func(self.dictionary[j][row[j]],row,j)) features = np.array(features) return features def create_features(self): if self.args.option == 'extra': def log_result(x,row,j): v = x[self.columns[0]].get(row[0],0) if v > 0: return math.log(v) else: return 0 feature_list = [ lambda x,row,j: x[self.columns[0]].get(row[0],0) if j > 0 else 0, lambda x,row,j: x[self.columns[1]].get(row[1],0) if j > 1 else 0, lambda x,row,j: x[self.columns[2]].get(row[2],0) if j > 2 else 0, lambda x,row,j: x[self.columns[3]].get(row[3],0) if j > 3 else 0, lambda x,row,j: x[self.columns[4]].get(row[4],0) if j > 4 else 0, lambda x,row,j: x[self.columns[5]].get(row[5],0) if j > 5 else 0, lambda x,row,j: x[self.columns[6]].get(row[6],0) if j > 6 else 0, lambda x,row,j: x[self.columns[7]].get(row[7],0) if j > 7 else 0, lambda x,row,j: x[self.columns[0]].get(row[0],0)**2 if j in range(7) else 0, log_result] elif self.args.option == 'tree': feature_list = [lambda x,row,j: x[self.columns[0]].get(row[0],0), lambda x,row,j: x[self.columns[1]].get(row[1],0), lambda x,row,j: x[self.columns[2]].get(row[2],0), lambda x,row,j: x[self.columns[3]].get(row[3],0), lambda x,row,j: x[self.columns[4]].get(row[4],0), lambda x,row,j: x[self.columns[5]].get(row[5],0), lambda x,row,j: x[self.columns[6]].get(row[6],0), lambda x,row,j: x[self.columns[7]].get(row[7],0)] elif self.args.option == 'meta': feature_list = [lambda x,row,j: self.dictionary_train[j].get(row[j],{}).get('total',0)] else: feature_list = [lambda x,row,j: x[self.columns[0]].get(row[0],0) / x['total'], lambda x,row,j: x[self.columns[1]].get(row[1],1) / x['total'], lambda x,row,j: x[self.columns[2]].get(row[2],2) / x['total'], lambda x,row,j: x[self.columns[3]].get(row[3],3) / x['total'], lambda x,row,j: x[self.columns[4]].get(row[4],4) / x['total'], lambda x,row,j: x[self.columns[5]].get(row[5],5) / x['total'], lambda x,row,j: x[self.columns[6]].get(row[6],6) / x['total'], lambda x,row,j: x[self.columns[7]].get(row[7],7) / x['total']] logger.info(f'building dataset with option:{self.args.option}') feature_train = self.gen_feature(self.train,feature_list) feature_test = self.gen_feature(self.test,feature_list) feature_train = compress_datatype(feature_train) feature_test = compress_datatype(feature_test) feature_train,feature_test = check_var(feature_train,feature_test) filename = self.args.option with open(f'interim_data_store/{filename}_data.pkl','wb') as f: pickle.dump((feature_train,feature_test),f) logger.info(f'saving {filename} data at interim_data_store') return feature_train,feature_test #%%
tasks/body.py
import math import pickle import numpy as np from helper.utils import logger from tasks import register_task from tasks.base_task import BaseTask from dataclass.configs import BaseDataClass from dataclass.choices import BODY_CHOICES from dataclasses import dataclass,field from typing import Optional from helper.utils import compress_datatype,check_var @dataclass class BodyConfig(BaseDataClass): option: Optional[BODY_CHOICES] = field(default='extra',metadata={'help':'the set of data to build'}) task: str = field(default='build_body') def check_name(dc,key): if key in dc: value = dc[key] else: raise ValueError(f'{key} must be input') return value @register_task('build_body',dataclass=BodyConfig) class BuildBody(BaseTask): def __init__(self, args, train, test, model, arch, **kwargs): self.args = args self.train = train[:,1:-1] self.test = test[:,:-1] self.arch = arch self.columns = ["resource", "manager", "role1", "role2", "department", "title", "family_desc", "family"] dictionary_train = check_name(kwargs,'pivottable_train') dictionary_test = check_name(kwargs,'pivottable_test') dictionary = check_name(kwargs,'pivottable') self.dictionary_train = dictionary_train self.dictionary_test = dictionary_test self.dictionary = dictionary def gen_feature(self,data,feature_list): features = [] for row in data: features.append([]) for j in range(len(self.columns)): for func in feature_list: features[-1].append(func(self.dictionary[j][row[j]],row,j)) features = np.array(features) return features def create_features(self): if self.args.option == 'extra': def log_result(x,row,j): v = x[self.columns[0]].get(row[0],0) if v > 0: return math.log(v) else: return 0 feature_list = [ lambda x,row,j: x[self.columns[0]].get(row[0],0) if j > 0 else 0, lambda x,row,j: x[self.columns[1]].get(row[1],0) if j > 1 else 0, lambda x,row,j: x[self.columns[2]].get(row[2],0) if j > 2 else 0, lambda x,row,j: x[self.columns[3]].get(row[3],0) if j > 3 else 0, lambda x,row,j: x[self.columns[4]].get(row[4],0) if j > 4 else 0, lambda x,row,j: x[self.columns[5]].get(row[5],0) if j > 5 else 0, lambda x,row,j: x[self.columns[6]].get(row[6],0) if j > 6 else 0, lambda x,row,j: x[self.columns[7]].get(row[7],0) if j > 7 else 0, lambda x,row,j: x[self.columns[0]].get(row[0],0)**2 if j in range(7) else 0, log_result] elif self.args.option == 'tree': feature_list = [lambda x,row,j: x[self.columns[0]].get(row[0],0), lambda x,row,j: x[self.columns[1]].get(row[1],0), lambda x,row,j: x[self.columns[2]].get(row[2],0), lambda x,row,j: x[self.columns[3]].get(row[3],0), lambda x,row,j: x[self.columns[4]].get(row[4],0), lambda x,row,j: x[self.columns[5]].get(row[5],0), lambda x,row,j: x[self.columns[6]].get(row[6],0), lambda x,row,j: x[self.columns[7]].get(row[7],0)] elif self.args.option == 'meta': feature_list = [lambda x,row,j: self.dictionary_train[j].get(row[j],{}).get('total',0)] else: feature_list = [lambda x,row,j: x[self.columns[0]].get(row[0],0) / x['total'], lambda x,row,j: x[self.columns[1]].get(row[1],1) / x['total'], lambda x,row,j: x[self.columns[2]].get(row[2],2) / x['total'], lambda x,row,j: x[self.columns[3]].get(row[3],3) / x['total'], lambda x,row,j: x[self.columns[4]].get(row[4],4) / x['total'], lambda x,row,j: x[self.columns[5]].get(row[5],5) / x['total'], lambda x,row,j: x[self.columns[6]].get(row[6],6) / x['total'], lambda x,row,j: x[self.columns[7]].get(row[7],7) / x['total']] logger.info(f'building dataset with option:{self.args.option}') feature_train = self.gen_feature(self.train,feature_list) feature_test = self.gen_feature(self.test,feature_list) feature_train = compress_datatype(feature_train) feature_test = compress_datatype(feature_test) feature_train,feature_test = check_var(feature_train,feature_test) filename = self.args.option with open(f'interim_data_store/{filename}_data.pkl','wb') as f: pickle.dump((feature_train,feature_test),f) logger.info(f'saving {filename} data at interim_data_store') return feature_train,feature_test #%%
0.537041
0.266285
import pandas as pd import numpy as np import math from dateutil import relativedelta import gc import logging from .demodulation import level_demodul_121,level_demodul_365 from ..config_features import NUMERICAL_FEATURES,CATEGORICAL_FEATURES,CAT_MAP from ..config import ALL_STATIONS def make_dataset(raw_hydro_df: pd.DataFrame, train=False) -> pd.DataFrame: ''' Метод для создания датасета со всеми таргетами и фичами Важно! Все гидропосты не из ALL_STATIONS будут проигнорированы Используются следующие фичи: 1) cos,sin преобразование от текущего дня (для учета цикличности) 2) cos,sin преобразование 10 дней назад (для учета цикличности) 3) воссталовленные периодические составляющие для уровня 10 дней назад с периодом 365 и 121 дней 4) уровень воды 10,20,30 дней назад 5) уровень воды год назад (ровно в тот жен день и усредненный за 3 дня) 6) уровень воды, код состояния водного объекта, расход воды, толщина льда, снежный покров 10 дней назад 7) количество дней без осадков 8) направление ветра, скорость ветра, количество осадков, мин. температура воздуха, макс. температура воздуха, относительная влажность, давление за текущий день 9) направление ветра, скорость ветра, количество осадков, мин. температура воздуха, макс. температура воздуха, относительная влажность, давление за вчерашний день 10) направление ветра, скорость ветра, максимальная скорость ветра, количество осадков, мин. температура воздуха, макс. температура воздуха, температура почвы, относительная влажность, давление,погода между сроками, погода в в срок наблюдения, количество облачности 10 дней назад 11) среднее количество осадков и относительной влажности за 3,7 и 45 дней 12) среднее количество осадков и относительной влажности за 3,7 дней 10 дней назад Каждые признаки вычисляются для каждого гидропоста из ALL_STATIONS и разворачиваются по дате в единый датафрейм :param raw_hydro_df: pd.DataFrame, датафрейм со гидро-метео признаками для всех станций :param train: bool, если True то считаем что это датасет для обучения модели :return: amur_df - pd.DataFrame - получившийся датасет ''' hydro_df = raw_hydro_df.copy() features = [] logger = logging.getLogger() logger.info('~~~START MAKING FEATURES~~~') # категориальные фичи if len(CATEGORICAL_FEATURES) > 0: logger.info('\tcategorical features') for col in ['water_code', 'presentWeather', 'pastWeather', 'cloudCoverTotal']: hydro_df[col] = col + hydro_df[col].astype(np.int).astype(str) hydro_df[col] = hydro_df[col].map(CAT_MAP) # sin,cos преобразования от дат logger.info('\tsin-cos dates') hydro_df['sin_day_of_year'] = hydro_df['date'].apply(lambda x: np.sin(2 * math.pi * x.timetuple().tm_yday / 365)) hydro_df['cos_day_of_year'] = hydro_df['date'].apply(lambda x: np.cos(2 * math.pi * x.timetuple().tm_yday / 365)) features.extend(['sin_day_of_year', 'cos_day_of_year']) # количество дней без осадков logger.info('\tdays without precipitation') hydro_df['perc_days'] = hydro_df.groupby('identifier')['totalAccumulatedPrecipitation'].apply( lambda x: (x > 0.01).astype(np.int).cumsum()) hydro_df['perc_days'] = (hydro_df.groupby(['identifier', 'perc_days']).cumcount() - 1).clip(lower=0) features.append('perc_days') # --- 10 дней назад--- logger.info('\t10 days before') hydro_df.sort_values('date', inplace=True) for col in ['sealevel_max', 'ice_thickness', 'snow_height', 'water_flow', 'water_code', 'water_temp', 'pastWeather', 'presentWeather', 'cloudCoverTotal', 'windDirection', 'windSpeed', 'maximumWindGustSpeed', 'totalAccumulatedPrecipitation', 'soilTemperature', 'airTemperature_min', 'airTemperature_max', 'relativeHumidity', 'pressure', 'sin_day_of_year', 'cos_day_of_year']: features.append('shift_10_days_' + col) hydro_df['shift_10_days_' + col] = hydro_df.groupby('identifier')[col].shift(10) # -----20-30 дней назад logger.info('\t20,30 days before') hydro_df.sort_values('date', inplace=True) for shift in [20, 30]: for col in ['sealevel_max', 'ice_thickness', 'snow_height', 'water_flow', 'water_temp']: features.append(f'shift_{shift}_days_' + col) hydro_df[f'shift_{shift}_days_' + col] = hydro_df.groupby('identifier')[col].shift(shift) # ----метод демодуляции logger.info('\tdemodulation') hydro_df['demodule_365_sealevel_max'] = hydro_df.groupby('identifier')['shift_10_days_sealevel_max'].apply( lambda x: level_demodul_365(x)) hydro_df['x'] = hydro_df['shift_10_days_sealevel_max'] - hydro_df['demodule_365_sealevel_max'] hydro_df['demodule_121_sealevel_max'] = hydro_df.groupby('identifier')['x'].apply(lambda x: level_demodul_121(x)) hydro_df.drop('x', axis=1, inplace=True) hydro_df['demodule_diff'] = (hydro_df['shift_10_days_sealevel_max'] - hydro_df['demodule_365_sealevel_max'] - hydro_df['demodule_121_sealevel_max'] + hydro_df['shift_10_days_sealevel_max'].mean()) features.extend(['demodule_365_sealevel_max', 'demodule_121_sealevel_max', 'demodule_diff']) # --- для метео - день назад logger.info('\t1 day before') for col in ['windDirection', 'windSpeed', 'totalAccumulatedPrecipitation', 'airTemperature_min', 'airTemperature_max', 'relativeHumidity', 'pressure']: hydro_df['shift_1_days_' + col] = hydro_df.groupby('identifier')[col].shift(1) features.append('shift_1_days_' + col) # --- для метео - текущий день logger.info('\tmeteo') for col in ['windDirection', 'windSpeed', 'totalAccumulatedPrecipitation', 'airTemperature_min', 'airTemperature_max', 'relativeHumidity', 'pressure']: features.append(col) # --- накопленная влажность, осадки за 7,3,45 дней: logger.info('\t7,3,45 days mean') hydro_df.sort_values('date', inplace=True) for col in ['relativeHumidity', 'totalAccumulatedPrecipitation']: for acc in [7, 3, 45]: new_col = f'accumulate_{acc}_days_{col}_sum' test_df = hydro_df.groupby('identifier').rolling(f'{acc}D', on='date', center=False, min_periods=1)[col].mean().reset_index().rename( columns={col: new_col}) hydro_df = hydro_df.merge(test_df, on=['identifier', 'date'], how='left') features.append(new_col) if acc != 45: new_col = f'accumulate_{acc}_days_shift_10_days_{col}_sum' test_df = hydro_df.groupby('identifier').rolling(f'{acc}D', on='date', center=False, min_periods=1)[ 'shift_10_days_' + col].mean().reset_index().rename(columns={'shift_10_days_' + col: new_col}) hydro_df = hydro_df.merge(test_df, on=['identifier', 'date'], how='left') features.append(new_col) # --- прошлогодние усредненные за три дня logger.info('\tlast year') test_df = hydro_df[['identifier', 'date', 'sealevel_max']].copy() test_df['date'] = test_df['date'].apply(lambda x: x + relativedelta.relativedelta(years=1)) test_df.sort_values(['identifier', 'date'], inplace=True) test_df = test_df.groupby('identifier').rolling(3, on='date', center=True, min_periods=1)['sealevel_max'].mean().reset_index() \ .rename(columns={'sealevel_max': 'past_year_sealevel_max_3D'}) hydro_df = hydro_df.merge(test_df[['identifier', 'date', 'past_year_sealevel_max_3D']], on=['identifier', 'date'], how='left') features.append('past_year_sealevel_max_3D') test_df = hydro_df[['identifier', 'date', 'sealevel_max', 'water_code']].copy() test_df['date'] = test_df['date'].apply(lambda x: x + relativedelta.relativedelta(years=1)) test_df.rename(columns={'sealevel_max': 'past_year_sealevel_max', 'water_code': 'past_year_water_code'}, inplace=True) hydro_df = hydro_df.merge(test_df[['identifier', 'date', 'past_year_sealevel_max']], on=['identifier', 'date'], how='left') features.append('past_year_sealevel_max') #------------------------ hydro_df.sort_values(['identifier', 'date'], inplace=True) hydro_df.drop_duplicates(['identifier', 'date'], keep='last', inplace=True) features = list(set(features)) amur_df = pd.DataFrame() new_features = [] # список с финальными фичами после разворачивания датафрейма new_targets = [] # список с финальными таргетами после разворачивания датафрейма for grp_name, grp_df in hydro_df.groupby('identifier'): if grp_name not in ALL_STATIONS: continue new_features.extend([col + '_' + str(grp_name) for col in features]) new_targets.append('sealevel_max_' + str(grp_name)) if amur_df.empty: amur_df = grp_df[features + ['date', 'sealevel_max']].copy() amur_df.rename(columns={col: col + '_' + str(grp_name) for col in features + ['sealevel_max']}, inplace=True) else: part_df = grp_df[features + ['date', 'sealevel_max']].copy() part_df.rename(columns={col: col + '_' + str(grp_name) for col in features + ['sealevel_max']}, inplace=True) amur_df = amur_df.merge(part_df[[col + '_' + str(grp_name) for col in features + ['sealevel_max']] + ['date']], on='date', how='left') amur_df.sort_values('date', inplace=True) gc.collect() bad_cols = list(set(new_features).difference(set(NUMERICAL_FEATURES+CATEGORICAL_FEATURES))) amur_df.drop(bad_cols, axis=1, inplace=True) for col in bad_cols: if col in new_features: new_features.remove(col) count_df = amur_df.count() / len(amur_df) bad_cols = set(count_df[count_df < 1].index) amur_df.sort_values('date', inplace=True) for col in bad_cols: if (not train) or (col in new_features): amur_df[col] = amur_df[col].interpolate(method='linear').fillna(method='ffill').fillna(method='bfill') logger.info('~~~END MAKING FEATURES~~~') return amur_df
amurlevel_model/features/amur_features.py
import pandas as pd import numpy as np import math from dateutil import relativedelta import gc import logging from .demodulation import level_demodul_121,level_demodul_365 from ..config_features import NUMERICAL_FEATURES,CATEGORICAL_FEATURES,CAT_MAP from ..config import ALL_STATIONS def make_dataset(raw_hydro_df: pd.DataFrame, train=False) -> pd.DataFrame: ''' Метод для создания датасета со всеми таргетами и фичами Важно! Все гидропосты не из ALL_STATIONS будут проигнорированы Используются следующие фичи: 1) cos,sin преобразование от текущего дня (для учета цикличности) 2) cos,sin преобразование 10 дней назад (для учета цикличности) 3) воссталовленные периодические составляющие для уровня 10 дней назад с периодом 365 и 121 дней 4) уровень воды 10,20,30 дней назад 5) уровень воды год назад (ровно в тот жен день и усредненный за 3 дня) 6) уровень воды, код состояния водного объекта, расход воды, толщина льда, снежный покров 10 дней назад 7) количество дней без осадков 8) направление ветра, скорость ветра, количество осадков, мин. температура воздуха, макс. температура воздуха, относительная влажность, давление за текущий день 9) направление ветра, скорость ветра, количество осадков, мин. температура воздуха, макс. температура воздуха, относительная влажность, давление за вчерашний день 10) направление ветра, скорость ветра, максимальная скорость ветра, количество осадков, мин. температура воздуха, макс. температура воздуха, температура почвы, относительная влажность, давление,погода между сроками, погода в в срок наблюдения, количество облачности 10 дней назад 11) среднее количество осадков и относительной влажности за 3,7 и 45 дней 12) среднее количество осадков и относительной влажности за 3,7 дней 10 дней назад Каждые признаки вычисляются для каждого гидропоста из ALL_STATIONS и разворачиваются по дате в единый датафрейм :param raw_hydro_df: pd.DataFrame, датафрейм со гидро-метео признаками для всех станций :param train: bool, если True то считаем что это датасет для обучения модели :return: amur_df - pd.DataFrame - получившийся датасет ''' hydro_df = raw_hydro_df.copy() features = [] logger = logging.getLogger() logger.info('~~~START MAKING FEATURES~~~') # категориальные фичи if len(CATEGORICAL_FEATURES) > 0: logger.info('\tcategorical features') for col in ['water_code', 'presentWeather', 'pastWeather', 'cloudCoverTotal']: hydro_df[col] = col + hydro_df[col].astype(np.int).astype(str) hydro_df[col] = hydro_df[col].map(CAT_MAP) # sin,cos преобразования от дат logger.info('\tsin-cos dates') hydro_df['sin_day_of_year'] = hydro_df['date'].apply(lambda x: np.sin(2 * math.pi * x.timetuple().tm_yday / 365)) hydro_df['cos_day_of_year'] = hydro_df['date'].apply(lambda x: np.cos(2 * math.pi * x.timetuple().tm_yday / 365)) features.extend(['sin_day_of_year', 'cos_day_of_year']) # количество дней без осадков logger.info('\tdays without precipitation') hydro_df['perc_days'] = hydro_df.groupby('identifier')['totalAccumulatedPrecipitation'].apply( lambda x: (x > 0.01).astype(np.int).cumsum()) hydro_df['perc_days'] = (hydro_df.groupby(['identifier', 'perc_days']).cumcount() - 1).clip(lower=0) features.append('perc_days') # --- 10 дней назад--- logger.info('\t10 days before') hydro_df.sort_values('date', inplace=True) for col in ['sealevel_max', 'ice_thickness', 'snow_height', 'water_flow', 'water_code', 'water_temp', 'pastWeather', 'presentWeather', 'cloudCoverTotal', 'windDirection', 'windSpeed', 'maximumWindGustSpeed', 'totalAccumulatedPrecipitation', 'soilTemperature', 'airTemperature_min', 'airTemperature_max', 'relativeHumidity', 'pressure', 'sin_day_of_year', 'cos_day_of_year']: features.append('shift_10_days_' + col) hydro_df['shift_10_days_' + col] = hydro_df.groupby('identifier')[col].shift(10) # -----20-30 дней назад logger.info('\t20,30 days before') hydro_df.sort_values('date', inplace=True) for shift in [20, 30]: for col in ['sealevel_max', 'ice_thickness', 'snow_height', 'water_flow', 'water_temp']: features.append(f'shift_{shift}_days_' + col) hydro_df[f'shift_{shift}_days_' + col] = hydro_df.groupby('identifier')[col].shift(shift) # ----метод демодуляции logger.info('\tdemodulation') hydro_df['demodule_365_sealevel_max'] = hydro_df.groupby('identifier')['shift_10_days_sealevel_max'].apply( lambda x: level_demodul_365(x)) hydro_df['x'] = hydro_df['shift_10_days_sealevel_max'] - hydro_df['demodule_365_sealevel_max'] hydro_df['demodule_121_sealevel_max'] = hydro_df.groupby('identifier')['x'].apply(lambda x: level_demodul_121(x)) hydro_df.drop('x', axis=1, inplace=True) hydro_df['demodule_diff'] = (hydro_df['shift_10_days_sealevel_max'] - hydro_df['demodule_365_sealevel_max'] - hydro_df['demodule_121_sealevel_max'] + hydro_df['shift_10_days_sealevel_max'].mean()) features.extend(['demodule_365_sealevel_max', 'demodule_121_sealevel_max', 'demodule_diff']) # --- для метео - день назад logger.info('\t1 day before') for col in ['windDirection', 'windSpeed', 'totalAccumulatedPrecipitation', 'airTemperature_min', 'airTemperature_max', 'relativeHumidity', 'pressure']: hydro_df['shift_1_days_' + col] = hydro_df.groupby('identifier')[col].shift(1) features.append('shift_1_days_' + col) # --- для метео - текущий день logger.info('\tmeteo') for col in ['windDirection', 'windSpeed', 'totalAccumulatedPrecipitation', 'airTemperature_min', 'airTemperature_max', 'relativeHumidity', 'pressure']: features.append(col) # --- накопленная влажность, осадки за 7,3,45 дней: logger.info('\t7,3,45 days mean') hydro_df.sort_values('date', inplace=True) for col in ['relativeHumidity', 'totalAccumulatedPrecipitation']: for acc in [7, 3, 45]: new_col = f'accumulate_{acc}_days_{col}_sum' test_df = hydro_df.groupby('identifier').rolling(f'{acc}D', on='date', center=False, min_periods=1)[col].mean().reset_index().rename( columns={col: new_col}) hydro_df = hydro_df.merge(test_df, on=['identifier', 'date'], how='left') features.append(new_col) if acc != 45: new_col = f'accumulate_{acc}_days_shift_10_days_{col}_sum' test_df = hydro_df.groupby('identifier').rolling(f'{acc}D', on='date', center=False, min_periods=1)[ 'shift_10_days_' + col].mean().reset_index().rename(columns={'shift_10_days_' + col: new_col}) hydro_df = hydro_df.merge(test_df, on=['identifier', 'date'], how='left') features.append(new_col) # --- прошлогодние усредненные за три дня logger.info('\tlast year') test_df = hydro_df[['identifier', 'date', 'sealevel_max']].copy() test_df['date'] = test_df['date'].apply(lambda x: x + relativedelta.relativedelta(years=1)) test_df.sort_values(['identifier', 'date'], inplace=True) test_df = test_df.groupby('identifier').rolling(3, on='date', center=True, min_periods=1)['sealevel_max'].mean().reset_index() \ .rename(columns={'sealevel_max': 'past_year_sealevel_max_3D'}) hydro_df = hydro_df.merge(test_df[['identifier', 'date', 'past_year_sealevel_max_3D']], on=['identifier', 'date'], how='left') features.append('past_year_sealevel_max_3D') test_df = hydro_df[['identifier', 'date', 'sealevel_max', 'water_code']].copy() test_df['date'] = test_df['date'].apply(lambda x: x + relativedelta.relativedelta(years=1)) test_df.rename(columns={'sealevel_max': 'past_year_sealevel_max', 'water_code': 'past_year_water_code'}, inplace=True) hydro_df = hydro_df.merge(test_df[['identifier', 'date', 'past_year_sealevel_max']], on=['identifier', 'date'], how='left') features.append('past_year_sealevel_max') #------------------------ hydro_df.sort_values(['identifier', 'date'], inplace=True) hydro_df.drop_duplicates(['identifier', 'date'], keep='last', inplace=True) features = list(set(features)) amur_df = pd.DataFrame() new_features = [] # список с финальными фичами после разворачивания датафрейма new_targets = [] # список с финальными таргетами после разворачивания датафрейма for grp_name, grp_df in hydro_df.groupby('identifier'): if grp_name not in ALL_STATIONS: continue new_features.extend([col + '_' + str(grp_name) for col in features]) new_targets.append('sealevel_max_' + str(grp_name)) if amur_df.empty: amur_df = grp_df[features + ['date', 'sealevel_max']].copy() amur_df.rename(columns={col: col + '_' + str(grp_name) for col in features + ['sealevel_max']}, inplace=True) else: part_df = grp_df[features + ['date', 'sealevel_max']].copy() part_df.rename(columns={col: col + '_' + str(grp_name) for col in features + ['sealevel_max']}, inplace=True) amur_df = amur_df.merge(part_df[[col + '_' + str(grp_name) for col in features + ['sealevel_max']] + ['date']], on='date', how='left') amur_df.sort_values('date', inplace=True) gc.collect() bad_cols = list(set(new_features).difference(set(NUMERICAL_FEATURES+CATEGORICAL_FEATURES))) amur_df.drop(bad_cols, axis=1, inplace=True) for col in bad_cols: if col in new_features: new_features.remove(col) count_df = amur_df.count() / len(amur_df) bad_cols = set(count_df[count_df < 1].index) amur_df.sort_values('date', inplace=True) for col in bad_cols: if (not train) or (col in new_features): amur_df[col] = amur_df[col].interpolate(method='linear').fillna(method='ffill').fillna(method='bfill') logger.info('~~~END MAKING FEATURES~~~') return amur_df
0.323915
0.53279
import cmudict from difflib import get_close_matches import warnings CMU_dict = cmudict.dict() CMU_keys = CMU_dict.keys() def DEPREC_fuzzy_CMU_keys(word, tolerance=91): """ Returns a list of tuples with fuzzy matching string in tuple[0] and similarity score in tuple[1]. ex: [(fuzzy_string1, similarity_score1), (fuzzy_string2, similarity_score2), ...] Takes fuzzy tolerance as an optional argument (0-100), and defaults to 91. """ if word.lower() in CMU_keys: return [(word,)] else: print(f"Search term not found. Looking for fuzzy matches. (Tolerance={tolerance})") fuzz_list = get_close_matches(word.lower(), CMU_keys, cutoff=tolerance*.01) if not len(fuzz_list) == 0: return fuzz_list else: raise ValueError("I tried, but I couldn't find any good results. " "Consider lowering the similarity tolerance to increase the number of matches." ) def DEPREC_fuzzy_CMU_key(word, tolerance=91): """ Returns a tuple with fuzzy matching string in tuple[0] and similarity score in tuple[1]. ex: (fuzzy_string, similarity_score) Takes fuzzy tolerance as an optional argument (0-100), and defaults to 91. """ if word.lower() in CMU_keys: return (word,) else: warnings.warn(f"Search term not found. Looking for closest fuzzy match. (Tolerance={tolerance*.01})") fuzz_list = get_close_matches(word.lower(), CMU_keys, n=1, cutoff=tolerance*.01) if not len(fuzz_list) == 0: closest_fuzz = fuzz_list return closest_fuzz else: raise ValueError("Could not find any good search terms. " "Consider lowering the similarity tolerance to find a match." ) def fuzzy_term(term, cutoff=.9, suppress_error=False): """ Takes a multi-word search term. For each word in the term: check if the word is in CMU dict. if the word is in CMU dict: append it to a result list. if the word is not in CMU dict: find the closest fuzzy match within CMU_dict above the given (or default) cutoff, and append that to fuzzy term. if no fuzzy match is found: skip the word but proceed with the search anyway. If search term exists: return search term. Otherwise: throw an error. """ fuzzy_term = [] for word in term.lower().split(): if word in CMU_dict: fuzzy_term.append(word.title()) else: warnings.warn(f"Search term not found. Looking for similar terms.") fuzzy_word = get_close_matches(word, CMU_keys, n=1, cutoff=cutoff) if not fuzzy_word == []: fuzzy_term.append(fuzzy_word[0].title()) fuzzy_term = ' '.join(fuzzy_term) if fuzzy_term: return fuzzy_term elif suppress_error: return term else: raise ValueError('Error: Could not identify a similar term. Perhaps try adjusting the delta cutoff. ' '(Cutoff must be between 0 and 1)' )
FuzzyTerm.py
import cmudict from difflib import get_close_matches import warnings CMU_dict = cmudict.dict() CMU_keys = CMU_dict.keys() def DEPREC_fuzzy_CMU_keys(word, tolerance=91): """ Returns a list of tuples with fuzzy matching string in tuple[0] and similarity score in tuple[1]. ex: [(fuzzy_string1, similarity_score1), (fuzzy_string2, similarity_score2), ...] Takes fuzzy tolerance as an optional argument (0-100), and defaults to 91. """ if word.lower() in CMU_keys: return [(word,)] else: print(f"Search term not found. Looking for fuzzy matches. (Tolerance={tolerance})") fuzz_list = get_close_matches(word.lower(), CMU_keys, cutoff=tolerance*.01) if not len(fuzz_list) == 0: return fuzz_list else: raise ValueError("I tried, but I couldn't find any good results. " "Consider lowering the similarity tolerance to increase the number of matches." ) def DEPREC_fuzzy_CMU_key(word, tolerance=91): """ Returns a tuple with fuzzy matching string in tuple[0] and similarity score in tuple[1]. ex: (fuzzy_string, similarity_score) Takes fuzzy tolerance as an optional argument (0-100), and defaults to 91. """ if word.lower() in CMU_keys: return (word,) else: warnings.warn(f"Search term not found. Looking for closest fuzzy match. (Tolerance={tolerance*.01})") fuzz_list = get_close_matches(word.lower(), CMU_keys, n=1, cutoff=tolerance*.01) if not len(fuzz_list) == 0: closest_fuzz = fuzz_list return closest_fuzz else: raise ValueError("Could not find any good search terms. " "Consider lowering the similarity tolerance to find a match." ) def fuzzy_term(term, cutoff=.9, suppress_error=False): """ Takes a multi-word search term. For each word in the term: check if the word is in CMU dict. if the word is in CMU dict: append it to a result list. if the word is not in CMU dict: find the closest fuzzy match within CMU_dict above the given (or default) cutoff, and append that to fuzzy term. if no fuzzy match is found: skip the word but proceed with the search anyway. If search term exists: return search term. Otherwise: throw an error. """ fuzzy_term = [] for word in term.lower().split(): if word in CMU_dict: fuzzy_term.append(word.title()) else: warnings.warn(f"Search term not found. Looking for similar terms.") fuzzy_word = get_close_matches(word, CMU_keys, n=1, cutoff=cutoff) if not fuzzy_word == []: fuzzy_term.append(fuzzy_word[0].title()) fuzzy_term = ' '.join(fuzzy_term) if fuzzy_term: return fuzzy_term elif suppress_error: return term else: raise ValueError('Error: Could not identify a similar term. Perhaps try adjusting the delta cutoff. ' '(Cutoff must be between 0 and 1)' )
0.609873
0.394901
from pdf2image import convert_from_path from datetime import date import urllib.request import json import os # Average dominant color import cv2 as cv import numpy as np import matplotlib.pyplot as plt import PIL # Accepts a string with the location of the params_file # Returns a dictionary with the parameters def get_params(params_file, username, password): params_dict = {} # Grabbing the username and password for the account with open(params_file) as params_file: json_params = json.load(params_file) params_file.close() # When testing locally with username and password in params file # params_dict['username'] = json_params['username'] # params_dict['password'] = json_params['password'] # When the username and password are stored as environment variables params_dict['username'] = os.getenv(username) params_dict['password'] = <PASSWORD>(password) params_dict['previous_post_key'] = json_params['previous_post_key'] return params_dict # Accepts a dictionary with the edited params values def set_params(params_file, edit_params): # Reading current parameters from file with open(params_file) as old_params_file: curr_params = json.load(old_params_file) old_params_file.close() # Debug print # print(curr_params) new_params = curr_params for key, value in edit_params.items(): new_params[key] = value # Debug print # print(new_params) # Writing new params to file with open(params_file, 'w') as new_params_file: json.dump(new_params, new_params_file) new_params_file.close() return # Accepts two strings, path where to download the image and the url from where to download the image def download_image(img_path, img_url): f = open(img_path,'wb') f.write(urllib.request.urlopen(img_url).read()) f.close() return # Accepts two strings, path of input image and path of output image def img_bg_color(input_img, output_img): # Getting average color in image and saving as background img = cv.imread(input_img) img = cv.cvtColor(img, cv.COLOR_BGR2RGB) img_temp = img.copy() img_temp[:,:,0], img_temp[:,:,1], img_temp[:,:,2] = np.average(img, axis=(0,1)) cv.imwrite(output_img, img_temp) return def compile_xelatex_silent(): os.system("\ cd latex ; \ xelatex main.tex >> /dev/null ; \ xelatex main.tex >> /dev/null") return def compile_xelatex_verbose(): os.system("\ cd latex ; \ xelatex main.tex ; \ xelatex main.tex") return def compile_latex_silent(): os.system("\ cd latex ; \ pdflatex main.tex >> /dev/null ; \ pdflatex main.tex >> /dev/null") return def compile_latex_verbose(): os.system("\ cd latex ; \ pdflatex main.tex ; \ pdflatex main.tex") return def pdf_2_jpg(input_pdf, output_img): pages = convert_from_path(input_pdf, 500) pages[0].save(output_img, 'JPEG') return def edit_badge(badge_file_name, execution_result): badge_file_path = "../badges/" + badge_file_name # Reading current parameters from file with open(badge_file_path) as badge_file: curr_badge_params = json.load(badge_file) badge_file.close() # Debug print # print(curr_badge_params) new_badge_params = curr_badge_params for key, value in execution_result.items(): new_badge_params[key] = value # Same values for all badges new_badge_params['schemaVersion'] = 1 new_badge_params["label"] = "Latest post" today = date.today() formatted_date = str(today.day) + " / " + str(today.month) + " / " + str(today.year) new_badge_params["message"] = formatted_date # Debug print # print(new_badge_params) # Writing new params to file with open(badge_file_path, 'w') as new_badge_file: json.dump(new_badge_params, new_badge_file) new_badge_file.close() return
utils.py
from pdf2image import convert_from_path from datetime import date import urllib.request import json import os # Average dominant color import cv2 as cv import numpy as np import matplotlib.pyplot as plt import PIL # Accepts a string with the location of the params_file # Returns a dictionary with the parameters def get_params(params_file, username, password): params_dict = {} # Grabbing the username and password for the account with open(params_file) as params_file: json_params = json.load(params_file) params_file.close() # When testing locally with username and password in params file # params_dict['username'] = json_params['username'] # params_dict['password'] = json_params['password'] # When the username and password are stored as environment variables params_dict['username'] = os.getenv(username) params_dict['password'] = <PASSWORD>(password) params_dict['previous_post_key'] = json_params['previous_post_key'] return params_dict # Accepts a dictionary with the edited params values def set_params(params_file, edit_params): # Reading current parameters from file with open(params_file) as old_params_file: curr_params = json.load(old_params_file) old_params_file.close() # Debug print # print(curr_params) new_params = curr_params for key, value in edit_params.items(): new_params[key] = value # Debug print # print(new_params) # Writing new params to file with open(params_file, 'w') as new_params_file: json.dump(new_params, new_params_file) new_params_file.close() return # Accepts two strings, path where to download the image and the url from where to download the image def download_image(img_path, img_url): f = open(img_path,'wb') f.write(urllib.request.urlopen(img_url).read()) f.close() return # Accepts two strings, path of input image and path of output image def img_bg_color(input_img, output_img): # Getting average color in image and saving as background img = cv.imread(input_img) img = cv.cvtColor(img, cv.COLOR_BGR2RGB) img_temp = img.copy() img_temp[:,:,0], img_temp[:,:,1], img_temp[:,:,2] = np.average(img, axis=(0,1)) cv.imwrite(output_img, img_temp) return def compile_xelatex_silent(): os.system("\ cd latex ; \ xelatex main.tex >> /dev/null ; \ xelatex main.tex >> /dev/null") return def compile_xelatex_verbose(): os.system("\ cd latex ; \ xelatex main.tex ; \ xelatex main.tex") return def compile_latex_silent(): os.system("\ cd latex ; \ pdflatex main.tex >> /dev/null ; \ pdflatex main.tex >> /dev/null") return def compile_latex_verbose(): os.system("\ cd latex ; \ pdflatex main.tex ; \ pdflatex main.tex") return def pdf_2_jpg(input_pdf, output_img): pages = convert_from_path(input_pdf, 500) pages[0].save(output_img, 'JPEG') return def edit_badge(badge_file_name, execution_result): badge_file_path = "../badges/" + badge_file_name # Reading current parameters from file with open(badge_file_path) as badge_file: curr_badge_params = json.load(badge_file) badge_file.close() # Debug print # print(curr_badge_params) new_badge_params = curr_badge_params for key, value in execution_result.items(): new_badge_params[key] = value # Same values for all badges new_badge_params['schemaVersion'] = 1 new_badge_params["label"] = "Latest post" today = date.today() formatted_date = str(today.day) + " / " + str(today.month) + " / " + str(today.year) new_badge_params["message"] = formatted_date # Debug print # print(new_badge_params) # Writing new params to file with open(badge_file_path, 'w') as new_badge_file: json.dump(new_badge_params, new_badge_file) new_badge_file.close() return
0.326057
0.26405
import shutil from os import path from typing import List, Tuple from urllib.request import urlopen import subprocess import click here = path.abspath(path.dirname(__file__)) PACKAGE = 'hmsclient' SUBPACKAGE = 'genthrift' generated = 'gen-py' FB303_URL = 'https://raw.githubusercontent.com/apache/thrift/0.11.0/contrib/fb303/if/fb303.thrift' METASTORE_URL = 'https://raw.githubusercontent.com/apache/hive/rel/release-2.3.3/metastore/if/hive_metastore.thrift' config = {path.join("hive_metastore", "ttypes.py"): [('import fb303.ttypes', 'from ..fb303 import ttypes')], path.join("hive_metastore", "ThriftHiveMetastore.py"): [('import fb303.FacebookService', 'from .. import fb303')], path.join("hive_metastore", "ThriftHiveMetastore-remote"): [('from hive_metastore import ThriftHiveMetastore', 'from ..hive_metastore import ThriftHiveMetastore'), ('from hive_metastore.ttypes import *', 'from ..hive_metastore.ttypes import *')], path.join("hive_metastore", "constants.py"): [], path.join("hive_metastore", "__init__.py"): [], path.join("fb303", "__init__.py"): [(']', ']\nfrom . import FacebookService')], path.join("fb303", "FacebookService.py"): [('from fb303 import FacebookService', 'from . import FacebookService'), ('from fb303.types import *', 'from .ttypes import *')], path.join("fb303", "constants.py"): [], path.join("fb303", "FacebookService-remote"): [('from fb303 import FacebookService', 'from . import FacebookService'), ('from fb303.ttypes import *', 'from .ttypes import *')], path.join("fb303", "ttypes.py"): [], '__init__.py': []} def replace(file_path: str, replacements: List[Tuple[str, str]]) -> str: with open(file_path, 'r') as f: string = f.read() for old, new in replacements: string = string.replace(old, new) return string def write_file(string: str, file_path: str) -> None: with open(file_path, 'w') as f: f.write(string) def save_url(url): data = urlopen(url).read() file_path = path.join(here, url.rsplit('/', 1)[-1]) with open(file_path, 'wb') as f: f.write(data) @click.command() @click.option('--fb303_url', default=FB303_URL, help='The URL where the fb303.thrift file can be ' 'downloaded') @click.option('--metastore_url', default=METASTORE_URL, help='The URL where the ' 'hive_metastore.thrift file can be ' 'downloaded') @click.option('--package', default=PACKAGE, help='The package where the client should be placed') @click.option('--subpackage', default=SUBPACKAGE, help='The subpackage where the client should be ' 'placed') def main(fb303_url, metastore_url, package, subpackage): for url in (fb303_url, metastore_url): save_url(url) metastore_path = path.join(here, metastore_url.rsplit('/', 1)[-1]) metastore_content = replace(metastore_path, [('include "share/fb303/if/fb303.thrift"', 'include "fb303.thrift"')]) with open(metastore_path, 'w') as f: f.write(metastore_content) subprocess.call(['thrift', '-r', '--gen', 'py', metastore_path]) for file_path, replacement in config.items(): to_write = replace(path.join(here, generated, file_path), replacement) write_file(to_write, path.join(here, package, subpackage, file_path)) shutil.rmtree(generated) if __name__ == '__main__': main()
generate.py
import shutil from os import path from typing import List, Tuple from urllib.request import urlopen import subprocess import click here = path.abspath(path.dirname(__file__)) PACKAGE = 'hmsclient' SUBPACKAGE = 'genthrift' generated = 'gen-py' FB303_URL = 'https://raw.githubusercontent.com/apache/thrift/0.11.0/contrib/fb303/if/fb303.thrift' METASTORE_URL = 'https://raw.githubusercontent.com/apache/hive/rel/release-2.3.3/metastore/if/hive_metastore.thrift' config = {path.join("hive_metastore", "ttypes.py"): [('import fb303.ttypes', 'from ..fb303 import ttypes')], path.join("hive_metastore", "ThriftHiveMetastore.py"): [('import fb303.FacebookService', 'from .. import fb303')], path.join("hive_metastore", "ThriftHiveMetastore-remote"): [('from hive_metastore import ThriftHiveMetastore', 'from ..hive_metastore import ThriftHiveMetastore'), ('from hive_metastore.ttypes import *', 'from ..hive_metastore.ttypes import *')], path.join("hive_metastore", "constants.py"): [], path.join("hive_metastore", "__init__.py"): [], path.join("fb303", "__init__.py"): [(']', ']\nfrom . import FacebookService')], path.join("fb303", "FacebookService.py"): [('from fb303 import FacebookService', 'from . import FacebookService'), ('from fb303.types import *', 'from .ttypes import *')], path.join("fb303", "constants.py"): [], path.join("fb303", "FacebookService-remote"): [('from fb303 import FacebookService', 'from . import FacebookService'), ('from fb303.ttypes import *', 'from .ttypes import *')], path.join("fb303", "ttypes.py"): [], '__init__.py': []} def replace(file_path: str, replacements: List[Tuple[str, str]]) -> str: with open(file_path, 'r') as f: string = f.read() for old, new in replacements: string = string.replace(old, new) return string def write_file(string: str, file_path: str) -> None: with open(file_path, 'w') as f: f.write(string) def save_url(url): data = urlopen(url).read() file_path = path.join(here, url.rsplit('/', 1)[-1]) with open(file_path, 'wb') as f: f.write(data) @click.command() @click.option('--fb303_url', default=FB303_URL, help='The URL where the fb303.thrift file can be ' 'downloaded') @click.option('--metastore_url', default=METASTORE_URL, help='The URL where the ' 'hive_metastore.thrift file can be ' 'downloaded') @click.option('--package', default=PACKAGE, help='The package where the client should be placed') @click.option('--subpackage', default=SUBPACKAGE, help='The subpackage where the client should be ' 'placed') def main(fb303_url, metastore_url, package, subpackage): for url in (fb303_url, metastore_url): save_url(url) metastore_path = path.join(here, metastore_url.rsplit('/', 1)[-1]) metastore_content = replace(metastore_path, [('include "share/fb303/if/fb303.thrift"', 'include "fb303.thrift"')]) with open(metastore_path, 'w') as f: f.write(metastore_content) subprocess.call(['thrift', '-r', '--gen', 'py', metastore_path]) for file_path, replacement in config.items(): to_write = replace(path.join(here, generated, file_path), replacement) write_file(to_write, path.join(here, package, subpackage, file_path)) shutil.rmtree(generated) if __name__ == '__main__': main()
0.494141
0.074366
import os # Make sure we're running from the spam/ directory if os.path.basename(os.getcwd()) == "": os.chdir("") from utils import load_unlabeled_spam_dataset df_train = load_unlabeled_spam_dataset() ABSTAIN = -1 NOT_SPAM = 0 SPAM = 1 from snorkel.labeling import labeling_function @labeling_function() def lf_keyword_my(x): """Many spam comments talk about 'my channel', 'my video', etc.""" return SPAM if "my" in x.text.lower() else ABSTAIN import re @labeling_function() def lf_regex_check_out(x): """Spam comments say 'check out my video', 'check it out', etc.""" return SPAM if re.search(r"check.*out", x.text, flags=re.I) else ABSTAIN @labeling_function() def lf_short_comment(x): """Non-spam comments are often short, such as 'cool video!'.""" return NOT_SPAM if len(x.text.split()) < 5 else ABSTAIN from textblob import TextBlob @labeling_function() def lf_textblob_polarity(x): """ We use a third-party sentiment classification model, TextBlob. We combine this with the heuristic that non-spam comments are often positive. """ return NOT_SPAM if TextBlob(x.text).sentiment.polarity > 0.3 else ABSTAIN from snorkel.labeling import LabelModel, PandasLFApplier # Define the set of labeling functions (LFs) lfs = [lf_keyword_my, lf_regex_check_out, lf_short_comment, lf_textblob_polarity] applier = PandasLFApplier(lfs) L_train = applier.apply(df_train) label_model = LabelModel(cardinality=2, verbose=True) label_model.fit(L_train, n_epochs=500, log_freq=50, seed=123) df_train["label"] = label_model.predict(L=L_train, tie_break_policy="abstain") df_train = df_train[df_train.label != ABSTAIN] import random import nltk from nltk.corpus import wordnet as wn from snorkel.augmentation import transformation_function nltk.download("wordnet", quiet=True) def get_synonyms(word): """Get the synonyms of word from Wordnet.""" lemmas = set().union(*[s.lemmas() for s in wn.synsets(word)]) return list(set(l.name().lower().replace("_", " ") for l in lemmas) - {word}) @transformation_function() def tf_replace_word_with_synonym(x): """Try to replace a random word with a synonym.""" words = x.text.lower().split() idx = random.choice(range(len(words))) synonyms = get_synonyms(words[idx]) if len(synonyms) > 0: x.text = " ".join(words[:idx] + [synonyms[0]] + words[idx + 1 :]) return x from snorkel.augmentation import ApplyOnePolicy, PandasTFApplier tf_policy = ApplyOnePolicy(n_per_original=2, keep_original=True) tf_applier = PandasTFApplier([tf_replace_word_with_synonym], tf_policy) df_train_augmented = tf_applier.apply(df_train) from snorkel.slicing import slicing_function @slicing_function() def short_link(x): """Return whether text matches common pattern for shortened ".ly" links.""" return int(bool(re.search(r"\w+\.ly", x.text))) from sklearn.feature_extraction.text import CountVectorizer from sklearn.linear_model import LogisticRegression train_text = df_train_augmented.text.tolist() X_train = CountVectorizer(ngram_range=(1, 2)).fit_transform(train_text) clf = LogisticRegression(solver="lbfgs") clf.fit(X=X_train, y=df_train_augmented.label.values)
Intro_Snorkel/1gettingStart.py
import os # Make sure we're running from the spam/ directory if os.path.basename(os.getcwd()) == "": os.chdir("") from utils import load_unlabeled_spam_dataset df_train = load_unlabeled_spam_dataset() ABSTAIN = -1 NOT_SPAM = 0 SPAM = 1 from snorkel.labeling import labeling_function @labeling_function() def lf_keyword_my(x): """Many spam comments talk about 'my channel', 'my video', etc.""" return SPAM if "my" in x.text.lower() else ABSTAIN import re @labeling_function() def lf_regex_check_out(x): """Spam comments say 'check out my video', 'check it out', etc.""" return SPAM if re.search(r"check.*out", x.text, flags=re.I) else ABSTAIN @labeling_function() def lf_short_comment(x): """Non-spam comments are often short, such as 'cool video!'.""" return NOT_SPAM if len(x.text.split()) < 5 else ABSTAIN from textblob import TextBlob @labeling_function() def lf_textblob_polarity(x): """ We use a third-party sentiment classification model, TextBlob. We combine this with the heuristic that non-spam comments are often positive. """ return NOT_SPAM if TextBlob(x.text).sentiment.polarity > 0.3 else ABSTAIN from snorkel.labeling import LabelModel, PandasLFApplier # Define the set of labeling functions (LFs) lfs = [lf_keyword_my, lf_regex_check_out, lf_short_comment, lf_textblob_polarity] applier = PandasLFApplier(lfs) L_train = applier.apply(df_train) label_model = LabelModel(cardinality=2, verbose=True) label_model.fit(L_train, n_epochs=500, log_freq=50, seed=123) df_train["label"] = label_model.predict(L=L_train, tie_break_policy="abstain") df_train = df_train[df_train.label != ABSTAIN] import random import nltk from nltk.corpus import wordnet as wn from snorkel.augmentation import transformation_function nltk.download("wordnet", quiet=True) def get_synonyms(word): """Get the synonyms of word from Wordnet.""" lemmas = set().union(*[s.lemmas() for s in wn.synsets(word)]) return list(set(l.name().lower().replace("_", " ") for l in lemmas) - {word}) @transformation_function() def tf_replace_word_with_synonym(x): """Try to replace a random word with a synonym.""" words = x.text.lower().split() idx = random.choice(range(len(words))) synonyms = get_synonyms(words[idx]) if len(synonyms) > 0: x.text = " ".join(words[:idx] + [synonyms[0]] + words[idx + 1 :]) return x from snorkel.augmentation import ApplyOnePolicy, PandasTFApplier tf_policy = ApplyOnePolicy(n_per_original=2, keep_original=True) tf_applier = PandasTFApplier([tf_replace_word_with_synonym], tf_policy) df_train_augmented = tf_applier.apply(df_train) from snorkel.slicing import slicing_function @slicing_function() def short_link(x): """Return whether text matches common pattern for shortened ".ly" links.""" return int(bool(re.search(r"\w+\.ly", x.text))) from sklearn.feature_extraction.text import CountVectorizer from sklearn.linear_model import LogisticRegression train_text = df_train_augmented.text.tolist() X_train = CountVectorizer(ngram_range=(1, 2)).fit_transform(train_text) clf = LogisticRegression(solver="lbfgs") clf.fit(X=X_train, y=df_train_augmented.label.values)
0.701509
0.289296
import yaml from models import VGGNet import pandas as pd import os from random import shuffle from glob import glob def get_model(input_shape, setting): setting['nc'] = len(setting['classes']) network = VGGNet(name='vgg16', ch=input_shape[-1], imgsz=input_shape, setting=setting) return network def parse_dataset(path, name='trainval'): if name == 'trainval': imagepath = path['images'] labelpath = path['labels'] label_df = pd.read_csv(labelpath) # imagelist = glob(f"{imagepath}/**/**/*.dcm", recursive=True) rids = os.listdir(imagepath) shuffle(rids) valid_rate = 0.1 train_rids = rids[:int(len(rids) * (1 - valid_rate))] valid_rids = rids[int(len(rids) * (1 - valid_rate)):] train_imagelist, valid_imagelist = [], [] for rid in train_rids: templist = glob(f"{imagepath}/{rid}/**/*.dcm", recursive=True) train_imagelist += templist for rid in valid_rids: templist = glob(f"{imagepath}/{rid}/**/*.dcm", recursive=True) valid_imagelist += templist train_label_df = label_df[label_df["BraTS21ID"].isin(list(map(int, train_rids)))] valid_label_df = label_df[label_df["BraTS21ID"].isin(list(map(int, valid_rids)))] return [{"images": train_imagelist, "labels": train_label_df, "rids": train_rids}, {"images": valid_imagelist, "labels": valid_label_df, "rids": valid_rids}] elif name == 'test': imagepath = path['images'] imagelist = glob(f"{imagepath}/**/**/*.dcm", recursive=True) return {"images": imagelist} if __name__ == "__main__": with open(f'./setting.yaml') as f: setting = yaml.load(f, Loader=yaml.SafeLoader) print(setting) model = get_model(input_shape=(64, 64, 1), setting=setting) print(model) train_path = setting['train'] test_path = setting['test'] train_dict = parse_dataset(train_path, name='trainval') test_dict = parse_dataset(test_path, name='test') model.fit(train_data=train_dict[0], validation_data=train_dict[0], epochs=100, batch_size=1)
torch/kaggle_RSNA/vgg.py
import yaml from models import VGGNet import pandas as pd import os from random import shuffle from glob import glob def get_model(input_shape, setting): setting['nc'] = len(setting['classes']) network = VGGNet(name='vgg16', ch=input_shape[-1], imgsz=input_shape, setting=setting) return network def parse_dataset(path, name='trainval'): if name == 'trainval': imagepath = path['images'] labelpath = path['labels'] label_df = pd.read_csv(labelpath) # imagelist = glob(f"{imagepath}/**/**/*.dcm", recursive=True) rids = os.listdir(imagepath) shuffle(rids) valid_rate = 0.1 train_rids = rids[:int(len(rids) * (1 - valid_rate))] valid_rids = rids[int(len(rids) * (1 - valid_rate)):] train_imagelist, valid_imagelist = [], [] for rid in train_rids: templist = glob(f"{imagepath}/{rid}/**/*.dcm", recursive=True) train_imagelist += templist for rid in valid_rids: templist = glob(f"{imagepath}/{rid}/**/*.dcm", recursive=True) valid_imagelist += templist train_label_df = label_df[label_df["BraTS21ID"].isin(list(map(int, train_rids)))] valid_label_df = label_df[label_df["BraTS21ID"].isin(list(map(int, valid_rids)))] return [{"images": train_imagelist, "labels": train_label_df, "rids": train_rids}, {"images": valid_imagelist, "labels": valid_label_df, "rids": valid_rids}] elif name == 'test': imagepath = path['images'] imagelist = glob(f"{imagepath}/**/**/*.dcm", recursive=True) return {"images": imagelist} if __name__ == "__main__": with open(f'./setting.yaml') as f: setting = yaml.load(f, Loader=yaml.SafeLoader) print(setting) model = get_model(input_shape=(64, 64, 1), setting=setting) print(model) train_path = setting['train'] test_path = setting['test'] train_dict = parse_dataset(train_path, name='trainval') test_dict = parse_dataset(test_path, name='test') model.fit(train_data=train_dict[0], validation_data=train_dict[0], epochs=100, batch_size=1)
0.493409
0.193357
from __future__ import absolute_import from stablemanager.models.api_response import ApiResponse from stablemanager.models.association import Association from stablemanager.models.horse import Horse from stablemanager.models.schedule_summary import ScheduleSummary from . import BaseTestCase from six import BytesIO from flask import json class TestHorseController(BaseTestCase): """ HorseController integration test stubs """ def test_add_horse(self): """ Test case for add_horse Adds a new horse to the barn """ body = Horse() response = self.client.open('/v1/horse', method='POST', data=json.dumps(body), content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_add_horse_people(self): """ Test case for add_horse_people Adds a people to the horse """ body = [Association()] response = self.client.open('/v1/horse/{id}/people'.format(id='id_example'), method='POST', data=json.dumps(body), content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_delete_horse(self): """ Test case for delete_horse Removes a horse from the barn """ response = self.client.open('/v1/horse/{id}'.format(id='id_example'), method='DELETE', content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_delete_horse_person(self): """ Test case for delete_horse_person Removes association """ response = self.client.open('/v1/horse/{id}/people/{personId}'.format(id='id_example', personId='personId_example'), method='DELETE', content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_get_horse(self): """ Test case for get_horse Gets information for a specific horse """ response = self.client.open('/v1/horse/{id}'.format(id='id_example'), method='GET', content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_get_horse_people(self): """ Test case for get_horse_people Retrieves a list of all people associated with the horse """ query_string = [('type', 'type_example')] response = self.client.open('/v1/horse/{id}/people'.format(id='id_example'), method='GET', content_type='application/json', query_string=query_string) self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_get_horse_schedule(self): """ Test case for get_horse_schedule Retrieves a list of scheduled actions """ response = self.client.open('/v1/horse/{id}/schedule'.format(id='id_example'), method='GET', content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_get_horses(self): """ Test case for get_horses Retrieves a list of horses in the barn """ response = self.client.open('/v1/horse', method='GET', content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_update_horse(self): """ Test case for update_horse Updates a horse's data """ body = Horse() response = self.client.open('/v1/horse', method='PUT', data=json.dumps(body), content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_update_horse_people(self): """ Test case for update_horse_people Updates association(s) """ body = [Association()] response = self.client.open('/v1/horse/{id}/people'.format(id='id_example'), method='PUT', data=json.dumps(body), content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) if __name__ == '__main__': import unittest unittest.main()
api/stablemanager/test/test_horse_controller.py
from __future__ import absolute_import from stablemanager.models.api_response import ApiResponse from stablemanager.models.association import Association from stablemanager.models.horse import Horse from stablemanager.models.schedule_summary import ScheduleSummary from . import BaseTestCase from six import BytesIO from flask import json class TestHorseController(BaseTestCase): """ HorseController integration test stubs """ def test_add_horse(self): """ Test case for add_horse Adds a new horse to the barn """ body = Horse() response = self.client.open('/v1/horse', method='POST', data=json.dumps(body), content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_add_horse_people(self): """ Test case for add_horse_people Adds a people to the horse """ body = [Association()] response = self.client.open('/v1/horse/{id}/people'.format(id='id_example'), method='POST', data=json.dumps(body), content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_delete_horse(self): """ Test case for delete_horse Removes a horse from the barn """ response = self.client.open('/v1/horse/{id}'.format(id='id_example'), method='DELETE', content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_delete_horse_person(self): """ Test case for delete_horse_person Removes association """ response = self.client.open('/v1/horse/{id}/people/{personId}'.format(id='id_example', personId='personId_example'), method='DELETE', content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_get_horse(self): """ Test case for get_horse Gets information for a specific horse """ response = self.client.open('/v1/horse/{id}'.format(id='id_example'), method='GET', content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_get_horse_people(self): """ Test case for get_horse_people Retrieves a list of all people associated with the horse """ query_string = [('type', 'type_example')] response = self.client.open('/v1/horse/{id}/people'.format(id='id_example'), method='GET', content_type='application/json', query_string=query_string) self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_get_horse_schedule(self): """ Test case for get_horse_schedule Retrieves a list of scheduled actions """ response = self.client.open('/v1/horse/{id}/schedule'.format(id='id_example'), method='GET', content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_get_horses(self): """ Test case for get_horses Retrieves a list of horses in the barn """ response = self.client.open('/v1/horse', method='GET', content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_update_horse(self): """ Test case for update_horse Updates a horse's data """ body = Horse() response = self.client.open('/v1/horse', method='PUT', data=json.dumps(body), content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) def test_update_horse_people(self): """ Test case for update_horse_people Updates association(s) """ body = [Association()] response = self.client.open('/v1/horse/{id}/people'.format(id='id_example'), method='PUT', data=json.dumps(body), content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8')) if __name__ == '__main__': import unittest unittest.main()
0.769167
0.249953
from typing import Any, Dict, List, Optional, Tuple, Union from ....core import get_namespace as get_services_namespace from ....core import run_request from ....core import same_doc_as from ..models import ErrorEntity from ..models import StoreBackupInfo from ..models import StoreCreate from ..models import StoreInfo from ..models import StoreUpdate from ..models import ValidationErrorEntity from ..operations.store import CloneStore from ..operations.store import CreateStore from ..operations.store import DeletePublishedStore from ..operations.store import DeleteStore from ..operations.store import ExportStore from ..operations.store import GetPublishedStore from ..operations.store import GetPublishedStoreBackup from ..operations.store import GetStore from ..operations.store import ImportStore from ..operations.store import ListStores from ..operations.store import PublicListStores from ..operations.store import RollbackPublishedStore from ..operations.store import UpdateStore @same_doc_as(CloneStore) def clone_store(store_id: str, target_store_id: Optional[str] = None, namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = CloneStore.create( store_id=store_id, target_store_id=target_store_id, namespace=namespace, ) return run_request(request) @same_doc_as(CreateStore) def create_store(body: Optional[StoreCreate] = None, namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = CreateStore.create( body=body, namespace=namespace, ) return run_request(request) @same_doc_as(DeletePublishedStore) def delete_published_store(namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = DeletePublishedStore.create( namespace=namespace, ) return run_request(request) @same_doc_as(DeleteStore) def delete_store(store_id: str, namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = DeleteStore.create( store_id=store_id, namespace=namespace, ) return run_request(request) @same_doc_as(ExportStore) def export_store(store_id: str, namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = ExportStore.create( store_id=store_id, namespace=namespace, ) return run_request(request) @same_doc_as(GetPublishedStore) def get_published_store(namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = GetPublishedStore.create( namespace=namespace, ) return run_request(request) @same_doc_as(GetPublishedStoreBackup) def get_published_store_backup(namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = GetPublishedStoreBackup.create( namespace=namespace, ) return run_request(request) @same_doc_as(GetStore) def get_store(store_id: str, namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = GetStore.create( store_id=store_id, namespace=namespace, ) return run_request(request) @same_doc_as(ImportStore) def import_store(file: Optional[Any] = None, store_id: Optional[str] = None, namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = ImportStore.create( file=file, store_id=store_id, namespace=namespace, ) return run_request(request) @same_doc_as(ListStores) def list_stores(namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = ListStores.create( namespace=namespace, ) return run_request(request) @same_doc_as(PublicListStores) def public_list_stores(namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = PublicListStores.create( namespace=namespace, ) return run_request(request) @same_doc_as(RollbackPublishedStore) def rollback_published_store(namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = RollbackPublishedStore.create( namespace=namespace, ) return run_request(request) @same_doc_as(UpdateStore) def update_store(store_id: str, body: Optional[StoreUpdate] = None, namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = UpdateStore.create( store_id=store_id, body=body, namespace=namespace, ) return run_request(request)
accelbyte_py_sdk/api/platform/wrappers/_store.py
from typing import Any, Dict, List, Optional, Tuple, Union from ....core import get_namespace as get_services_namespace from ....core import run_request from ....core import same_doc_as from ..models import ErrorEntity from ..models import StoreBackupInfo from ..models import StoreCreate from ..models import StoreInfo from ..models import StoreUpdate from ..models import ValidationErrorEntity from ..operations.store import CloneStore from ..operations.store import CreateStore from ..operations.store import DeletePublishedStore from ..operations.store import DeleteStore from ..operations.store import ExportStore from ..operations.store import GetPublishedStore from ..operations.store import GetPublishedStoreBackup from ..operations.store import GetStore from ..operations.store import ImportStore from ..operations.store import ListStores from ..operations.store import PublicListStores from ..operations.store import RollbackPublishedStore from ..operations.store import UpdateStore @same_doc_as(CloneStore) def clone_store(store_id: str, target_store_id: Optional[str] = None, namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = CloneStore.create( store_id=store_id, target_store_id=target_store_id, namespace=namespace, ) return run_request(request) @same_doc_as(CreateStore) def create_store(body: Optional[StoreCreate] = None, namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = CreateStore.create( body=body, namespace=namespace, ) return run_request(request) @same_doc_as(DeletePublishedStore) def delete_published_store(namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = DeletePublishedStore.create( namespace=namespace, ) return run_request(request) @same_doc_as(DeleteStore) def delete_store(store_id: str, namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = DeleteStore.create( store_id=store_id, namespace=namespace, ) return run_request(request) @same_doc_as(ExportStore) def export_store(store_id: str, namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = ExportStore.create( store_id=store_id, namespace=namespace, ) return run_request(request) @same_doc_as(GetPublishedStore) def get_published_store(namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = GetPublishedStore.create( namespace=namespace, ) return run_request(request) @same_doc_as(GetPublishedStoreBackup) def get_published_store_backup(namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = GetPublishedStoreBackup.create( namespace=namespace, ) return run_request(request) @same_doc_as(GetStore) def get_store(store_id: str, namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = GetStore.create( store_id=store_id, namespace=namespace, ) return run_request(request) @same_doc_as(ImportStore) def import_store(file: Optional[Any] = None, store_id: Optional[str] = None, namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = ImportStore.create( file=file, store_id=store_id, namespace=namespace, ) return run_request(request) @same_doc_as(ListStores) def list_stores(namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = ListStores.create( namespace=namespace, ) return run_request(request) @same_doc_as(PublicListStores) def public_list_stores(namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = PublicListStores.create( namespace=namespace, ) return run_request(request) @same_doc_as(RollbackPublishedStore) def rollback_published_store(namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = RollbackPublishedStore.create( namespace=namespace, ) return run_request(request) @same_doc_as(UpdateStore) def update_store(store_id: str, body: Optional[StoreUpdate] = None, namespace: Optional[str] = None): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = UpdateStore.create( store_id=store_id, body=body, namespace=namespace, ) return run_request(request)
0.754282
0.148973
import pygame as pg import os import constants as c class GameStatesManager: """ Control class for managing game states. """ def __init__(self): self.state_dict = {} self.state_name = None self.state = None def setup(self, state_dict, start_state): """ Given a dictionary of states and a state to start in, builds the self.state_dict. """ self.state_dict = state_dict self.state_name = start_state self.state = self.state_dict[self.state_name] self.set_music() def update(self, window, keys, dt, events): """ Checks if a state is done. Changes state if necessary and state.update is called. """ if self.state.done: self.flip_state() self.state.update(window, keys, dt, events) def flip_state(self): """ Changes to a new state and performs clean_up for exiting state and start_up for new state. (Most importantly passing on game data.) """ previous, self.state_name = self.state_name, self.state.next previous_music = self.state.music_title game_data = self.state.clean_up() self.state = self.state_dict[self.state_name] self.state.previous = previous self.state.previous_music = previous_music self.state.start_up(game_data) self.set_music() def set_music(self): """ Play correct music for the state. """ if self.state.music_title == self.state.previous_music: pass elif self.state.music: pg.mixer.music.load(self.state.music) pg.mixer.music.set_volume(self.state.volume) pg.mixer.music.play(-1) class State: """ Template class for all game states to inherit from. """ def __init__(self): self.done = False self.game_data = None self.next = None self.previous = 'start' def start_up(self, game_data): self.game_data = game_data def clean_up(self): self.done = False return self.game_data def update(self, window, keys, dt, events): """ Update method for state. Must be overrided in children. """ pass def create_game_data_dict(): """ Creates a dictionary of game data to be carried between states and for save game functionality. """ # Items that player has collected and is carrying. ################################################## player_data = {'gold': 0, 'chickens': {'show': False, 'amount': 0, 'max': 0, 'catchable': False, 'rescue': False, 'catch': False}, 'found_items': set(), 'catched_chickens': set(), 'hearts': 0 } # Data for quests. ################################################## chicken_rescue = {'class_name': ChickenRescue(), 'i': 0, 'dialogs': {0: 'rescue_start', 1: 'rescue_complete'} } chicken_catch = {'class_name': ChickenCatch(), 'i': 0, 'dialogs': {0: 'catch_start', 1: 'catch_complete'} } quests = {'chicken_rescue': chicken_rescue, 'chicken_catch': chicken_catch } # Compile the above into game data dictionary. ################################################## game_data_dict = {'player_data': player_data, 'quest_data': quests, 'active_quests': {'chicken_rescue'}, 'current_map': None } return game_data_dict def load_all_gfx(directory, colorkey=c.WHITE, accept=('.png', '.jpg', '.bmp')): graphics = {} for pic in os.listdir(directory): name, ext = os.path.splitext(pic) if ext.lower() in accept: img = pg.image.load(os.path.join(directory, pic)) if img.get_alpha(): img = img.convert_alpha() else: img = img.convert() img.set_colorkey(colorkey) graphics[name] = img return graphics def load_all_tmx(directory, accept=('.tmx')): tmx = {} for file in os.listdir(directory): name, ext = os.path.splitext(file) if ext.lower() in accept: tmx[name] = os.path.join(directory, file) return tmx def load_all_fonts(directory, accept=('.ttf')): return load_all_tmx(directory, accept) def load_all_music(directory, accept=('.mp3', '.ogg')): return load_all_tmx(directory, accept) def load_all_sfx(directory, accept=('.wav','.ogg',)): effects = {} for fx in os.listdir(directory): name, ext = os.path.splitext(fx) if ext.lower() in accept: effects[name] = pg.mixer.Sound(os.path.join(directory, fx)) return effects class Camera: """ Class to handle world scrolling. Applying moves target rect position so that screen view is centered on source_rect. """ def __init__(self, map_width, map_height): self.state = pg.Rect(0, 0, map_width, map_height) def apply(self, target_rect): """ Offsets target rects position according to camera state. """ return target_rect.move(self.state.topleft) def update(self, source_rect): """ Updates camera to follow source_rect. """ x = - source_rect.center[0] + c.WINDOW_SIZE[0] // 2 y = - source_rect.center[1] + c.WINDOW_SIZE[1] // 2 position = pg.Vector2(self.state.topleft) position += (pg.Vector2((x, y)) - position) self.state.topleft = (int(position.x), int(position.y)) self.state.x = max(-(self.state.width - c.WINDOW_SIZE[0]), min(0, self.state.x)) self.state.y = max(-(self.state.height - c.WINDOW_SIZE[1]), min(0, self.state.y)) class Portal: """ Used for storing the transportation points between maps. """ def __init__(self, name, x, y, sound): self.name = name self.rect = pg.Rect(x, y, c.TILE_WIDTH, c.TILE_WIDTH) self.sound = sound class Dialogue: """ Class for storing dialogues and info needed to initiate them in the right time in the right place. (Place assigned in Tiled.) """ def __init__(self, name, x, y, properties): self.name = name self.rect = pg.Rect(x, y, c.TILE_WIDTH, c.TILE_WIDTH) self.dict = properties class Quest: def __init__(self): self.active = True self.completed = False self.name = None def open(self, game_data): self.game_data = game_data pass def update(self): pass def deactivate(self): pass class ChickenRescue(Quest): def __init__(self): super().__init__() self.name = 'chicken_rescue' self.chickens_to_rescue = 3 def open(self, game_data): game_data['player_data']['chickens']['show'] = True game_data['player_data']['chickens']['max'] = self.chickens_to_rescue if game_data['current_map'] == c.MYSTERIOUS_CAVE: game_data['player_data']['chickens']['catchable'] = True game_data['player_data']['chickens']['rescue'] = True self.game_data = game_data def update(self): if not self.completed: if (self.game_data['player_data']['chickens']['amount'] == self.chickens_to_rescue): self.completed = True self.game_data['quest_data'][self.name]['i'] = 1 def deactivate(self): self.active = False self.game_data['player_data']['chickens']['catchable'] = False self.game_data['player_data']['chickens']['rescue'] = False self.game_data['player_data']['chickens']['show'] = False self.game_data['player_data']['chickens']['amount'] = 0 # TODO Is this where the chicken catch will begin? #self.game_data['active_quests'].add('chicken_catch') class ChickenCatch(Quest): def __init__(self): super().__init__() self.name = 'chicken_catch' self.chickens_to_catch = 23 def open(self, game_data): game_data['player_data']['chickens']['show'] = True game_data['player_data']['chickens']['max'] = self.chickens_to_catch if game_data['current_map'] == c.SANDY_COVE: game_data['player_data']['chickens']['catchable'] = True game_data['player_data']['chickens']['catch'] = True self.game_data = game_data def update(self): if not self.completed: if (self.game_data['player_data']['chickens']['amount'] == self.chickens_to_catch): self.completed = True self.game_data['quest_data'][self.name]['i'] = 1 def deactivate(self): self.active = False self.game_data['player_data']['chickens']['catchable'] = False self.game_data['player_data']['chickens']['catch'] = False self.game_data['player_data']['chickens']['show'] = False self.game_data['player_data']['catched_chickens'].clear() self.game_data['player_data']['chickens']['amount'] = 0
quest/tools.py
import pygame as pg import os import constants as c class GameStatesManager: """ Control class for managing game states. """ def __init__(self): self.state_dict = {} self.state_name = None self.state = None def setup(self, state_dict, start_state): """ Given a dictionary of states and a state to start in, builds the self.state_dict. """ self.state_dict = state_dict self.state_name = start_state self.state = self.state_dict[self.state_name] self.set_music() def update(self, window, keys, dt, events): """ Checks if a state is done. Changes state if necessary and state.update is called. """ if self.state.done: self.flip_state() self.state.update(window, keys, dt, events) def flip_state(self): """ Changes to a new state and performs clean_up for exiting state and start_up for new state. (Most importantly passing on game data.) """ previous, self.state_name = self.state_name, self.state.next previous_music = self.state.music_title game_data = self.state.clean_up() self.state = self.state_dict[self.state_name] self.state.previous = previous self.state.previous_music = previous_music self.state.start_up(game_data) self.set_music() def set_music(self): """ Play correct music for the state. """ if self.state.music_title == self.state.previous_music: pass elif self.state.music: pg.mixer.music.load(self.state.music) pg.mixer.music.set_volume(self.state.volume) pg.mixer.music.play(-1) class State: """ Template class for all game states to inherit from. """ def __init__(self): self.done = False self.game_data = None self.next = None self.previous = 'start' def start_up(self, game_data): self.game_data = game_data def clean_up(self): self.done = False return self.game_data def update(self, window, keys, dt, events): """ Update method for state. Must be overrided in children. """ pass def create_game_data_dict(): """ Creates a dictionary of game data to be carried between states and for save game functionality. """ # Items that player has collected and is carrying. ################################################## player_data = {'gold': 0, 'chickens': {'show': False, 'amount': 0, 'max': 0, 'catchable': False, 'rescue': False, 'catch': False}, 'found_items': set(), 'catched_chickens': set(), 'hearts': 0 } # Data for quests. ################################################## chicken_rescue = {'class_name': ChickenRescue(), 'i': 0, 'dialogs': {0: 'rescue_start', 1: 'rescue_complete'} } chicken_catch = {'class_name': ChickenCatch(), 'i': 0, 'dialogs': {0: 'catch_start', 1: 'catch_complete'} } quests = {'chicken_rescue': chicken_rescue, 'chicken_catch': chicken_catch } # Compile the above into game data dictionary. ################################################## game_data_dict = {'player_data': player_data, 'quest_data': quests, 'active_quests': {'chicken_rescue'}, 'current_map': None } return game_data_dict def load_all_gfx(directory, colorkey=c.WHITE, accept=('.png', '.jpg', '.bmp')): graphics = {} for pic in os.listdir(directory): name, ext = os.path.splitext(pic) if ext.lower() in accept: img = pg.image.load(os.path.join(directory, pic)) if img.get_alpha(): img = img.convert_alpha() else: img = img.convert() img.set_colorkey(colorkey) graphics[name] = img return graphics def load_all_tmx(directory, accept=('.tmx')): tmx = {} for file in os.listdir(directory): name, ext = os.path.splitext(file) if ext.lower() in accept: tmx[name] = os.path.join(directory, file) return tmx def load_all_fonts(directory, accept=('.ttf')): return load_all_tmx(directory, accept) def load_all_music(directory, accept=('.mp3', '.ogg')): return load_all_tmx(directory, accept) def load_all_sfx(directory, accept=('.wav','.ogg',)): effects = {} for fx in os.listdir(directory): name, ext = os.path.splitext(fx) if ext.lower() in accept: effects[name] = pg.mixer.Sound(os.path.join(directory, fx)) return effects class Camera: """ Class to handle world scrolling. Applying moves target rect position so that screen view is centered on source_rect. """ def __init__(self, map_width, map_height): self.state = pg.Rect(0, 0, map_width, map_height) def apply(self, target_rect): """ Offsets target rects position according to camera state. """ return target_rect.move(self.state.topleft) def update(self, source_rect): """ Updates camera to follow source_rect. """ x = - source_rect.center[0] + c.WINDOW_SIZE[0] // 2 y = - source_rect.center[1] + c.WINDOW_SIZE[1] // 2 position = pg.Vector2(self.state.topleft) position += (pg.Vector2((x, y)) - position) self.state.topleft = (int(position.x), int(position.y)) self.state.x = max(-(self.state.width - c.WINDOW_SIZE[0]), min(0, self.state.x)) self.state.y = max(-(self.state.height - c.WINDOW_SIZE[1]), min(0, self.state.y)) class Portal: """ Used for storing the transportation points between maps. """ def __init__(self, name, x, y, sound): self.name = name self.rect = pg.Rect(x, y, c.TILE_WIDTH, c.TILE_WIDTH) self.sound = sound class Dialogue: """ Class for storing dialogues and info needed to initiate them in the right time in the right place. (Place assigned in Tiled.) """ def __init__(self, name, x, y, properties): self.name = name self.rect = pg.Rect(x, y, c.TILE_WIDTH, c.TILE_WIDTH) self.dict = properties class Quest: def __init__(self): self.active = True self.completed = False self.name = None def open(self, game_data): self.game_data = game_data pass def update(self): pass def deactivate(self): pass class ChickenRescue(Quest): def __init__(self): super().__init__() self.name = 'chicken_rescue' self.chickens_to_rescue = 3 def open(self, game_data): game_data['player_data']['chickens']['show'] = True game_data['player_data']['chickens']['max'] = self.chickens_to_rescue if game_data['current_map'] == c.MYSTERIOUS_CAVE: game_data['player_data']['chickens']['catchable'] = True game_data['player_data']['chickens']['rescue'] = True self.game_data = game_data def update(self): if not self.completed: if (self.game_data['player_data']['chickens']['amount'] == self.chickens_to_rescue): self.completed = True self.game_data['quest_data'][self.name]['i'] = 1 def deactivate(self): self.active = False self.game_data['player_data']['chickens']['catchable'] = False self.game_data['player_data']['chickens']['rescue'] = False self.game_data['player_data']['chickens']['show'] = False self.game_data['player_data']['chickens']['amount'] = 0 # TODO Is this where the chicken catch will begin? #self.game_data['active_quests'].add('chicken_catch') class ChickenCatch(Quest): def __init__(self): super().__init__() self.name = 'chicken_catch' self.chickens_to_catch = 23 def open(self, game_data): game_data['player_data']['chickens']['show'] = True game_data['player_data']['chickens']['max'] = self.chickens_to_catch if game_data['current_map'] == c.SANDY_COVE: game_data['player_data']['chickens']['catchable'] = True game_data['player_data']['chickens']['catch'] = True self.game_data = game_data def update(self): if not self.completed: if (self.game_data['player_data']['chickens']['amount'] == self.chickens_to_catch): self.completed = True self.game_data['quest_data'][self.name]['i'] = 1 def deactivate(self): self.active = False self.game_data['player_data']['chickens']['catchable'] = False self.game_data['player_data']['chickens']['catch'] = False self.game_data['player_data']['chickens']['show'] = False self.game_data['player_data']['catched_chickens'].clear() self.game_data['player_data']['chickens']['amount'] = 0
0.465873
0.250148
from pygraphblas import * from pygraphblas.types import BOOL from pyformlang.regular_expression import Regex class Graph: def __init__(self): self.labels_adj = dict() self.start_states = set() self.final_states = set() self.size = 0 def set(self, key, value): self.labels_adj[key] = value def copy(self): res = Graph() res.size = self.size for label in self.labels_adj: res.labels_adj[label] = self.labels_adj[label].dup() res.start_states = self.start_states.copy() res.final_states = self.final_states.copy() return res def read_from_txt(self, filename): input_file = open(filename) edges = input_file.readlines() input_file.close() size = 0 for edge in edges: v1, _, v2 = edge.split(' ') v1, v2 = int(v1), int(v2) size = max(size, v1, v2) size += 1 self.size = size for edge in edges: v1, label, v2 = edge.split(' ') v1, v2 = int(v1), int(v2) if label not in self.labels_adj: self.labels_adj[label] = Matrix.sparse(BOOL, size, size) self.labels_adj[label][v1, v2] = True self.start_states.add(v1) self.final_states.add(v2) def read_from_regex(self, filename): input_file = open(filename) regex = Regex(input_file.read().rstrip()) input_file.close() dfa = regex.to_epsilon_nfa().to_deterministic().minimize() size = len(dfa.states) self.size = size i = 0 state_number = dict() for state in dfa.states: state_number[state] = i i += 1 for v1, label, v2 in dfa._transition_function.get_edges(): self.labels_adj[label] = Matrix.sparse(BOOL, size, size) self.labels_adj[label][state_number[v1], state_number[v2]] = True for st in dfa.final_states: self.final_states.add(state_number[st]) self.start_states.add(state_number[dfa.start_state]) def transitive_closure_mul(self): res = Matrix.sparse(BOOL, self.size, self.size) for label in self.labels_adj: res += self.labels_adj[label] mtx = res.dup() for _ in range(self.size): tmp = res.nvals res += mtx @ res if tmp == res.nvals: break return res def transitive_closure_sq(self): res = Matrix.sparse(BOOL, self.size, self.size) for label in self.labels_adj: res += self.labels_adj[label] for _ in range(self.size): tmp = res.nvals res += res @ res if tmp == res.nvals: break return res def intersect(self, other): res = Graph() res.size = self.size * other.size for l in self.labels_adj: if l in other.labels_adj: res.labels_adj[l] = self.labels_adj[l].kronecker(other.labels_adj[l]) for i in self.start_states: for j in other.start_states: res.start_states.add(i * self.size + j) for i in self.final_states: for j in other.final_states: res.final_states.add(i * self.size + j) return res def print_pairs(self): for label in self.labels_adj: print(label, ": ", self.labels_adj[label].nvals) def reachable_from(self, from_vertices): res = self.transitive_closure_sq() for v in range(self.size): if v not in from_vertices: res.assign_row(v, Vector.sparse(BOOL, self.size).full(0)) return res def reachable_from_to(self, from_vertices, to_vertices): res = self.transitive_closure_sq() for v in range(self.size): if v not in from_vertices: res.assign_row(v, Vector.sparse(BOOL, self.size).full(0)) if v not in to_vertices: res.assign_col(v, Vector.sparse(BOOL, self.size).full(0)) return res
src/graph.py
from pygraphblas import * from pygraphblas.types import BOOL from pyformlang.regular_expression import Regex class Graph: def __init__(self): self.labels_adj = dict() self.start_states = set() self.final_states = set() self.size = 0 def set(self, key, value): self.labels_adj[key] = value def copy(self): res = Graph() res.size = self.size for label in self.labels_adj: res.labels_adj[label] = self.labels_adj[label].dup() res.start_states = self.start_states.copy() res.final_states = self.final_states.copy() return res def read_from_txt(self, filename): input_file = open(filename) edges = input_file.readlines() input_file.close() size = 0 for edge in edges: v1, _, v2 = edge.split(' ') v1, v2 = int(v1), int(v2) size = max(size, v1, v2) size += 1 self.size = size for edge in edges: v1, label, v2 = edge.split(' ') v1, v2 = int(v1), int(v2) if label not in self.labels_adj: self.labels_adj[label] = Matrix.sparse(BOOL, size, size) self.labels_adj[label][v1, v2] = True self.start_states.add(v1) self.final_states.add(v2) def read_from_regex(self, filename): input_file = open(filename) regex = Regex(input_file.read().rstrip()) input_file.close() dfa = regex.to_epsilon_nfa().to_deterministic().minimize() size = len(dfa.states) self.size = size i = 0 state_number = dict() for state in dfa.states: state_number[state] = i i += 1 for v1, label, v2 in dfa._transition_function.get_edges(): self.labels_adj[label] = Matrix.sparse(BOOL, size, size) self.labels_adj[label][state_number[v1], state_number[v2]] = True for st in dfa.final_states: self.final_states.add(state_number[st]) self.start_states.add(state_number[dfa.start_state]) def transitive_closure_mul(self): res = Matrix.sparse(BOOL, self.size, self.size) for label in self.labels_adj: res += self.labels_adj[label] mtx = res.dup() for _ in range(self.size): tmp = res.nvals res += mtx @ res if tmp == res.nvals: break return res def transitive_closure_sq(self): res = Matrix.sparse(BOOL, self.size, self.size) for label in self.labels_adj: res += self.labels_adj[label] for _ in range(self.size): tmp = res.nvals res += res @ res if tmp == res.nvals: break return res def intersect(self, other): res = Graph() res.size = self.size * other.size for l in self.labels_adj: if l in other.labels_adj: res.labels_adj[l] = self.labels_adj[l].kronecker(other.labels_adj[l]) for i in self.start_states: for j in other.start_states: res.start_states.add(i * self.size + j) for i in self.final_states: for j in other.final_states: res.final_states.add(i * self.size + j) return res def print_pairs(self): for label in self.labels_adj: print(label, ": ", self.labels_adj[label].nvals) def reachable_from(self, from_vertices): res = self.transitive_closure_sq() for v in range(self.size): if v not in from_vertices: res.assign_row(v, Vector.sparse(BOOL, self.size).full(0)) return res def reachable_from_to(self, from_vertices, to_vertices): res = self.transitive_closure_sq() for v in range(self.size): if v not in from_vertices: res.assign_row(v, Vector.sparse(BOOL, self.size).full(0)) if v not in to_vertices: res.assign_col(v, Vector.sparse(BOOL, self.size).full(0)) return res
0.585812
0.387111
import itertools from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.ext.declarative import declared_attr from anthill.framework.db import db """ models.py features a basic, non-hierarchical, non-constrained RBAC data model, also known as a flat model -- Ref: http://csrc.nist.gov/rbac/sandhu-ferraiolo-kuhn-00.pdf +-----------------+ +-------------------+ +---------------+ | | | | | | | | | R o l e | | | | R o l e +----------+ Permission +----------+ Permission | | | | | | | +-----------------+ +-------------------+ +---------------+ +-----------------+ +-------------------+ +---------------+ | | | | | | | | | R o l e | | | | U s e r +----------+ Membership +----------+ R o l e | | | | | | | +-----------------+ +-------------------+ +---------------+ """ role_permission = db.Table( 'role_permission', db.metadata, db.Column('role_id', db.ForeignKey('role.id'), primary_key=True), db.Column('permission_id', db.ForeignKey('permission.id'), primary_key=True) ) role_membership = db.Table( 'role_membership', db.metadata, db.Column('role_id', db.ForeignKey('role.id'), primary_key=True), db.Column('user_id', db.ForeignKey('user.id'), primary_key=True) ) class UserMixin(db.Model): __abstract__ = True @declared_attr def roles(self): return db.relationship('Role', secondary=role_membership, backref='users') @declared_attr def perms(self): return association_proxy('roles', 'permissions') @property def permissions(self): return list(itertools.chain(*self.perms)) class Credential(db.Model): __tablename__ = 'credential' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.ForeignKey('user.id'), nullable=False, unique=False) credential = db.Column(db.String, nullable=False) credential_type_id = db.Column(db.ForeignKey('credential_type.id'), nullable=False) expiration_dt = db.Column(db.DateTime(timezone=True), nullable=False) user = db.relationship('User', backref='credential', cascade="all, delete-orphan", single_parent=True) def __repr__(self): return ("Credential(credential_type_id={0}, user_id={1})". format(self.credential_type_id, self.user_id)) class CredentialType(db.Model): __tablename__ = 'credential_type' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String, nullable=False) def __repr__(self): return "CredentialType(title={0})".format(self.title) class Domain(db.Model): __tablename__ = 'domain' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) def __repr__(self): return "Domain(id={0}, name={1})".format(self.id, self.name) class Action(db.Model): __tablename__ = 'action' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) def __repr__(self): return "Action(id={0}, name={1})".format(self.id, self.name) class Resource(db.Model): __tablename__ = 'resource' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) def __repr__(self): return "Resource(id={0}, name={1})".format(self.id, self.name) class Scope(db.Model): __tablename__ = 'scope' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) def __repr__(self): return "Scope(id={0}, name={1})".format(self.id, self.name) class Permission(db.Model): __tablename__ = 'permission' id = db.Column(db.Integer, primary_key=True) domain_id = db.Column(db.ForeignKey('domain.id'), nullable=True) action_id = db.Column(db.ForeignKey('action.id'), nullable=True) resource_id = db.Column(db.ForeignKey('resource.id'), nullable=True) domain = db.relationship('Domain', backref='permission') action = db.relationship('Action', backref='permission') resource = db.relationship('Resource', backref='permission') roles = db.relationship('Role', secondary=role_permission, backref='permissions') users = association_proxy('roles', 'users') def __repr__(self): return ("Permission(domain_id={0},action_id={1},resource_id={2})". format(self.domain_id, self.action_id, self.resource_id)) class Role(db.Model): __tablename__ = 'role' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100)) def __repr__(self): return "Role(title={0})".format(self.title)
auth/backends/db/models.py
import itertools from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.ext.declarative import declared_attr from anthill.framework.db import db """ models.py features a basic, non-hierarchical, non-constrained RBAC data model, also known as a flat model -- Ref: http://csrc.nist.gov/rbac/sandhu-ferraiolo-kuhn-00.pdf +-----------------+ +-------------------+ +---------------+ | | | | | | | | | R o l e | | | | R o l e +----------+ Permission +----------+ Permission | | | | | | | +-----------------+ +-------------------+ +---------------+ +-----------------+ +-------------------+ +---------------+ | | | | | | | | | R o l e | | | | U s e r +----------+ Membership +----------+ R o l e | | | | | | | +-----------------+ +-------------------+ +---------------+ """ role_permission = db.Table( 'role_permission', db.metadata, db.Column('role_id', db.ForeignKey('role.id'), primary_key=True), db.Column('permission_id', db.ForeignKey('permission.id'), primary_key=True) ) role_membership = db.Table( 'role_membership', db.metadata, db.Column('role_id', db.ForeignKey('role.id'), primary_key=True), db.Column('user_id', db.ForeignKey('user.id'), primary_key=True) ) class UserMixin(db.Model): __abstract__ = True @declared_attr def roles(self): return db.relationship('Role', secondary=role_membership, backref='users') @declared_attr def perms(self): return association_proxy('roles', 'permissions') @property def permissions(self): return list(itertools.chain(*self.perms)) class Credential(db.Model): __tablename__ = 'credential' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.ForeignKey('user.id'), nullable=False, unique=False) credential = db.Column(db.String, nullable=False) credential_type_id = db.Column(db.ForeignKey('credential_type.id'), nullable=False) expiration_dt = db.Column(db.DateTime(timezone=True), nullable=False) user = db.relationship('User', backref='credential', cascade="all, delete-orphan", single_parent=True) def __repr__(self): return ("Credential(credential_type_id={0}, user_id={1})". format(self.credential_type_id, self.user_id)) class CredentialType(db.Model): __tablename__ = 'credential_type' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String, nullable=False) def __repr__(self): return "CredentialType(title={0})".format(self.title) class Domain(db.Model): __tablename__ = 'domain' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) def __repr__(self): return "Domain(id={0}, name={1})".format(self.id, self.name) class Action(db.Model): __tablename__ = 'action' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) def __repr__(self): return "Action(id={0}, name={1})".format(self.id, self.name) class Resource(db.Model): __tablename__ = 'resource' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) def __repr__(self): return "Resource(id={0}, name={1})".format(self.id, self.name) class Scope(db.Model): __tablename__ = 'scope' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) def __repr__(self): return "Scope(id={0}, name={1})".format(self.id, self.name) class Permission(db.Model): __tablename__ = 'permission' id = db.Column(db.Integer, primary_key=True) domain_id = db.Column(db.ForeignKey('domain.id'), nullable=True) action_id = db.Column(db.ForeignKey('action.id'), nullable=True) resource_id = db.Column(db.ForeignKey('resource.id'), nullable=True) domain = db.relationship('Domain', backref='permission') action = db.relationship('Action', backref='permission') resource = db.relationship('Resource', backref='permission') roles = db.relationship('Role', secondary=role_permission, backref='permissions') users = association_proxy('roles', 'users') def __repr__(self): return ("Permission(domain_id={0},action_id={1},resource_id={2})". format(self.domain_id, self.action_id, self.resource_id)) class Role(db.Model): __tablename__ = 'role' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100)) def __repr__(self): return "Role(title={0})".format(self.title)
0.61832
0.20949
import re def getVisibleLength(text): # remove ansi escape sequences (coloring!) before getting the length ansi_escape = re.compile(r'(?:\x1b[^m]*m|\x0f)', re.UNICODE) return len(ansi_escape.sub('', text).decode('utf-8')) class Columnar(object): pos = 0 """The internal cursor""" headers = [] """Headers for data""" data = [] """Data rows""" widths = [] """Widths of data for display""" fillchars = [] """Fillchar for each column""" def __init__(self, data = [], headers = [], fillchars = []): """Construct object""" self.widths = [] self.data = data self.setHeaders(headers) self.setFillchars(fillchars) self.measureColumnWidths() def setHeaders(self, headers = []): self.headers = headers return self def setFillchars(self, fillchars = []): if len(fillchars) == 0: for i in range(len(self.headers)): # Default to spaces for each column fillchars.append(' ') self.fillchars = fillchars return self def render(self, do_print = True): print(self.renderHeaders()) if do_print: for row in self: print(row) else: output = '' for row in self: output += row.render() return output def renderHeaders(self): out = '' if len(self.headers) == 0: return out for i in range(len(self.widths)): header = self.headers[i] filler = (self.widths[i] - getVisibleLength(header)) * ' ' out += header + filler + ' ' return out def getWidths(self): return self.widths def getRows(self): return self.data def getRow(self, offset): row = ColumnarRow(self.data[offset], self.widths, self.fillchars) return row def addRow(self, rowData): self.data.append(rowData) self.measureColumnWidths() def measureColumnWidths(self): """Measure the widest entries in each column in the data and the headers""" for row in self.data: i = 0 for col in row: self._setColumnWidth(col, i) i = i + 1 i = 0 for col in self.headers: self._setColumnWidth(col, i) i = i + 1 def next(self): if self.pos >= len(self.data): raise StopIteration row = ColumnarRow(self.data[self.pos], self.widths, self.fillchars) self.pos = self.pos + 1 return row def _setColumnWidth(self, col, i): #length = getVisibleLength(col.encode('utf-8')) length = getVisibleLength(col) try: if length > self.widths[i]: self.widths[i] = length except IndexError: self.widths.insert(i, length) def __iter__(self): """Iterator protocol""" return self class ColumnarRow(object): widths = [] data = [] fillchars = [] def __init__(self, data = [], widths = [], fillchars = []): self.data = data self.widths = widths self.fillchars = fillchars def render(self): out = '' for i in range(len(self.widths)): try: fillchar = self.fillchars[i] except IndexError: # Default to space if not set fillchar = ' ' data = self.data[i] filler = (self.widths[i] - getVisibleLength(data)) * fillchar out += data + filler + ' ' return out def __str__(self): return self.render() def get(self, offset): try: itemValue = self.data[offset] except: return '' return itemValue def set(self, offset, value): self.data[offset] = value return self
qi/columnar.py
import re def getVisibleLength(text): # remove ansi escape sequences (coloring!) before getting the length ansi_escape = re.compile(r'(?:\x1b[^m]*m|\x0f)', re.UNICODE) return len(ansi_escape.sub('', text).decode('utf-8')) class Columnar(object): pos = 0 """The internal cursor""" headers = [] """Headers for data""" data = [] """Data rows""" widths = [] """Widths of data for display""" fillchars = [] """Fillchar for each column""" def __init__(self, data = [], headers = [], fillchars = []): """Construct object""" self.widths = [] self.data = data self.setHeaders(headers) self.setFillchars(fillchars) self.measureColumnWidths() def setHeaders(self, headers = []): self.headers = headers return self def setFillchars(self, fillchars = []): if len(fillchars) == 0: for i in range(len(self.headers)): # Default to spaces for each column fillchars.append(' ') self.fillchars = fillchars return self def render(self, do_print = True): print(self.renderHeaders()) if do_print: for row in self: print(row) else: output = '' for row in self: output += row.render() return output def renderHeaders(self): out = '' if len(self.headers) == 0: return out for i in range(len(self.widths)): header = self.headers[i] filler = (self.widths[i] - getVisibleLength(header)) * ' ' out += header + filler + ' ' return out def getWidths(self): return self.widths def getRows(self): return self.data def getRow(self, offset): row = ColumnarRow(self.data[offset], self.widths, self.fillchars) return row def addRow(self, rowData): self.data.append(rowData) self.measureColumnWidths() def measureColumnWidths(self): """Measure the widest entries in each column in the data and the headers""" for row in self.data: i = 0 for col in row: self._setColumnWidth(col, i) i = i + 1 i = 0 for col in self.headers: self._setColumnWidth(col, i) i = i + 1 def next(self): if self.pos >= len(self.data): raise StopIteration row = ColumnarRow(self.data[self.pos], self.widths, self.fillchars) self.pos = self.pos + 1 return row def _setColumnWidth(self, col, i): #length = getVisibleLength(col.encode('utf-8')) length = getVisibleLength(col) try: if length > self.widths[i]: self.widths[i] = length except IndexError: self.widths.insert(i, length) def __iter__(self): """Iterator protocol""" return self class ColumnarRow(object): widths = [] data = [] fillchars = [] def __init__(self, data = [], widths = [], fillchars = []): self.data = data self.widths = widths self.fillchars = fillchars def render(self): out = '' for i in range(len(self.widths)): try: fillchar = self.fillchars[i] except IndexError: # Default to space if not set fillchar = ' ' data = self.data[i] filler = (self.widths[i] - getVisibleLength(data)) * fillchar out += data + filler + ' ' return out def __str__(self): return self.render() def get(self, offset): try: itemValue = self.data[offset] except: return '' return itemValue def set(self, offset, value): self.data[offset] = value return self
0.444685
0.421611
from app import app, mongo from bson.json_util import dumps from bson.objectid import ObjectId from flask import jsonify, request from werkzeug.security import generate_password_hash, check_password_hash # Endpoint for creating new user @app.route('/add', methods=['POST']) def add_user(): _json = request.json _name = _json['name'] _email = _json['email'] _password = _json['<PASSWORD>'] # Validate the received values if _name and _email and _password and request.method == 'POST': # do not save password as a plain text _hashed_password = generate_password_hash(_password) # save details id = mongo.db.user.insert({ 'name': _name, 'email': _email, 'pwd': <PASSWORD> }) resp = jsonify('User added successfully!') resp.status_code = 200 return resp else: return not_found() # Endpoint to list all user @app.route('/users') def users(): users = mongo.db.user.find() resp = dumps(users) return resp # Endpoint to find a user @app.route('/user/<id>') def user(id): user = mongo.db.user.find_one({'_id': ObjectId(id)}) resp = dumps(user) return resp # Endpoint to update user @app.route('/update', methods=['PUT']) def update_user(): _json = request.json _id = _json['_id'] _name = _json['name'] _email = _json['email'] _password = _json['<PASSWORD>'] # validate the received values if _name and _email and _password and _id and request.method == 'PUT': # hash the password _hashed_password = generate_password_hash(_password) # save edits mongo.db.user.update_one({'_id': ObjectId(_id['$oid']) if '$oid' in _id else ObjectId(_id)}, {'$set': {'name': _name, 'email': _email, 'pwd': _<PASSWORD>}}) resp = jsonify('User updated successfully!') resp.status_code = 200 return resp else: return not_found() # Endpoint to delete user @app.route('/delete/<id>', methods=['DELETE']) def delete_user(id): mongo.db.user.delete_one({'_id': ObjectId(id)}) resp = jsonify('User deleted successfully!') resp.status_code = 200 return resp # 404 method to handle not found error @app.errorhandler(404) def not_found(error=None): message = { 'status': 404, 'message': 'Not Found: ' + request.url, } resp = jsonify(message) resp.status_code = 404 return resp # Run application if __name__ == '__main__': app.run()
main.py
from app import app, mongo from bson.json_util import dumps from bson.objectid import ObjectId from flask import jsonify, request from werkzeug.security import generate_password_hash, check_password_hash # Endpoint for creating new user @app.route('/add', methods=['POST']) def add_user(): _json = request.json _name = _json['name'] _email = _json['email'] _password = _json['<PASSWORD>'] # Validate the received values if _name and _email and _password and request.method == 'POST': # do not save password as a plain text _hashed_password = generate_password_hash(_password) # save details id = mongo.db.user.insert({ 'name': _name, 'email': _email, 'pwd': <PASSWORD> }) resp = jsonify('User added successfully!') resp.status_code = 200 return resp else: return not_found() # Endpoint to list all user @app.route('/users') def users(): users = mongo.db.user.find() resp = dumps(users) return resp # Endpoint to find a user @app.route('/user/<id>') def user(id): user = mongo.db.user.find_one({'_id': ObjectId(id)}) resp = dumps(user) return resp # Endpoint to update user @app.route('/update', methods=['PUT']) def update_user(): _json = request.json _id = _json['_id'] _name = _json['name'] _email = _json['email'] _password = _json['<PASSWORD>'] # validate the received values if _name and _email and _password and _id and request.method == 'PUT': # hash the password _hashed_password = generate_password_hash(_password) # save edits mongo.db.user.update_one({'_id': ObjectId(_id['$oid']) if '$oid' in _id else ObjectId(_id)}, {'$set': {'name': _name, 'email': _email, 'pwd': _<PASSWORD>}}) resp = jsonify('User updated successfully!') resp.status_code = 200 return resp else: return not_found() # Endpoint to delete user @app.route('/delete/<id>', methods=['DELETE']) def delete_user(id): mongo.db.user.delete_one({'_id': ObjectId(id)}) resp = jsonify('User deleted successfully!') resp.status_code = 200 return resp # 404 method to handle not found error @app.errorhandler(404) def not_found(error=None): message = { 'status': 404, 'message': 'Not Found: ' + request.url, } resp = jsonify(message) resp.status_code = 404 return resp # Run application if __name__ == '__main__': app.run()
0.326593
0.046747
import errno from pathlib import Path import stat from mock import patch, call, mock_open from pytest import raises import fake_super def assertSimilar(a, b): if a != b: raise AssertionError("Assertion failed:" " Value mismatch: %r (%s) != %r (%s)" % (a, type(a), b, type(b))) @patch('fake_super.secrets') @patch('fake_super.os.rename') @patch('fake_super.os.mknod') @patch('fake_super.os.lchown') def test_restore_chr(mock_lchown, mock_mknod, mock_rename, mock_secrets): mock_secrets.token_urlsafe.return_value = '9<PASSWORD>' fake_super.restore('name', { 'type': 'chr', 'mode': stat.S_IFCHR | 0o444, 'major': 10, 'minor': 20, 'owner': 123, 'group': 456 }) mock_mknod.assert_called_with( Path('.name.999999'), stat.S_IFCHR | 0o444, device=0xa14) mock_lchown.assert_called_with(Path('.name.999999'), 123, 456) mock_rename.assert_called_with(Path('.name.999999'), 'name') @patch('fake_super.secrets') @patch('fake_super.os') def test_restore_chr2(mock_os, mock_secrets): mock_secrets.token_urlsafe.return_value = '9<PASSWORD>' mock_os.mknod.side_effect = OSError(errno.EPERM, "Permission denied") with raises(SystemExit, match=r'mknod: Permission denied'): fake_super.restore('name', { 'type': 'chr', 'mode': stat.S_IFCHR | 0o444, 'major': 10, 'minor': 20, 'owner': 123, 'group': 456 }) @patch('fake_super.secrets') @patch('fake_super.os') def test_restore_chr3(mock_os, mock_secrets): mock_secrets.token_urlsafe.return_value = '999999' mock_os.rename.side_effect = OSError(errno.EPERM, "Permission denied") with raises(SystemExit, match=r'rename.*: Permission denied'): fake_super.restore('name', { 'type': 'chr', 'mode': stat.S_IFCHR | 0o444, 'major': 10, 'minor': 20, 'owner': 123, 'group': 456 }) @patch('fake_super.secrets') @patch('fake_super.os.rename') @patch('fake_super.os.symlink') @patch('fake_super.os.lchown') @patch('builtins.open', new_callable=mock_open, read_data='../some/path') def test_restore_lnk(mock_file, mock_lchown, mock_symlink, mock_rename, mock_secrets): mock_secrets.token_urlsafe.return_value = '999999' fake_super.restore('name', { 'type': 'lnk', 'mode': stat.S_IFCHR | 0o444, 'major': 10, 'minor': 20, 'owner': 123, 'group': 456 }) mock_file.assert_called_with('name', 'r') mock_symlink.assert_called_with('../some/path', Path('.name.999999')) mock_lchown.assert_called_with(Path('.name.999999'), 123, 456) mock_rename.assert_called_with(Path('.name.999999'), 'name') @patch('fake_super.secrets') @patch('fake_super.os') @patch('builtins.open', new_callable=mock_open, read_data='../some/path') def test_restore_lnk2(mock_file, mock_os, mock_secrets): mock_secrets.token_urlsafe.return_value = '999999' mock_os.symlink.side_effect = OSError(errno.EPERM, "Permission denied") with raises(SystemExit, match=r'symlink: Permission denied'): fake_super.restore('name', { 'type': 'lnk', 'mode': stat.S_IFLNK | 0o444, 'major': 0, 'minor': 0, 'owner': 123, 'group': 456 }) @patch('fake_super.secrets') @patch('fake_super.os') @patch('builtins.open') def test_restore_lnk3(mock_file, mock_os, mock_secrets): mock_secrets.token_urlsafe.return_value = '999999' mock_file.side_effect = OSError(errno.EPERM, "Permission denied") with raises(SystemExit, match=r'name: open/read: Permission denied'): fake_super.restore('name', { 'type': 'lnk', 'mode': stat.S_IFLNK | 0o444, 'major': 0, 'minor': 0, 'owner': 123, 'group': 456 }) @patch('fake_super.secrets') @patch('fake_super.os') @patch('builtins.open', new_callable=mock_open, read_data='../some/path') def test_restore_lnk4(mock_file, mock_os, mock_secrets): mock_secrets.token_urlsafe.return_value = '999999' mock_os.rename.side_effect = OSError(errno.EPERM, "Permission denied") with raises(SystemExit, match=r'rename.*: Permission denied'): fake_super.restore('name', { 'type': 'lnk', 'mode': stat.S_IFLNK | 0o444, 'major': 0, 'minor': 0, 'owner': 123, 'group': 456 }) mock_file.assert_called_with('name', 'r') # The PosixPath argument is mangled by pytest assert mock_os.symlink.call_args.args[0] == '../some/path' assert mock_os.lchown.call_args.args[1:] == (123, 456) @patch('fake_super.os') def test_restore_reg(mock_os): fake_super.restore('/file/name', { 'type': 'reg', 'perms': 0o4444, 'owner': 123, 'group': 456 }) assertSimilar(mock_os.mock_calls, [ call.lchown('/file/name', 123, 456), call.chmod('/file/name', 0o4444) ]) @patch('fake_super.os') def test_restore_reg2(mock_os): mock_os.chmod.side_effect = OSError(errno.EPERM, "Permission denied") with raises(SystemExit, match=r'^/dir/name: chmod: Permission denied'): fake_super.restore('/dir/name', { 'type': 'dir', 'perms': 0o4444, 'owner': 123, 'group': 456 }) def test_restore_unknown(): with raises(SystemExit, match=r"^/file/name: Don't know how to create whiteout entry"): fake_super.restore('/file/name', { 'type': 'wht', 'perms': 0o4444, 'owner': 123, 'group': 456 }) @patch('fake_super.os') def test_restore_key(mock_os): with raises(KeyError, match=r"^'perms'$"): fake_super.restore('/file/name', { 'type': 'reg', 'mode': 0o4444, 'owner': 123, 'group': 456 }) @patch('fake_super.os') def test_restore_fail(mock_os): mock_os.lchown.side_effect = OSError(errno.EPERM, "Permission denied") with raises(SystemExit, match=r'^/file/name: chown: Permission denied'): fake_super.restore('/file/name', { 'type': 'reg', 'perms': 0o4444, 'owner': 123, 'group': 456 })
tests/test_30_restore.py
import errno from pathlib import Path import stat from mock import patch, call, mock_open from pytest import raises import fake_super def assertSimilar(a, b): if a != b: raise AssertionError("Assertion failed:" " Value mismatch: %r (%s) != %r (%s)" % (a, type(a), b, type(b))) @patch('fake_super.secrets') @patch('fake_super.os.rename') @patch('fake_super.os.mknod') @patch('fake_super.os.lchown') def test_restore_chr(mock_lchown, mock_mknod, mock_rename, mock_secrets): mock_secrets.token_urlsafe.return_value = '9<PASSWORD>' fake_super.restore('name', { 'type': 'chr', 'mode': stat.S_IFCHR | 0o444, 'major': 10, 'minor': 20, 'owner': 123, 'group': 456 }) mock_mknod.assert_called_with( Path('.name.999999'), stat.S_IFCHR | 0o444, device=0xa14) mock_lchown.assert_called_with(Path('.name.999999'), 123, 456) mock_rename.assert_called_with(Path('.name.999999'), 'name') @patch('fake_super.secrets') @patch('fake_super.os') def test_restore_chr2(mock_os, mock_secrets): mock_secrets.token_urlsafe.return_value = '9<PASSWORD>' mock_os.mknod.side_effect = OSError(errno.EPERM, "Permission denied") with raises(SystemExit, match=r'mknod: Permission denied'): fake_super.restore('name', { 'type': 'chr', 'mode': stat.S_IFCHR | 0o444, 'major': 10, 'minor': 20, 'owner': 123, 'group': 456 }) @patch('fake_super.secrets') @patch('fake_super.os') def test_restore_chr3(mock_os, mock_secrets): mock_secrets.token_urlsafe.return_value = '999999' mock_os.rename.side_effect = OSError(errno.EPERM, "Permission denied") with raises(SystemExit, match=r'rename.*: Permission denied'): fake_super.restore('name', { 'type': 'chr', 'mode': stat.S_IFCHR | 0o444, 'major': 10, 'minor': 20, 'owner': 123, 'group': 456 }) @patch('fake_super.secrets') @patch('fake_super.os.rename') @patch('fake_super.os.symlink') @patch('fake_super.os.lchown') @patch('builtins.open', new_callable=mock_open, read_data='../some/path') def test_restore_lnk(mock_file, mock_lchown, mock_symlink, mock_rename, mock_secrets): mock_secrets.token_urlsafe.return_value = '999999' fake_super.restore('name', { 'type': 'lnk', 'mode': stat.S_IFCHR | 0o444, 'major': 10, 'minor': 20, 'owner': 123, 'group': 456 }) mock_file.assert_called_with('name', 'r') mock_symlink.assert_called_with('../some/path', Path('.name.999999')) mock_lchown.assert_called_with(Path('.name.999999'), 123, 456) mock_rename.assert_called_with(Path('.name.999999'), 'name') @patch('fake_super.secrets') @patch('fake_super.os') @patch('builtins.open', new_callable=mock_open, read_data='../some/path') def test_restore_lnk2(mock_file, mock_os, mock_secrets): mock_secrets.token_urlsafe.return_value = '999999' mock_os.symlink.side_effect = OSError(errno.EPERM, "Permission denied") with raises(SystemExit, match=r'symlink: Permission denied'): fake_super.restore('name', { 'type': 'lnk', 'mode': stat.S_IFLNK | 0o444, 'major': 0, 'minor': 0, 'owner': 123, 'group': 456 }) @patch('fake_super.secrets') @patch('fake_super.os') @patch('builtins.open') def test_restore_lnk3(mock_file, mock_os, mock_secrets): mock_secrets.token_urlsafe.return_value = '999999' mock_file.side_effect = OSError(errno.EPERM, "Permission denied") with raises(SystemExit, match=r'name: open/read: Permission denied'): fake_super.restore('name', { 'type': 'lnk', 'mode': stat.S_IFLNK | 0o444, 'major': 0, 'minor': 0, 'owner': 123, 'group': 456 }) @patch('fake_super.secrets') @patch('fake_super.os') @patch('builtins.open', new_callable=mock_open, read_data='../some/path') def test_restore_lnk4(mock_file, mock_os, mock_secrets): mock_secrets.token_urlsafe.return_value = '999999' mock_os.rename.side_effect = OSError(errno.EPERM, "Permission denied") with raises(SystemExit, match=r'rename.*: Permission denied'): fake_super.restore('name', { 'type': 'lnk', 'mode': stat.S_IFLNK | 0o444, 'major': 0, 'minor': 0, 'owner': 123, 'group': 456 }) mock_file.assert_called_with('name', 'r') # The PosixPath argument is mangled by pytest assert mock_os.symlink.call_args.args[0] == '../some/path' assert mock_os.lchown.call_args.args[1:] == (123, 456) @patch('fake_super.os') def test_restore_reg(mock_os): fake_super.restore('/file/name', { 'type': 'reg', 'perms': 0o4444, 'owner': 123, 'group': 456 }) assertSimilar(mock_os.mock_calls, [ call.lchown('/file/name', 123, 456), call.chmod('/file/name', 0o4444) ]) @patch('fake_super.os') def test_restore_reg2(mock_os): mock_os.chmod.side_effect = OSError(errno.EPERM, "Permission denied") with raises(SystemExit, match=r'^/dir/name: chmod: Permission denied'): fake_super.restore('/dir/name', { 'type': 'dir', 'perms': 0o4444, 'owner': 123, 'group': 456 }) def test_restore_unknown(): with raises(SystemExit, match=r"^/file/name: Don't know how to create whiteout entry"): fake_super.restore('/file/name', { 'type': 'wht', 'perms': 0o4444, 'owner': 123, 'group': 456 }) @patch('fake_super.os') def test_restore_key(mock_os): with raises(KeyError, match=r"^'perms'$"): fake_super.restore('/file/name', { 'type': 'reg', 'mode': 0o4444, 'owner': 123, 'group': 456 }) @patch('fake_super.os') def test_restore_fail(mock_os): mock_os.lchown.side_effect = OSError(errno.EPERM, "Permission denied") with raises(SystemExit, match=r'^/file/name: chown: Permission denied'): fake_super.restore('/file/name', { 'type': 'reg', 'perms': 0o4444, 'owner': 123, 'group': 456 })
0.431345
0.118845
import datetime import os import unittest import buildscripts.ciconfig.evergreen as _evergreen # pylint: disable=missing-docstring,protected-access TEST_FILE_PATH = os.path.join(os.path.dirname(__file__), "evergreen.yml") class TestEvergreenProjectConfig(unittest.TestCase): """Unit tests for the Evergreen for the EvergreenProjectConfig class.""" @classmethod def setUpClass(cls): cls.conf = _evergreen.parse_evergreen_file(TEST_FILE_PATH, evergreen_binary=None) def test_invalid_path(self): invalid_path = "non_existing_file" with self.assertRaises(IOError): _evergreen.parse_evergreen_file(invalid_path, evergreen_binary=None) def test_list_tasks(self): self.assertEqual(6, len(self.conf.tasks)) self.assertEqual(6, len(self.conf.task_names)) self.assertIn("compile", self.conf.task_names) self.assertIn("passing_test", self.conf.task_names) self.assertIn("failing_test", self.conf.task_names) self.assertIn("timeout_test", self.conf.task_names) self.assertIn("no_lifecycle_task", self.conf.task_names) self.assertIn("resmoke_task", self.conf.task_names) def test_list_task_groups(self): self.assertEqual(1, len(self.conf.task_groups)) self.assertEqual(1, len(self.conf.task_group_names)) self.assertIn("tg_1", self.conf.task_group_names) def test_list_variants(self): self.assertEqual(4, len(self.conf.variants)) self.assertEqual(4, len(self.conf.variant_names)) self.assertIn("osx-108", self.conf.variant_names) self.assertIn("ubuntu", self.conf.variant_names) self.assertIn("debian", self.conf.variant_names) self.assertIn("amazon", self.conf.variant_names) def test_get_variant(self): variant = self.conf.get_variant("osx-108") self.assertIsNotNone(variant) self.assertEqual("osx-108", variant.name) def test_get_required_variants(self): variants = self.conf.get_required_variants() self.assertEqual(len(variants), 2) def test_list_distro_names(self): self.assertEqual(5, len(self.conf.distro_names)) self.assertIn("localtestdistro", self.conf.distro_names) self.assertIn("ubuntu1404-test", self.conf.distro_names) self.assertIn("pdp-11", self.conf.distro_names) self.assertIn("debian-stretch", self.conf.distro_names) self.assertIn("amazon", self.conf.distro_names) class TestTask(unittest.TestCase): # pylint: disable=too-many-public-methods """Unit tests for the Task class.""" def test_from_dict(self): task_dict = { "name": "compile", "depends_on": [], "commands": [{"func": "fetch source"}, {"func": "run a task that passes"}, {"func": "run a function with an arg", "vars": {"foobar": "TESTING: ONE"}}, {"func": "run a function with an arg", "vars": {"foobar": "TESTING: TWO"}}] } # yapf: disable task = _evergreen.Task(task_dict) self.assertEqual("compile", task.name) self.assertEqual([], task.depends_on) self.assertEqual(task_dict, task.raw) def test_resmoke_args(self): suite_and_task = "jstestfuzz" task_commands = [{"func": "run tests", "vars": {"resmoke_args": "--arg=val"}}] task_dict = {"name": suite_and_task, "commands": task_commands} task = _evergreen.Task(task_dict) self.assertEqual(f"--suites={suite_and_task} --arg=val", task.resmoke_args) def test_is_run_tests_task(self): task_commands = [{"func": "run tests", "vars": {"resmoke_args": "--suites=core"}}] task_dict = {"name": "jsCore", "commands": task_commands} task = _evergreen.Task(task_dict) self.assertTrue(task.is_run_tests_task) self.assertFalse(task.is_generate_resmoke_task) def test_run_tests_command(self): task_commands = [{"func": "run tests", "vars": {"resmoke_args": "--suites=core"}}] task_dict = {"name": "jsCore", "commands": task_commands} task = _evergreen.Task(task_dict) self.assertDictEqual(task_commands[0], task.run_tests_command) def test_run_tests_multiversion(self): require_multiversion_setup = True task_commands = [{"func": "do multiversion setup"}, {"func": "run tests", "vars": {"resmoke_args": "--suites=core"}}] task_dict = {"name": "jsCore", "commands": task_commands, "tags": ["multiversion"]} task = _evergreen.Task(task_dict) self.assertEqual(task.multiversion_setup_command, {"func": "do multiversion setup"}) self.assertEqual(require_multiversion_setup, task.require_multiversion_setup()) def test_run_tests_no_multiversion(self): task_commands = [{"func": "run tests", "vars": {"resmoke_args": "--suites=core"}}] task_dict = {"name": "jsCore", "commands": task_commands} task = _evergreen.Task(task_dict) self.assertFalse(task.require_multiversion_setup()) self.assertIsNone(task.multiversion_setup_command) def test_resmoke_args_gen(self): task_commands = [{ "func": "generate resmoke tasks", "vars": {"resmoke_args": "--installDir=/bin"} }] task_dict = {"name": "jsCore_gen", "commands": task_commands} task = _evergreen.Task(task_dict) self.assertEqual("--suites=jsCore --installDir=/bin", task.resmoke_args) def test_is_generate_resmoke_task(self): task_name = "core" task_commands = [{ "func": "generate resmoke tasks", "vars": {"task": task_name, "resmoke_args": "--installDir=/bin"} }] task_dict = {"name": "jsCore", "commands": task_commands} task = _evergreen.Task(task_dict) self.assertTrue(task.is_generate_resmoke_task) self.assertFalse(task.is_run_tests_task) def test_generate_resmoke_tasks_command(self): task_commands = [{ "func": "generate resmoke tasks", "vars": {"resmoke_args": "--installDir=/bin"} }] task_dict = {"name": "jsCore_gen", "commands": task_commands} task = _evergreen.Task(task_dict) self.assertDictEqual(task_commands[0], task.generate_resmoke_tasks_command) self.assertEqual("jsCore", task.generated_task_name) def test_resmoke_args_gen_with_suite(self): task_name = "jsCore" suite_name = "core" task_commands = [{ "func": "generate resmoke tasks", "vars": {"task": task_name, "suite": suite_name, "resmoke_args": "--installDir=/bin"} }] task_dict = {"name": "jsCore", "commands": task_commands} task = _evergreen.Task(task_dict) self.assertEqual("--suites=core --installDir=/bin", task.resmoke_args) def test_tags_with_no_tags(self): task_dict = { "name": "jsCore", "commands": [{ "func": "run tests", "vars": {"resmoke_args": "--suites=core"} }] } # yapf: disable task = _evergreen.Task(task_dict) self.assertEqual(0, len(task.tags)) def test_tags_with_tags(self): task_dict = { "name": "jsCore", "tags": ["tag 0", "tag 1", "tag 2"], "commands": [{ "func": "run tests", "vars": {"resmoke_args": "--suites=core"} }] } # yapf: disable task = _evergreen.Task(task_dict) tag_set = task.tags for tag in task_dict["tags"]: self.assertIn(tag, tag_set) self.assertEqual(len(task_dict["tags"]), len(tag_set)) def test_generate_resmoke_tasks_command_with_suite(self): task_name = "jsCore_gen" suite_name = "core" task_commands = [{ "func": "generate resmoke tasks", "vars": {"suite": suite_name, "resmoke_args": "--installDir=/bin"} }] task_dict = {"name": task_name, "commands": task_commands} task = _evergreen.Task(task_dict) self.assertDictEqual(task_commands[0], task.generate_resmoke_tasks_command) self.assertEqual("jsCore", task.generated_task_name) def test_gen_resmoke_multiversion(self): require_multiversion_setup = True task_name = "core" task_commands = [{ "func": "generate resmoke tasks", "vars": {"task": task_name, "resmoke_args": "--installDir=/bin"} }] task_dict = {"name": "jsCore", "commands": task_commands, "tags": ["multiversion"]} task = _evergreen.Task(task_dict) self.assertEqual(require_multiversion_setup, task.require_multiversion_setup()) def test_gen_resmoke_no_multiversion(self): task_name = "core" task_commands = [{ "func": "generate resmoke tasks", "vars": {"task": task_name, "resmoke_args": "--installDir=/bin"} }] task_dict = {"name": "jsCore", "commands": task_commands} task = _evergreen.Task(task_dict) self.assertFalse(task.require_multiversion_setup()) def test_get_vars_suite_name_generate_resmoke_tasks(self): task_name = "jsCore" suite_name = "core" task_commands = [{ "func": "generate resmoke tasks", "vars": {"task": task_name, "suite": suite_name, "resmoke_args": "--installDir=/bin"} }] task_dict = {"name": task_name, "commands": task_commands} task = _evergreen.Task(task_dict) self.assertEqual(suite_name, task.get_suite_name()) def test_get_suite_name_default_to_task_name(self): task_name = "concurrency_gen" no_gen_task_name = "concurrency" task_commands = [{"func": "generate resmoke tasks"}] task_dict = {"name": task_name, "commands": task_commands} task = _evergreen.Task(task_dict) self.assertEqual(no_gen_task_name, task.get_suite_name()) def test_generate_task_name_non_gen_tasks(self): task_name = "jsCore" task_commands = [{"func": "run tasks"}] task_dict = {"name": task_name, "commands": task_commands} task = _evergreen.Task(task_dict) with self.assertRaises(TypeError): task.generated_task_name # pylint: disable=pointless-statement def test_generate_task_name(self): task_name = "jsCore_gen" task_commands = [{"func": "generate resmoke tasks"}] task_dict = {"name": task_name, "commands": task_commands} task = _evergreen.Task(task_dict) self.assertEqual("jsCore", task.generated_task_name) class TestTaskGroup(unittest.TestCase): """Unit tests for the TaskGroup class.""" def test_from_list(self): task_group_dict = { "name": "my_group", "max_hosts": 3, "tasks": ["task1", "task2"], "setup_task": [], "teardown_task": [], "setup_group": [], "teardown_group": [], "timeout": [] } task_group = _evergreen.TaskGroup(task_group_dict) self.assertEqual("my_group", task_group.name) self.assertEqual(2, len(task_group.tasks)) self.assertEqual(task_group_dict, task_group.raw) class TestVariant(unittest.TestCase): """Unit tests for the Variant class.""" @classmethod def setUpClass(cls): cls.conf = _evergreen.parse_evergreen_file(TEST_FILE_PATH, evergreen_binary=None) def test_from_dict(self): task = _evergreen.Task({"name": "compile"}) tasks_map = {task.name: task} task_groups_map = {} variant_dict = { "name": "ubuntu", "display_name": "Ubuntu", "run_on": ["ubuntu1404-test"], "tasks": [{"name": "compile"}], } variant = _evergreen.Variant(variant_dict, tasks_map, task_groups_map) self.assertEqual("ubuntu", variant.name) self.assertEqual("Ubuntu", variant.display_name) self.assertEqual(["ubuntu1404-test"], variant.run_on) self.assertEqual(1, len(variant.tasks)) self.assertEqual("compile", variant.tasks[0].name) def test_display_name(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertEqual("Ubuntu", variant_ubuntu.display_name) variant_osx = self.conf.get_variant("osx-108") self.assertEqual("OSX", variant_osx.display_name) def test_batchtime(self): variant_ubuntu = self.conf.get_variant("ubuntu") batchtime = datetime.timedelta(minutes=1440) self.assertEqual(batchtime, variant_ubuntu.batchtime) variant_osx = self.conf.get_variant("osx-108") self.assertIsNone(variant_osx.batchtime) def test_is_required_variant(self): variant_debian = self.conf.get_variant("debian") is_required_variant = variant_debian.is_required_variant() self.assertEqual(is_required_variant, True) variant_ubuntu = self.conf.get_variant("ubuntu") is_required_variant = variant_ubuntu.is_required_variant() self.assertEqual(is_required_variant, False) def test_expansion(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertEqual("--param=value --ubuntu", variant_ubuntu.expansion("test_flags")) self.assertEqual(None, variant_ubuntu.expansion("not_a_valid_expansion_name")) def test_expansions(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertEqual({"test_flags": "--param=value --ubuntu"}, variant_ubuntu.expansions) def test_modules(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertEqual(["render-module"], variant_ubuntu.modules) variant_osx = self.conf.get_variant("osx-108") self.assertEqual([], variant_osx.modules) def test_run_on(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertEqual(["ubuntu1404-test"], variant_ubuntu.run_on) variant_osx = self.conf.get_variant("osx-108") self.assertEqual(["localtestdistro"], variant_osx.run_on) def test_distro_names(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertEqual(set(["ubuntu1404-test", "pdp-11"]), variant_ubuntu.distro_names) variant_osx = self.conf.get_variant("osx-108") self.assertEqual(set(["localtestdistro"]), variant_osx.distro_names) def test_test_flags(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertEqual("--param=value --ubuntu", variant_ubuntu.test_flags) variant_osx = self.conf.get_variant("osx-108") self.assertIsNone(variant_osx.test_flags) def test_num_jobs_available(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertIsNone(variant_ubuntu.num_jobs_available) variant_osx = self.conf.get_variant("osx-108") self.assertEqual(549, variant_osx.num_jobs_available) def test_variant_tasks(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertEqual(5, len(variant_ubuntu.tasks)) for task_name in [ "compile", "passing_test", "failing_test", "timeout_test", "resmoke_task" ]: task = variant_ubuntu.get_task(task_name) self.assertIsNotNone(task) self.assertEqual(variant_ubuntu, task.variant) self.assertIn(task_name, variant_ubuntu.task_names) # Check combined_resmoke_args when test_flags is set on the variant. resmoke_task = variant_ubuntu.get_task("resmoke_task") self.assertEqual("--suites=resmoke_task --storageEngine=wiredTiger --param=value --ubuntu", resmoke_task.combined_resmoke_args) # Check combined_resmoke_args when the task doesn't have resmoke_args. passing_task = variant_ubuntu.get_task("passing_test") self.assertEqual("--suites=passing_test --param=value --ubuntu", passing_task.combined_resmoke_args) # Check combined_resmoke_args when test_flags is not set on the variant. variant_debian = self.conf.get_variant("debian") resmoke_task = variant_debian.get_task("resmoke_task") self.assertEqual("--suites=resmoke_task --storageEngine=wiredTiger", resmoke_task.combined_resmoke_args) # Check for tasks included in task_groups variant_amazon = self.conf.get_variant("amazon") self.assertEqual(3, len(variant_amazon.tasks)) self.assertIn("compile", variant_amazon.task_names)
buildscripts/tests/ciconfig/test_evergreen.py
import datetime import os import unittest import buildscripts.ciconfig.evergreen as _evergreen # pylint: disable=missing-docstring,protected-access TEST_FILE_PATH = os.path.join(os.path.dirname(__file__), "evergreen.yml") class TestEvergreenProjectConfig(unittest.TestCase): """Unit tests for the Evergreen for the EvergreenProjectConfig class.""" @classmethod def setUpClass(cls): cls.conf = _evergreen.parse_evergreen_file(TEST_FILE_PATH, evergreen_binary=None) def test_invalid_path(self): invalid_path = "non_existing_file" with self.assertRaises(IOError): _evergreen.parse_evergreen_file(invalid_path, evergreen_binary=None) def test_list_tasks(self): self.assertEqual(6, len(self.conf.tasks)) self.assertEqual(6, len(self.conf.task_names)) self.assertIn("compile", self.conf.task_names) self.assertIn("passing_test", self.conf.task_names) self.assertIn("failing_test", self.conf.task_names) self.assertIn("timeout_test", self.conf.task_names) self.assertIn("no_lifecycle_task", self.conf.task_names) self.assertIn("resmoke_task", self.conf.task_names) def test_list_task_groups(self): self.assertEqual(1, len(self.conf.task_groups)) self.assertEqual(1, len(self.conf.task_group_names)) self.assertIn("tg_1", self.conf.task_group_names) def test_list_variants(self): self.assertEqual(4, len(self.conf.variants)) self.assertEqual(4, len(self.conf.variant_names)) self.assertIn("osx-108", self.conf.variant_names) self.assertIn("ubuntu", self.conf.variant_names) self.assertIn("debian", self.conf.variant_names) self.assertIn("amazon", self.conf.variant_names) def test_get_variant(self): variant = self.conf.get_variant("osx-108") self.assertIsNotNone(variant) self.assertEqual("osx-108", variant.name) def test_get_required_variants(self): variants = self.conf.get_required_variants() self.assertEqual(len(variants), 2) def test_list_distro_names(self): self.assertEqual(5, len(self.conf.distro_names)) self.assertIn("localtestdistro", self.conf.distro_names) self.assertIn("ubuntu1404-test", self.conf.distro_names) self.assertIn("pdp-11", self.conf.distro_names) self.assertIn("debian-stretch", self.conf.distro_names) self.assertIn("amazon", self.conf.distro_names) class TestTask(unittest.TestCase): # pylint: disable=too-many-public-methods """Unit tests for the Task class.""" def test_from_dict(self): task_dict = { "name": "compile", "depends_on": [], "commands": [{"func": "fetch source"}, {"func": "run a task that passes"}, {"func": "run a function with an arg", "vars": {"foobar": "TESTING: ONE"}}, {"func": "run a function with an arg", "vars": {"foobar": "TESTING: TWO"}}] } # yapf: disable task = _evergreen.Task(task_dict) self.assertEqual("compile", task.name) self.assertEqual([], task.depends_on) self.assertEqual(task_dict, task.raw) def test_resmoke_args(self): suite_and_task = "jstestfuzz" task_commands = [{"func": "run tests", "vars": {"resmoke_args": "--arg=val"}}] task_dict = {"name": suite_and_task, "commands": task_commands} task = _evergreen.Task(task_dict) self.assertEqual(f"--suites={suite_and_task} --arg=val", task.resmoke_args) def test_is_run_tests_task(self): task_commands = [{"func": "run tests", "vars": {"resmoke_args": "--suites=core"}}] task_dict = {"name": "jsCore", "commands": task_commands} task = _evergreen.Task(task_dict) self.assertTrue(task.is_run_tests_task) self.assertFalse(task.is_generate_resmoke_task) def test_run_tests_command(self): task_commands = [{"func": "run tests", "vars": {"resmoke_args": "--suites=core"}}] task_dict = {"name": "jsCore", "commands": task_commands} task = _evergreen.Task(task_dict) self.assertDictEqual(task_commands[0], task.run_tests_command) def test_run_tests_multiversion(self): require_multiversion_setup = True task_commands = [{"func": "do multiversion setup"}, {"func": "run tests", "vars": {"resmoke_args": "--suites=core"}}] task_dict = {"name": "jsCore", "commands": task_commands, "tags": ["multiversion"]} task = _evergreen.Task(task_dict) self.assertEqual(task.multiversion_setup_command, {"func": "do multiversion setup"}) self.assertEqual(require_multiversion_setup, task.require_multiversion_setup()) def test_run_tests_no_multiversion(self): task_commands = [{"func": "run tests", "vars": {"resmoke_args": "--suites=core"}}] task_dict = {"name": "jsCore", "commands": task_commands} task = _evergreen.Task(task_dict) self.assertFalse(task.require_multiversion_setup()) self.assertIsNone(task.multiversion_setup_command) def test_resmoke_args_gen(self): task_commands = [{ "func": "generate resmoke tasks", "vars": {"resmoke_args": "--installDir=/bin"} }] task_dict = {"name": "jsCore_gen", "commands": task_commands} task = _evergreen.Task(task_dict) self.assertEqual("--suites=jsCore --installDir=/bin", task.resmoke_args) def test_is_generate_resmoke_task(self): task_name = "core" task_commands = [{ "func": "generate resmoke tasks", "vars": {"task": task_name, "resmoke_args": "--installDir=/bin"} }] task_dict = {"name": "jsCore", "commands": task_commands} task = _evergreen.Task(task_dict) self.assertTrue(task.is_generate_resmoke_task) self.assertFalse(task.is_run_tests_task) def test_generate_resmoke_tasks_command(self): task_commands = [{ "func": "generate resmoke tasks", "vars": {"resmoke_args": "--installDir=/bin"} }] task_dict = {"name": "jsCore_gen", "commands": task_commands} task = _evergreen.Task(task_dict) self.assertDictEqual(task_commands[0], task.generate_resmoke_tasks_command) self.assertEqual("jsCore", task.generated_task_name) def test_resmoke_args_gen_with_suite(self): task_name = "jsCore" suite_name = "core" task_commands = [{ "func": "generate resmoke tasks", "vars": {"task": task_name, "suite": suite_name, "resmoke_args": "--installDir=/bin"} }] task_dict = {"name": "jsCore", "commands": task_commands} task = _evergreen.Task(task_dict) self.assertEqual("--suites=core --installDir=/bin", task.resmoke_args) def test_tags_with_no_tags(self): task_dict = { "name": "jsCore", "commands": [{ "func": "run tests", "vars": {"resmoke_args": "--suites=core"} }] } # yapf: disable task = _evergreen.Task(task_dict) self.assertEqual(0, len(task.tags)) def test_tags_with_tags(self): task_dict = { "name": "jsCore", "tags": ["tag 0", "tag 1", "tag 2"], "commands": [{ "func": "run tests", "vars": {"resmoke_args": "--suites=core"} }] } # yapf: disable task = _evergreen.Task(task_dict) tag_set = task.tags for tag in task_dict["tags"]: self.assertIn(tag, tag_set) self.assertEqual(len(task_dict["tags"]), len(tag_set)) def test_generate_resmoke_tasks_command_with_suite(self): task_name = "jsCore_gen" suite_name = "core" task_commands = [{ "func": "generate resmoke tasks", "vars": {"suite": suite_name, "resmoke_args": "--installDir=/bin"} }] task_dict = {"name": task_name, "commands": task_commands} task = _evergreen.Task(task_dict) self.assertDictEqual(task_commands[0], task.generate_resmoke_tasks_command) self.assertEqual("jsCore", task.generated_task_name) def test_gen_resmoke_multiversion(self): require_multiversion_setup = True task_name = "core" task_commands = [{ "func": "generate resmoke tasks", "vars": {"task": task_name, "resmoke_args": "--installDir=/bin"} }] task_dict = {"name": "jsCore", "commands": task_commands, "tags": ["multiversion"]} task = _evergreen.Task(task_dict) self.assertEqual(require_multiversion_setup, task.require_multiversion_setup()) def test_gen_resmoke_no_multiversion(self): task_name = "core" task_commands = [{ "func": "generate resmoke tasks", "vars": {"task": task_name, "resmoke_args": "--installDir=/bin"} }] task_dict = {"name": "jsCore", "commands": task_commands} task = _evergreen.Task(task_dict) self.assertFalse(task.require_multiversion_setup()) def test_get_vars_suite_name_generate_resmoke_tasks(self): task_name = "jsCore" suite_name = "core" task_commands = [{ "func": "generate resmoke tasks", "vars": {"task": task_name, "suite": suite_name, "resmoke_args": "--installDir=/bin"} }] task_dict = {"name": task_name, "commands": task_commands} task = _evergreen.Task(task_dict) self.assertEqual(suite_name, task.get_suite_name()) def test_get_suite_name_default_to_task_name(self): task_name = "concurrency_gen" no_gen_task_name = "concurrency" task_commands = [{"func": "generate resmoke tasks"}] task_dict = {"name": task_name, "commands": task_commands} task = _evergreen.Task(task_dict) self.assertEqual(no_gen_task_name, task.get_suite_name()) def test_generate_task_name_non_gen_tasks(self): task_name = "jsCore" task_commands = [{"func": "run tasks"}] task_dict = {"name": task_name, "commands": task_commands} task = _evergreen.Task(task_dict) with self.assertRaises(TypeError): task.generated_task_name # pylint: disable=pointless-statement def test_generate_task_name(self): task_name = "jsCore_gen" task_commands = [{"func": "generate resmoke tasks"}] task_dict = {"name": task_name, "commands": task_commands} task = _evergreen.Task(task_dict) self.assertEqual("jsCore", task.generated_task_name) class TestTaskGroup(unittest.TestCase): """Unit tests for the TaskGroup class.""" def test_from_list(self): task_group_dict = { "name": "my_group", "max_hosts": 3, "tasks": ["task1", "task2"], "setup_task": [], "teardown_task": [], "setup_group": [], "teardown_group": [], "timeout": [] } task_group = _evergreen.TaskGroup(task_group_dict) self.assertEqual("my_group", task_group.name) self.assertEqual(2, len(task_group.tasks)) self.assertEqual(task_group_dict, task_group.raw) class TestVariant(unittest.TestCase): """Unit tests for the Variant class.""" @classmethod def setUpClass(cls): cls.conf = _evergreen.parse_evergreen_file(TEST_FILE_PATH, evergreen_binary=None) def test_from_dict(self): task = _evergreen.Task({"name": "compile"}) tasks_map = {task.name: task} task_groups_map = {} variant_dict = { "name": "ubuntu", "display_name": "Ubuntu", "run_on": ["ubuntu1404-test"], "tasks": [{"name": "compile"}], } variant = _evergreen.Variant(variant_dict, tasks_map, task_groups_map) self.assertEqual("ubuntu", variant.name) self.assertEqual("Ubuntu", variant.display_name) self.assertEqual(["ubuntu1404-test"], variant.run_on) self.assertEqual(1, len(variant.tasks)) self.assertEqual("compile", variant.tasks[0].name) def test_display_name(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertEqual("Ubuntu", variant_ubuntu.display_name) variant_osx = self.conf.get_variant("osx-108") self.assertEqual("OSX", variant_osx.display_name) def test_batchtime(self): variant_ubuntu = self.conf.get_variant("ubuntu") batchtime = datetime.timedelta(minutes=1440) self.assertEqual(batchtime, variant_ubuntu.batchtime) variant_osx = self.conf.get_variant("osx-108") self.assertIsNone(variant_osx.batchtime) def test_is_required_variant(self): variant_debian = self.conf.get_variant("debian") is_required_variant = variant_debian.is_required_variant() self.assertEqual(is_required_variant, True) variant_ubuntu = self.conf.get_variant("ubuntu") is_required_variant = variant_ubuntu.is_required_variant() self.assertEqual(is_required_variant, False) def test_expansion(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertEqual("--param=value --ubuntu", variant_ubuntu.expansion("test_flags")) self.assertEqual(None, variant_ubuntu.expansion("not_a_valid_expansion_name")) def test_expansions(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertEqual({"test_flags": "--param=value --ubuntu"}, variant_ubuntu.expansions) def test_modules(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertEqual(["render-module"], variant_ubuntu.modules) variant_osx = self.conf.get_variant("osx-108") self.assertEqual([], variant_osx.modules) def test_run_on(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertEqual(["ubuntu1404-test"], variant_ubuntu.run_on) variant_osx = self.conf.get_variant("osx-108") self.assertEqual(["localtestdistro"], variant_osx.run_on) def test_distro_names(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertEqual(set(["ubuntu1404-test", "pdp-11"]), variant_ubuntu.distro_names) variant_osx = self.conf.get_variant("osx-108") self.assertEqual(set(["localtestdistro"]), variant_osx.distro_names) def test_test_flags(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertEqual("--param=value --ubuntu", variant_ubuntu.test_flags) variant_osx = self.conf.get_variant("osx-108") self.assertIsNone(variant_osx.test_flags) def test_num_jobs_available(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertIsNone(variant_ubuntu.num_jobs_available) variant_osx = self.conf.get_variant("osx-108") self.assertEqual(549, variant_osx.num_jobs_available) def test_variant_tasks(self): variant_ubuntu = self.conf.get_variant("ubuntu") self.assertEqual(5, len(variant_ubuntu.tasks)) for task_name in [ "compile", "passing_test", "failing_test", "timeout_test", "resmoke_task" ]: task = variant_ubuntu.get_task(task_name) self.assertIsNotNone(task) self.assertEqual(variant_ubuntu, task.variant) self.assertIn(task_name, variant_ubuntu.task_names) # Check combined_resmoke_args when test_flags is set on the variant. resmoke_task = variant_ubuntu.get_task("resmoke_task") self.assertEqual("--suites=resmoke_task --storageEngine=wiredTiger --param=value --ubuntu", resmoke_task.combined_resmoke_args) # Check combined_resmoke_args when the task doesn't have resmoke_args. passing_task = variant_ubuntu.get_task("passing_test") self.assertEqual("--suites=passing_test --param=value --ubuntu", passing_task.combined_resmoke_args) # Check combined_resmoke_args when test_flags is not set on the variant. variant_debian = self.conf.get_variant("debian") resmoke_task = variant_debian.get_task("resmoke_task") self.assertEqual("--suites=resmoke_task --storageEngine=wiredTiger", resmoke_task.combined_resmoke_args) # Check for tasks included in task_groups variant_amazon = self.conf.get_variant("amazon") self.assertEqual(3, len(variant_amazon.tasks)) self.assertIn("compile", variant_amazon.task_names)
0.589835
0.498047
import argparse import sys from biocode import utils def main(): parser = argparse.ArgumentParser( description='Report coverage gaps/dips from a samtools mpileup file') ## output file to be written parser.add_argument('-i', '--input_file', type=str, required=True, help='Path to an input mpileup file to be read' ) parser.add_argument('-o', '--output_file', type=str, required=False, help='Path to an output file to be created' ) parser.add_argument('-f', '--fasta_file', type=str, required=True, help='Reference fasta file, against which reads were aligned. Needed for low 3-prime end coverage' ) parser.add_argument('-mcd', '--min_coverage_depth', type=int, required=True, help='Min coverage depth, below which is reported' ) parser.add_argument('-mcs', '--min_coverage_span', type=int, required=False, help='Coverage window size, the avg of which is calculated for depth cutoff' ) parser.add_argument('-eb', '--end_buffer', type=int, required=False, default=0, help='If specified, gaps this far from either end of the molecule will not be reported.' ) args = parser.parse_args() # Check, this isn't ready yet: if args.min_coverage_span is not None: raise Exception("ERROR: Sorry, --min_coverage_span not yet implemented.") if args.output_file is None: out_fh = sys.stdout else: out_fh = open(args.output_file, 'wt') lengths = utils.fasta_sizes_from_file(args.fasta_file) stats = {'total_molecules': 0, 'total_bases': 0, 'depth_sum': 0} # In mpileup gaps are reported either with positions of coverage 0 OR omitted rows. depths = list() current_seq_id = None for line in open(args.input_file): contig, this_coord, base, depth = line.split("\t")[0:4] this_coord = int(this_coord) # new molecule if contig != current_seq_id: stats['total_molecules'] += 1 # purge the last one if current_seq_id != None: print_spans(current_seq_id, depths, args.min_coverage_depth, out_fh, stats, lengths, args.end_buffer) depths = [0] * lengths[contig] current_seq_id = contig depths[this_coord - 1] = depth print_spans(current_seq_id, depths, args.min_coverage_depth, out_fh, stats, lengths, args.end_buffer) print("INFO: Total molecules: {0}".format(stats['total_molecules']), file=sys.stderr) print("INFO: Total bases : {0}".format(stats['total_bases']), file=sys.stderr) print("INFO: Avg cov depth : {0}x".format(int(stats['depth_sum'] / stats['total_bases'])), file=sys.stderr) def print_spans(id, depths, cutoff, fh, stats, lengths, skip_end_dist): print("Skip end dist is: {0}".format(skip_end_dist)) i = 0 span_start = None in_span = False for depth in depths: stats['total_bases'] += 1 stats['depth_sum'] += int(depth) if int(depth) < cutoff: if in_span == False: in_span = True span_start = i else: if in_span == True: if skip_end_dist is not None and skip_end_dist > 0: print("DEBUG: ended first span within {0}, skipped end needs evaluating".format(id)) if i > skip_end_dist and i < (lengths[id] - skip_end_dist): print("\tDEBUG: span with i:{0} falls within range to include".format(id)) fh.write("{0}\t{1}\t{2}\t{3}\n".format(id, span_start + 1, i + 1, i - span_start)) else: print("\tDEBUG: span with i:{0} falls within range to exclude".format(id)) else: print("DEBUG: ended first span within {0}, skipped end doesn't need evaluating".format(id)) fh.write("{0}\t{1}\t{2}\t{3}\n".format(id, span_start + 1, i + 1, i - span_start)) in_span = False span_start = None i += 1 if __name__ == '__main__': main()
sam_bam/report_coverage_gaps.py
import argparse import sys from biocode import utils def main(): parser = argparse.ArgumentParser( description='Report coverage gaps/dips from a samtools mpileup file') ## output file to be written parser.add_argument('-i', '--input_file', type=str, required=True, help='Path to an input mpileup file to be read' ) parser.add_argument('-o', '--output_file', type=str, required=False, help='Path to an output file to be created' ) parser.add_argument('-f', '--fasta_file', type=str, required=True, help='Reference fasta file, against which reads were aligned. Needed for low 3-prime end coverage' ) parser.add_argument('-mcd', '--min_coverage_depth', type=int, required=True, help='Min coverage depth, below which is reported' ) parser.add_argument('-mcs', '--min_coverage_span', type=int, required=False, help='Coverage window size, the avg of which is calculated for depth cutoff' ) parser.add_argument('-eb', '--end_buffer', type=int, required=False, default=0, help='If specified, gaps this far from either end of the molecule will not be reported.' ) args = parser.parse_args() # Check, this isn't ready yet: if args.min_coverage_span is not None: raise Exception("ERROR: Sorry, --min_coverage_span not yet implemented.") if args.output_file is None: out_fh = sys.stdout else: out_fh = open(args.output_file, 'wt') lengths = utils.fasta_sizes_from_file(args.fasta_file) stats = {'total_molecules': 0, 'total_bases': 0, 'depth_sum': 0} # In mpileup gaps are reported either with positions of coverage 0 OR omitted rows. depths = list() current_seq_id = None for line in open(args.input_file): contig, this_coord, base, depth = line.split("\t")[0:4] this_coord = int(this_coord) # new molecule if contig != current_seq_id: stats['total_molecules'] += 1 # purge the last one if current_seq_id != None: print_spans(current_seq_id, depths, args.min_coverage_depth, out_fh, stats, lengths, args.end_buffer) depths = [0] * lengths[contig] current_seq_id = contig depths[this_coord - 1] = depth print_spans(current_seq_id, depths, args.min_coverage_depth, out_fh, stats, lengths, args.end_buffer) print("INFO: Total molecules: {0}".format(stats['total_molecules']), file=sys.stderr) print("INFO: Total bases : {0}".format(stats['total_bases']), file=sys.stderr) print("INFO: Avg cov depth : {0}x".format(int(stats['depth_sum'] / stats['total_bases'])), file=sys.stderr) def print_spans(id, depths, cutoff, fh, stats, lengths, skip_end_dist): print("Skip end dist is: {0}".format(skip_end_dist)) i = 0 span_start = None in_span = False for depth in depths: stats['total_bases'] += 1 stats['depth_sum'] += int(depth) if int(depth) < cutoff: if in_span == False: in_span = True span_start = i else: if in_span == True: if skip_end_dist is not None and skip_end_dist > 0: print("DEBUG: ended first span within {0}, skipped end needs evaluating".format(id)) if i > skip_end_dist and i < (lengths[id] - skip_end_dist): print("\tDEBUG: span with i:{0} falls within range to include".format(id)) fh.write("{0}\t{1}\t{2}\t{3}\n".format(id, span_start + 1, i + 1, i - span_start)) else: print("\tDEBUG: span with i:{0} falls within range to exclude".format(id)) else: print("DEBUG: ended first span within {0}, skipped end doesn't need evaluating".format(id)) fh.write("{0}\t{1}\t{2}\t{3}\n".format(id, span_start + 1, i + 1, i - span_start)) in_span = False span_start = None i += 1 if __name__ == '__main__': main()
0.285372
0.231603
import sqlalchemy as sql import inflection from sqlalchemy.types import INT, VARCHAR, FLOAT from sqlalchemy.sql import func as db_func from schools3.data.features.features_table import FeaturesTable from schools3.config.data import db_tables from schools3.config.data.features import features_config from schools3.config.data.features import absence_features_config from schools3.data.features.processors.impute_null_processor import ImputeNullProcessor from schools3.data.features.processors.composite_feature_processor import CompositeFeatureProcessor class AbsenceFeatures(FeaturesTable): def __init__(self): feature_cols = [ sql.Column('absence_rate',FLOAT), sql.Column('unexcused_absence_rate',FLOAT), sql.Column('absence_rate_perc',FLOAT) ] super(AbsenceFeatures, self).__init__( table_name=inflection.underscore(AbsenceFeatures.__name__), # converts AbsenceFeatures to 'absence_features' feature_cols=feature_cols, categorical_cols=[], post_features_processor=CompositeFeatureProcessor([ ImputeNullProcessor( col_val_dict= absence_features_config.fill_values ) ]) ) def get_data_query(self): all_snapshot= db_tables.clean_all_snapshots_table student_lookup= all_snapshot.c.student_lookup school_year= all_snapshot.c.school_year grade= all_snapshot.c.grade days_absent= all_snapshot.c.days_absent days_absent_unexcused= all_snapshot.c.days_absent_unexcused student_years = sql.select([ student_lookup, school_year.label('end_year'), grade, ]).distinct( student_lookup, school_year, grade ).where( grade >= 9 ).alias('student_years') student_absence= sql.select([ student_lookup, school_year, grade, days_absent, days_absent_unexcused ]).where( grade >= features_config.min_grade ).alias('student_absence') joined= sql.join( left= student_absence, right= student_years, onclause=sql.and_( student_absence.c.student_lookup == student_years.c.student_lookup, student_absence.c.school_year <= student_years.c.end_year ) ) absence_rates = sql.select([ joined.c.student_absence_student_lookup.label('student_lookup'), joined.c.student_years_end_year.label('school_year'), joined.c.student_years_grade.label('grade'), db_func.avg(joined.c.student_absence_days_absent).label('absence_rate'), db_func.avg(joined.c.student_absence_days_absent_unexcused).label('unexcused_absence_rate') ]).select_from( joined ).group_by( joined.c.student_absence_student_lookup.label('student_lookup'), joined.c.student_years_end_year.label('school_year'), joined.c.student_years_grade.label('grade') ).alias('absence_rates') return sql.select( [c for c in absence_rates.c] + [db_func.percent_rank().over( order_by=absence_rates.c.absence_rate, partition_by=[absence_rates.c.school_year, absence_rates.c.grade] ).label('absence_rate_perc')] )
schools3/data/features/absence_features.py
import sqlalchemy as sql import inflection from sqlalchemy.types import INT, VARCHAR, FLOAT from sqlalchemy.sql import func as db_func from schools3.data.features.features_table import FeaturesTable from schools3.config.data import db_tables from schools3.config.data.features import features_config from schools3.config.data.features import absence_features_config from schools3.data.features.processors.impute_null_processor import ImputeNullProcessor from schools3.data.features.processors.composite_feature_processor import CompositeFeatureProcessor class AbsenceFeatures(FeaturesTable): def __init__(self): feature_cols = [ sql.Column('absence_rate',FLOAT), sql.Column('unexcused_absence_rate',FLOAT), sql.Column('absence_rate_perc',FLOAT) ] super(AbsenceFeatures, self).__init__( table_name=inflection.underscore(AbsenceFeatures.__name__), # converts AbsenceFeatures to 'absence_features' feature_cols=feature_cols, categorical_cols=[], post_features_processor=CompositeFeatureProcessor([ ImputeNullProcessor( col_val_dict= absence_features_config.fill_values ) ]) ) def get_data_query(self): all_snapshot= db_tables.clean_all_snapshots_table student_lookup= all_snapshot.c.student_lookup school_year= all_snapshot.c.school_year grade= all_snapshot.c.grade days_absent= all_snapshot.c.days_absent days_absent_unexcused= all_snapshot.c.days_absent_unexcused student_years = sql.select([ student_lookup, school_year.label('end_year'), grade, ]).distinct( student_lookup, school_year, grade ).where( grade >= 9 ).alias('student_years') student_absence= sql.select([ student_lookup, school_year, grade, days_absent, days_absent_unexcused ]).where( grade >= features_config.min_grade ).alias('student_absence') joined= sql.join( left= student_absence, right= student_years, onclause=sql.and_( student_absence.c.student_lookup == student_years.c.student_lookup, student_absence.c.school_year <= student_years.c.end_year ) ) absence_rates = sql.select([ joined.c.student_absence_student_lookup.label('student_lookup'), joined.c.student_years_end_year.label('school_year'), joined.c.student_years_grade.label('grade'), db_func.avg(joined.c.student_absence_days_absent).label('absence_rate'), db_func.avg(joined.c.student_absence_days_absent_unexcused).label('unexcused_absence_rate') ]).select_from( joined ).group_by( joined.c.student_absence_student_lookup.label('student_lookup'), joined.c.student_years_end_year.label('school_year'), joined.c.student_years_grade.label('grade') ).alias('absence_rates') return sql.select( [c for c in absence_rates.c] + [db_func.percent_rank().over( order_by=absence_rates.c.absence_rate, partition_by=[absence_rates.c.school_year, absence_rates.c.grade] ).label('absence_rate_perc')] )
0.563498
0.200421
import itertools import regex as re import warnings from collections import namedtuple Match = namedtuple('Match', 'start end cls') MARKERS = [chr(x) for x in range(0x4DC0, 0x4DFF)] def generate_options(path: str = 'elisa_dnt/rules.ini') -> dict: colors = [ '#e3f2fd', '#bbdefb', '#90caf9', '#64b5f6', '#42a5f5', '#2196f3', '#1e88e5', '#1976d2', '#1565c0', '#0d47a1' ] options = {'colors': {'comb': 'background-color: #4caf50;' }, 'categories': ['comb']} with open(path) as i: for j, line in enumerate(map(lambda x: x.strip('\n'), i.readlines())): name, _ = line.split('=', 1) options['categories'].append(name) options['colors'][name] = f'background-color: {colors[j%len(colors)]};' options['categories'].append('emoji') options['colors']['emoji'] = f'background-color: {colors[(j+1)%len(colors)]};' return options def load_rules(rule_path: str = 'elisa_dnt/rules.ini', scheme: str = 'del') -> dict: rules = {} with open(rule_path) as i: for rule in map(lambda x: x.strip('\n'), i.readlines()): name, value = rule.split('=', 1) if scheme == "del": rules[name] = re.compile(u"( *{} *)".format(value)) else: rules[name] = re.compile(r"({})".format(value)) return rules def find(string: str, rules: dict, scheme='del') -> list: # matches = itertools.chain(*[(key, exp.finditer(string)) ]) matches = [(key, match) for key, exp in rules.items() for match in exp.finditer(string)] matches = [match for match in sorted(matches, key=lambda m: (m[-1].start(0), -(m[-1].end(0))))] merged_matches = [] for i, (name, match) in enumerate(matches): if i > 0 and merged_matches[-1].start <= match.start(0) < match.end(0) <= merged_matches[-1].end: continue elif i > 0 and ((match.start(0) <= merged_matches[-1].end) or (scheme == 'del' and match.start(0) <= merged_matches[-1].end + 1)): merged_matches[-1] = Match(merged_matches[-1].start, max(match.end(0), merged_matches[-1].end), 'comb') else: merged_matches.append(Match(match.start(0), match.end(0), name)) return merged_matches def mark(string: str, matches: list, scheme: str = "sub", ordered: bool = True) -> tuple: global MARKERS if scheme == "sub": modification = [] for i, (match, key) in enumerate(zip(matches, MARKERS)): start, end = match.start, match.end text = string[start:end] modification.append((text, key)) for value, key in sorted(modification, key=lambda x: (len(x[0]), x[0]), reverse=True): if ordered: string = string.replace(value, f"{key}") else: string = string.replace(value, MARKERS[0]) return string, [m[0] for m in modification], None elif scheme == "del": lead = False modification = [] segments = [] remain = string for i, match in enumerate(matches): start, end = match.start, match.end if start == 0: lead = True text = string[start:end] modification.append(text) if remain: segment, remain = remain.split(text, maxsplit=1) if segment: segments.append(segment) if remain: segments.append(remain) restore = [] i, j = 0, 0 curr = 0 while i < len(modification) and j < len(segments): if lead and (i == 0 or curr % 2 == 0): restore.append(modification[i]) i += 1 curr += 1 elif not lead and (j == 0 or curr % 2 == 0): restore.append(segments[j]) j += 1 curr += 1 elif not lead and curr % 2 == 1: restore.append(modification[i]) i += 1 curr += 1 elif lead and curr % 2 == 1: restore.append(segments[j]) j += 1 curr += 1 while i < len(modification): restore.append(modification[i]) i += 1 curr += 1 while j < len(segments): restore.append(segments[j]) j += 1 curr += 1 try: assert "".join(restore) == string, "".join(restore) except AssertionError as ae: print(string) print(matches) print(segments) print(modification) print(restore) print(ae) print() return segments, modification, lead def visual(string: str, matches: list, options: dict, rules: dict) -> str: def colorize(match, text): cls = match.cls if cls in options["categories"]: if "<" not in text and ">" not in text: return f"""<span class="{cls}" title="{cls}">{text}</span>""" else: text = text.replace("<", "&lt;") text = text.replace(">", "&gt;") return f"""<span class="{cls}" title="{cls}">{text}</span>""" else: return text res = string matched = set() for match in matches: start, end = match.start, match.end text = string[start:end] if text not in matched: res = res.replace(text, colorize(match, text)) matched.add(text) return res def split(corpus_path, corpus_output, ini_output, scheme: str, ref: str, rules: dict, ordered: bool=True): with open(corpus_path) as source, open(corpus_output, "w") as o_source, open(ini_output, "w") as o_source_ini: if ref == "": total_sents, total_matches, total_match_sents = 0, 0, 0 for src in source.readlines(): total_sents += 1 src = src.strip('\n') src_matches = find(src, rules, scheme) src_after, src_mod, src_lead = mark(src, src_matches, scheme=scheme, ordered=ordered) if scheme == "del": for seg in src_after: o_source.write(seg + "\n") else: o_source.write(src_after + "\n") if src_matches: total_match_sents += 1 total_matches += len(src_mod) if scheme == "del": if src_after: o_source_ini.write( ("YL" if src_lead and len(src_after) >= len(src_mod) else "YS" if src_lead else \ "NL" if not src_lead and len(src_after) > len(src_mod) else "NS" ) + "\t" + "\t".join(src_mod) + "\n") else: o_source_ini.write("EMPTY" + "\t" + "\t".join(src_mod) + "\n") else: o_source_ini.write('\t'.join(["SUB"] + src_mod) + "\n") else: o_source_ini.write("IGNORE\n") print(f"{total_matches} LI tokens found in {total_match_sents}/{total_sents} sentences {corpus_path}") else: assert scheme != "del", "ref is not required for del scheme!" src_lines = source.readlines() tgt_lines = open(ref).readlines() for src_line, tgt_line in zip(src_lines, tgt_lines): src_line = src_line.strip('\n') tgt_line = tgt_line.strip('\n') src_matches = find(src_line, rules, scheme) tgt_matches = find(tgt_line, rules, scheme) src_matches_text = [src_line[m.start(0):m.end(0)] for m in src_matches] tgt_matches_text = [tgt_line[m.start(0):m.end(0)] for m in tgt_matches] x_matches = list(set(src_matches_text).intersection(set(tgt_matches_text))) x_src_matches = [m for m in src_matches if src_line[m.start(0):m.end(0)] in x_matches] src_after, src_mod, src_lead = mark(src_line, x_src_matches, scheme=scheme, ordered=ordered) o_source.write(src_after + "\n") if x_matches: o_source_ini.write('\t'.join(["SUB"] + src_mod) + "\n") else: o_source_ini.write("IGNORE\n") def restore(dnt_path, ini_path, output, scheme="del", ordered:bool=True): global MARKERS with open(output, "w") as o, open(dnt_path) as i_source, open(ini_path) as i_source_ini: translations = list(map(lambda x: x.strip('\n'), i_source.readlines())) instructions = list(map(lambda x: x.strip('\n'), i_source_ini.readlines())) if scheme == "del": i = 0 j = 0 placeholder = [] while i < len(instructions) and j < len(translations): lead, *tokens = instructions[i].split('\t') if lead == "IGNORE": o.write(translations[j] + "\n") j += 1 i += 1 continue if lead == "EMPTY": o.write("".join(tokens) + "\n") i += 1 continue if lead == "YL": for token in tokens: placeholder.append(token) placeholder.append(translations[j]) j += 1 elif lead == "YS": for x, token in enumerate(tokens): placeholder.append(token) if x < len(tokens) - 1: placeholder.append(translations[j]) j += 1 if lead == "NL": for token in tokens: placeholder.append(translations[j]) placeholder.append(token) j += 1 placeholder.append(translations[j]) j += 1 elif lead == "NS": for token in tokens: placeholder.append(translations[j]) placeholder.append(token) j += 1 o.write("".join(placeholder) + "\n") placeholder = [] i += 1 else: for translation, instruction in zip(translations, instructions): flag, *segments = instruction.split('\t') if flag == "IGNORE": o.write(translation + '\n') continue new_translation = translation for char in translation: if char in MARKERS: if ord(char) - 0x4DC0 >= len(segments) or segments == []: warnings.warn("Wired source sentence: {}".format(translation), Warning) warnings.warn(" ".join(segments), Warning) continue if ordered: new_translation = new_translation.replace(char, segments[min(ord(char) - 0x4DC0, len(segments) - 1)]) else: new_translation = new_translation.replace(char, segments[0], 1) segments.pop(0) o.write(new_translation + '\n') if __name__ == "__main__": txt = """RT @jokateM: Utu humfanya mtu awe kipenzi cha watu,utu humfanya mtu awe kimbilio la watu,aliyekosa utu hana mvuto kwa watu. 🙏🏽❤ She writes [ar]: ملخص تغطية وكالة الانباء الرسمية لمظاهرات امس: مواطنين اعتدوا على الشرطة فاضطروها لاستخدام الغاز المسيل للدموع http://suna-sd.net/suna/showNews/-fJi7HGycvs26Azq7aG4mmjptp-NQZ_WndSuVb1-KMY/1 #الخرا ds.CRIME BE PART OF VODACOM SUCCESS: https://t.co/Wzo1EckNhe via @YouTube CEO wa @MeTL_Group, @moodewji akiwa katika majadiliano kwenye mkutano wa @africaceoforum unaofanyika Geneva, Switze... https://t.co/uBAXDYfmlQ @earadiofm: #MICHEZO Msanii na Mbunge wa Mikumi @ProfessorJayTz akiwa na <NAME> katika uwanja wa Taifa kushuhudia mechi kati ya...RT @earadiofm: #MICHEZO Msanii na Mbunge wa Mikumi @ProfessorJayTz akiwa na <NAME> katika uwanja wa Taifa kushuhudia mechi kati ya...@Youtube She writes [ar]: ملخص تغطية وكالة الانباء الرسمية لمظاهرات امس: مواطنين اعتدوا على الشرطة فاضطروها لاستخدام الغاز المسيل للدموع http://suna-sd.net/suna/showNews/-fJi7HGycvs26Azq7aG4mmjptp-NQZ_WndSuVb1-KMY/1 https://t.co/6fURhmguTF‬""" rules = load_rules('rules.ini', 'sub') options = generate_options('rules.ini') matches = find(txt, rules, 'sub') spans = [txt[m.start:m.end] for m in matches] print(spans) print(mark(txt, find(txt, rules, 'sub'), 'sub', ordered=False)) print(visual(txt, matches, options, rules))
elisa_dnt/utils.py
import itertools import regex as re import warnings from collections import namedtuple Match = namedtuple('Match', 'start end cls') MARKERS = [chr(x) for x in range(0x4DC0, 0x4DFF)] def generate_options(path: str = 'elisa_dnt/rules.ini') -> dict: colors = [ '#e3f2fd', '#bbdefb', '#90caf9', '#64b5f6', '#42a5f5', '#2196f3', '#1e88e5', '#1976d2', '#1565c0', '#0d47a1' ] options = {'colors': {'comb': 'background-color: #4caf50;' }, 'categories': ['comb']} with open(path) as i: for j, line in enumerate(map(lambda x: x.strip('\n'), i.readlines())): name, _ = line.split('=', 1) options['categories'].append(name) options['colors'][name] = f'background-color: {colors[j%len(colors)]};' options['categories'].append('emoji') options['colors']['emoji'] = f'background-color: {colors[(j+1)%len(colors)]};' return options def load_rules(rule_path: str = 'elisa_dnt/rules.ini', scheme: str = 'del') -> dict: rules = {} with open(rule_path) as i: for rule in map(lambda x: x.strip('\n'), i.readlines()): name, value = rule.split('=', 1) if scheme == "del": rules[name] = re.compile(u"( *{} *)".format(value)) else: rules[name] = re.compile(r"({})".format(value)) return rules def find(string: str, rules: dict, scheme='del') -> list: # matches = itertools.chain(*[(key, exp.finditer(string)) ]) matches = [(key, match) for key, exp in rules.items() for match in exp.finditer(string)] matches = [match for match in sorted(matches, key=lambda m: (m[-1].start(0), -(m[-1].end(0))))] merged_matches = [] for i, (name, match) in enumerate(matches): if i > 0 and merged_matches[-1].start <= match.start(0) < match.end(0) <= merged_matches[-1].end: continue elif i > 0 and ((match.start(0) <= merged_matches[-1].end) or (scheme == 'del' and match.start(0) <= merged_matches[-1].end + 1)): merged_matches[-1] = Match(merged_matches[-1].start, max(match.end(0), merged_matches[-1].end), 'comb') else: merged_matches.append(Match(match.start(0), match.end(0), name)) return merged_matches def mark(string: str, matches: list, scheme: str = "sub", ordered: bool = True) -> tuple: global MARKERS if scheme == "sub": modification = [] for i, (match, key) in enumerate(zip(matches, MARKERS)): start, end = match.start, match.end text = string[start:end] modification.append((text, key)) for value, key in sorted(modification, key=lambda x: (len(x[0]), x[0]), reverse=True): if ordered: string = string.replace(value, f"{key}") else: string = string.replace(value, MARKERS[0]) return string, [m[0] for m in modification], None elif scheme == "del": lead = False modification = [] segments = [] remain = string for i, match in enumerate(matches): start, end = match.start, match.end if start == 0: lead = True text = string[start:end] modification.append(text) if remain: segment, remain = remain.split(text, maxsplit=1) if segment: segments.append(segment) if remain: segments.append(remain) restore = [] i, j = 0, 0 curr = 0 while i < len(modification) and j < len(segments): if lead and (i == 0 or curr % 2 == 0): restore.append(modification[i]) i += 1 curr += 1 elif not lead and (j == 0 or curr % 2 == 0): restore.append(segments[j]) j += 1 curr += 1 elif not lead and curr % 2 == 1: restore.append(modification[i]) i += 1 curr += 1 elif lead and curr % 2 == 1: restore.append(segments[j]) j += 1 curr += 1 while i < len(modification): restore.append(modification[i]) i += 1 curr += 1 while j < len(segments): restore.append(segments[j]) j += 1 curr += 1 try: assert "".join(restore) == string, "".join(restore) except AssertionError as ae: print(string) print(matches) print(segments) print(modification) print(restore) print(ae) print() return segments, modification, lead def visual(string: str, matches: list, options: dict, rules: dict) -> str: def colorize(match, text): cls = match.cls if cls in options["categories"]: if "<" not in text and ">" not in text: return f"""<span class="{cls}" title="{cls}">{text}</span>""" else: text = text.replace("<", "&lt;") text = text.replace(">", "&gt;") return f"""<span class="{cls}" title="{cls}">{text}</span>""" else: return text res = string matched = set() for match in matches: start, end = match.start, match.end text = string[start:end] if text not in matched: res = res.replace(text, colorize(match, text)) matched.add(text) return res def split(corpus_path, corpus_output, ini_output, scheme: str, ref: str, rules: dict, ordered: bool=True): with open(corpus_path) as source, open(corpus_output, "w") as o_source, open(ini_output, "w") as o_source_ini: if ref == "": total_sents, total_matches, total_match_sents = 0, 0, 0 for src in source.readlines(): total_sents += 1 src = src.strip('\n') src_matches = find(src, rules, scheme) src_after, src_mod, src_lead = mark(src, src_matches, scheme=scheme, ordered=ordered) if scheme == "del": for seg in src_after: o_source.write(seg + "\n") else: o_source.write(src_after + "\n") if src_matches: total_match_sents += 1 total_matches += len(src_mod) if scheme == "del": if src_after: o_source_ini.write( ("YL" if src_lead and len(src_after) >= len(src_mod) else "YS" if src_lead else \ "NL" if not src_lead and len(src_after) > len(src_mod) else "NS" ) + "\t" + "\t".join(src_mod) + "\n") else: o_source_ini.write("EMPTY" + "\t" + "\t".join(src_mod) + "\n") else: o_source_ini.write('\t'.join(["SUB"] + src_mod) + "\n") else: o_source_ini.write("IGNORE\n") print(f"{total_matches} LI tokens found in {total_match_sents}/{total_sents} sentences {corpus_path}") else: assert scheme != "del", "ref is not required for del scheme!" src_lines = source.readlines() tgt_lines = open(ref).readlines() for src_line, tgt_line in zip(src_lines, tgt_lines): src_line = src_line.strip('\n') tgt_line = tgt_line.strip('\n') src_matches = find(src_line, rules, scheme) tgt_matches = find(tgt_line, rules, scheme) src_matches_text = [src_line[m.start(0):m.end(0)] for m in src_matches] tgt_matches_text = [tgt_line[m.start(0):m.end(0)] for m in tgt_matches] x_matches = list(set(src_matches_text).intersection(set(tgt_matches_text))) x_src_matches = [m for m in src_matches if src_line[m.start(0):m.end(0)] in x_matches] src_after, src_mod, src_lead = mark(src_line, x_src_matches, scheme=scheme, ordered=ordered) o_source.write(src_after + "\n") if x_matches: o_source_ini.write('\t'.join(["SUB"] + src_mod) + "\n") else: o_source_ini.write("IGNORE\n") def restore(dnt_path, ini_path, output, scheme="del", ordered:bool=True): global MARKERS with open(output, "w") as o, open(dnt_path) as i_source, open(ini_path) as i_source_ini: translations = list(map(lambda x: x.strip('\n'), i_source.readlines())) instructions = list(map(lambda x: x.strip('\n'), i_source_ini.readlines())) if scheme == "del": i = 0 j = 0 placeholder = [] while i < len(instructions) and j < len(translations): lead, *tokens = instructions[i].split('\t') if lead == "IGNORE": o.write(translations[j] + "\n") j += 1 i += 1 continue if lead == "EMPTY": o.write("".join(tokens) + "\n") i += 1 continue if lead == "YL": for token in tokens: placeholder.append(token) placeholder.append(translations[j]) j += 1 elif lead == "YS": for x, token in enumerate(tokens): placeholder.append(token) if x < len(tokens) - 1: placeholder.append(translations[j]) j += 1 if lead == "NL": for token in tokens: placeholder.append(translations[j]) placeholder.append(token) j += 1 placeholder.append(translations[j]) j += 1 elif lead == "NS": for token in tokens: placeholder.append(translations[j]) placeholder.append(token) j += 1 o.write("".join(placeholder) + "\n") placeholder = [] i += 1 else: for translation, instruction in zip(translations, instructions): flag, *segments = instruction.split('\t') if flag == "IGNORE": o.write(translation + '\n') continue new_translation = translation for char in translation: if char in MARKERS: if ord(char) - 0x4DC0 >= len(segments) or segments == []: warnings.warn("Wired source sentence: {}".format(translation), Warning) warnings.warn(" ".join(segments), Warning) continue if ordered: new_translation = new_translation.replace(char, segments[min(ord(char) - 0x4DC0, len(segments) - 1)]) else: new_translation = new_translation.replace(char, segments[0], 1) segments.pop(0) o.write(new_translation + '\n') if __name__ == "__main__": txt = """RT @jokateM: Utu humfanya mtu awe kipenzi cha watu,utu humfanya mtu awe kimbilio la watu,aliyekosa utu hana mvuto kwa watu. 🙏🏽❤ She writes [ar]: ملخص تغطية وكالة الانباء الرسمية لمظاهرات امس: مواطنين اعتدوا على الشرطة فاضطروها لاستخدام الغاز المسيل للدموع http://suna-sd.net/suna/showNews/-fJi7HGycvs26Azq7aG4mmjptp-NQZ_WndSuVb1-KMY/1 #الخرا ds.CRIME BE PART OF VODACOM SUCCESS: https://t.co/Wzo1EckNhe via @YouTube CEO wa @MeTL_Group, @moodewji akiwa katika majadiliano kwenye mkutano wa @africaceoforum unaofanyika Geneva, Switze... https://t.co/uBAXDYfmlQ @earadiofm: #MICHEZO Msanii na Mbunge wa Mikumi @ProfessorJayTz akiwa na <NAME> katika uwanja wa Taifa kushuhudia mechi kati ya...RT @earadiofm: #MICHEZO Msanii na Mbunge wa Mikumi @ProfessorJayTz akiwa na <NAME> katika uwanja wa Taifa kushuhudia mechi kati ya...@Youtube She writes [ar]: ملخص تغطية وكالة الانباء الرسمية لمظاهرات امس: مواطنين اعتدوا على الشرطة فاضطروها لاستخدام الغاز المسيل للدموع http://suna-sd.net/suna/showNews/-fJi7HGycvs26Azq7aG4mmjptp-NQZ_WndSuVb1-KMY/1 https://t.co/6fURhmguTF‬""" rules = load_rules('rules.ini', 'sub') options = generate_options('rules.ini') matches = find(txt, rules, 'sub') spans = [txt[m.start:m.end] for m in matches] print(spans) print(mark(txt, find(txt, rules, 'sub'), 'sub', ordered=False)) print(visual(txt, matches, options, rules))
0.310172
0.233422
from FEMur import * import sys import sympy as sy import numpy as np import scipy as sc import matplotlib.pyplot as plt import matplotlib.tri as tri import scipy.interpolate from math import ceil class Solver(object): ''' 2-dimensional solver top class. Provides common initialization to all child solver classes. ''' def __init__(self, meshfile, analysis_type): self.meshfile = meshfile self.analysis_type = analysis_type self.get_mesh() self.D = None self.gbl_stiff = None self.gbl_load = None self.gbl_omega = None self.dirichlet_applied = False def weakform(self): ''' Prints weak form used by the solver to approximate the results. ''' def get_mesh(self): ''' Call Mesh class to create the mesh. ''' try: a = self.meshfile except AttributeError: print('A mesh file has not been provided.') sys.exit(1) self.mesh = Mesh2D(self.meshfile, self.analysis_type) self.mesh.mesh() def solve(self): ''' Solves the equation system. Solves for O in: [K]{O}={F} where K is the global stiffness matrix (or conductivitity) O is the displacement (or temperature) F is the applied load (or [...]) ''' if self.gbl_stiff is None or self.gbl_load is None: self.assemble_stiff_load() if self.dirichlet_applied is False: self.update_stiff_load_dirichlet() print('\n# SOLVING FOR OMEGA #\n') print(self.gbl_stiff) print(self.gbl_load) new_stiff = sy.matrix2numpy(self.gbl_stiff, dtype=float) new_load = sy.matrix2numpy(self.gbl_load, dtype=float) new_omega = np.linalg.solve(new_stiff, new_load) self.gbl_omega = new_omega print(self.gbl_omega) def plot_results(self): if self.gbl_omega is None: # Check if the system has been solved self.solve() x = np.zeros(self.mesh.num_nodes) y = np.zeros(self.mesh.num_nodes) z = self.gbl_omega.T for i in self.mesh.nodes.keys(): x[i] = self.mesh.nodes[i].x y[i] = self.mesh.nodes[i].y xi, yi = np.linspace(x.min(), x.max(), 100), np.linspace(y.min(), y.max(), 100) xi, yi = np.meshgrid(xi, yi) trias = np.zeros((self.mesh.num_elem, 3)) for i in self.mesh.elements.keys(): if self.mesh.elements[i].num_nodes < 6: pass else: for j in range(3): trias[i, j] = self.mesh.elements[i].nodes[j].index rbf = sc.interpolate.Rbf(x, y, z, function='linear') zi = rbf(xi, yi) plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower', extent=[x.min(), x.max(), y.min(), y.max()], cmap=plt.get_cmap('plasma')) plt.scatter(x, y, c=z, cmap=plt.get_cmap('plasma')) plt.colorbar() plt.triplot(x, y, trias, 'o-', ms=3, lw=1.0, color='black') plt.show() class SteadyHeatSolver(Solver): ''' 2-dimensional steady state heat transfer solver. ''' def __init__(self, meshfile): Solver.__init__(self, meshfile, "SSHeat") def assemble_stiff_load(self): ''' Assemble the Global Stiffness Matrix and Global Load Vector based on elements. Only affects nodes pertaining to shell elements. It will overwrite nodes that were defined under the first assembler. ''' try: a = self.mesh.elements[0].nodes[0].x except AttributeError: self.get_mesh() self.gbl_stiff = sy.zeros(self.mesh.num_nodes) self.gbl_load = sy.zeros(self.mesh.num_nodes, 1) print('\n# STARTING ASSEMBLY #\n') if self.mesh.calculated is None: self.mesh.solve_elements() for i in self.mesh.elements.keys(): key = int(i) # To do: Create a method to provide all elements with the # surrounding conditions. self.mesh.elements[i].D = self.D self.mesh.elements[i].h = self.h self.mesh.elements[i].e = self.e self.mesh.elements[i].t_ext = self.t_ext is_point = isinstance(self.mesh.elements[i], Point1) # Is it a Point1 if not is_point: print(f"Calculating Element({key})'s Stiffness Matrix") # self.elements[i].solve_heat_stiff() print(f"Calculating Element({key})'s Load Vector") self.mesh.elements[i].get_C() # self.elements[i].solve_heat_load() print(f"Applying Element({key})'s Stiffness Matrix and Load Vector" f"to the global Stiffness Matrix and Global Load Vector") nodes_indexes = [] for j in self.mesh.elements[i].nodes.keys(): # Create a list with all the element nodes indexes nodes_indexes.append(self.mesh.elements[i].nodes[j].index) for j in range(self.mesh.elements[i].num_nodes): # Assemble Stiffness matrix for k in range(self.mesh.elements[i].num_nodes): self.gbl_stiff[nodes_indexes[j], nodes_indexes[k]] += ( self.mesh.elements[i].K_e[j, k] ) # Assemble Load vector self.gbl_load[nodes_indexes[j]] += ( self.mesh.elements[i].F_e[j] ) return None def set_environment(self, t_ext, h, e, dirichlet, dirichlet_nodes, k_x, k_y=None, k_xy=None): ''' Provide the environment variable to the mesh 'T_ext' the temperature of the surounding air. 'h' the convection factors. 'e' the thickness of the shell. [D] with its diffusion factors (K) will be as follows: [D] = [k_x k_xy] [k_xy k_y] ''' print('Applying Environment') self.t_ext = t_ext self.h = h self.e = e self.dirichlet = dirichlet self.dirichlet_nodes = dirichlet_nodes # table with nodes affected. if k_y is None: k_y = k_x if k_xy is None: k_xy = 0 self.D = sy.Matrix([[k_x, k_xy], [k_xy, k_y]]) print('Environment Applied') def update_stiff_load_dirichlet(self): ''' Impose the 'impose' value on all nodes corresponding to value of x or y provided. This will clear the row and column associated with all nodes, effectively cancelling all neighboring nodes from having an impact on the dirichlet nodes. ''' if self.gbl_stiff is None or self.gbl_load is None: self.assemble_stiff_load() new_gbl_stiff = self.gbl_stiff new_gbl_load = self.gbl_load print('\n# IMPOSING DIRICHLET #\n') for i in self.dirichlet_nodes: print(f"Imposing Dirichlet on Node({i}).") new_gbl_load -= (new_gbl_stiff[:, self.mesh.nodes[i].index] * self.dirichlet) for j in range(self.mesh.num_nodes): new_gbl_stiff[self.mesh.nodes[i].index, j] = 0 new_gbl_stiff[j, self.mesh.nodes[i].index] = 0 new_gbl_stiff[self.mesh.nodes[i].index, self.mesh.nodes[i].index] = 1 new_gbl_load[self.mesh.nodes[i].index] = self.dirichlet self.gbl_stiff = new_gbl_stiff self.gbl_load = new_gbl_load self.dirichlet_applied = True return None class SteadyStructureSolver(Solver): ''' 2-dimensional steady state structure solver. ''' def __init__(self, meshfile): Solver.__init__(self, meshfile, "SSMech")
FEMur/solver2D.py
from FEMur import * import sys import sympy as sy import numpy as np import scipy as sc import matplotlib.pyplot as plt import matplotlib.tri as tri import scipy.interpolate from math import ceil class Solver(object): ''' 2-dimensional solver top class. Provides common initialization to all child solver classes. ''' def __init__(self, meshfile, analysis_type): self.meshfile = meshfile self.analysis_type = analysis_type self.get_mesh() self.D = None self.gbl_stiff = None self.gbl_load = None self.gbl_omega = None self.dirichlet_applied = False def weakform(self): ''' Prints weak form used by the solver to approximate the results. ''' def get_mesh(self): ''' Call Mesh class to create the mesh. ''' try: a = self.meshfile except AttributeError: print('A mesh file has not been provided.') sys.exit(1) self.mesh = Mesh2D(self.meshfile, self.analysis_type) self.mesh.mesh() def solve(self): ''' Solves the equation system. Solves for O in: [K]{O}={F} where K is the global stiffness matrix (or conductivitity) O is the displacement (or temperature) F is the applied load (or [...]) ''' if self.gbl_stiff is None or self.gbl_load is None: self.assemble_stiff_load() if self.dirichlet_applied is False: self.update_stiff_load_dirichlet() print('\n# SOLVING FOR OMEGA #\n') print(self.gbl_stiff) print(self.gbl_load) new_stiff = sy.matrix2numpy(self.gbl_stiff, dtype=float) new_load = sy.matrix2numpy(self.gbl_load, dtype=float) new_omega = np.linalg.solve(new_stiff, new_load) self.gbl_omega = new_omega print(self.gbl_omega) def plot_results(self): if self.gbl_omega is None: # Check if the system has been solved self.solve() x = np.zeros(self.mesh.num_nodes) y = np.zeros(self.mesh.num_nodes) z = self.gbl_omega.T for i in self.mesh.nodes.keys(): x[i] = self.mesh.nodes[i].x y[i] = self.mesh.nodes[i].y xi, yi = np.linspace(x.min(), x.max(), 100), np.linspace(y.min(), y.max(), 100) xi, yi = np.meshgrid(xi, yi) trias = np.zeros((self.mesh.num_elem, 3)) for i in self.mesh.elements.keys(): if self.mesh.elements[i].num_nodes < 6: pass else: for j in range(3): trias[i, j] = self.mesh.elements[i].nodes[j].index rbf = sc.interpolate.Rbf(x, y, z, function='linear') zi = rbf(xi, yi) plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower', extent=[x.min(), x.max(), y.min(), y.max()], cmap=plt.get_cmap('plasma')) plt.scatter(x, y, c=z, cmap=plt.get_cmap('plasma')) plt.colorbar() plt.triplot(x, y, trias, 'o-', ms=3, lw=1.0, color='black') plt.show() class SteadyHeatSolver(Solver): ''' 2-dimensional steady state heat transfer solver. ''' def __init__(self, meshfile): Solver.__init__(self, meshfile, "SSHeat") def assemble_stiff_load(self): ''' Assemble the Global Stiffness Matrix and Global Load Vector based on elements. Only affects nodes pertaining to shell elements. It will overwrite nodes that were defined under the first assembler. ''' try: a = self.mesh.elements[0].nodes[0].x except AttributeError: self.get_mesh() self.gbl_stiff = sy.zeros(self.mesh.num_nodes) self.gbl_load = sy.zeros(self.mesh.num_nodes, 1) print('\n# STARTING ASSEMBLY #\n') if self.mesh.calculated is None: self.mesh.solve_elements() for i in self.mesh.elements.keys(): key = int(i) # To do: Create a method to provide all elements with the # surrounding conditions. self.mesh.elements[i].D = self.D self.mesh.elements[i].h = self.h self.mesh.elements[i].e = self.e self.mesh.elements[i].t_ext = self.t_ext is_point = isinstance(self.mesh.elements[i], Point1) # Is it a Point1 if not is_point: print(f"Calculating Element({key})'s Stiffness Matrix") # self.elements[i].solve_heat_stiff() print(f"Calculating Element({key})'s Load Vector") self.mesh.elements[i].get_C() # self.elements[i].solve_heat_load() print(f"Applying Element({key})'s Stiffness Matrix and Load Vector" f"to the global Stiffness Matrix and Global Load Vector") nodes_indexes = [] for j in self.mesh.elements[i].nodes.keys(): # Create a list with all the element nodes indexes nodes_indexes.append(self.mesh.elements[i].nodes[j].index) for j in range(self.mesh.elements[i].num_nodes): # Assemble Stiffness matrix for k in range(self.mesh.elements[i].num_nodes): self.gbl_stiff[nodes_indexes[j], nodes_indexes[k]] += ( self.mesh.elements[i].K_e[j, k] ) # Assemble Load vector self.gbl_load[nodes_indexes[j]] += ( self.mesh.elements[i].F_e[j] ) return None def set_environment(self, t_ext, h, e, dirichlet, dirichlet_nodes, k_x, k_y=None, k_xy=None): ''' Provide the environment variable to the mesh 'T_ext' the temperature of the surounding air. 'h' the convection factors. 'e' the thickness of the shell. [D] with its diffusion factors (K) will be as follows: [D] = [k_x k_xy] [k_xy k_y] ''' print('Applying Environment') self.t_ext = t_ext self.h = h self.e = e self.dirichlet = dirichlet self.dirichlet_nodes = dirichlet_nodes # table with nodes affected. if k_y is None: k_y = k_x if k_xy is None: k_xy = 0 self.D = sy.Matrix([[k_x, k_xy], [k_xy, k_y]]) print('Environment Applied') def update_stiff_load_dirichlet(self): ''' Impose the 'impose' value on all nodes corresponding to value of x or y provided. This will clear the row and column associated with all nodes, effectively cancelling all neighboring nodes from having an impact on the dirichlet nodes. ''' if self.gbl_stiff is None or self.gbl_load is None: self.assemble_stiff_load() new_gbl_stiff = self.gbl_stiff new_gbl_load = self.gbl_load print('\n# IMPOSING DIRICHLET #\n') for i in self.dirichlet_nodes: print(f"Imposing Dirichlet on Node({i}).") new_gbl_load -= (new_gbl_stiff[:, self.mesh.nodes[i].index] * self.dirichlet) for j in range(self.mesh.num_nodes): new_gbl_stiff[self.mesh.nodes[i].index, j] = 0 new_gbl_stiff[j, self.mesh.nodes[i].index] = 0 new_gbl_stiff[self.mesh.nodes[i].index, self.mesh.nodes[i].index] = 1 new_gbl_load[self.mesh.nodes[i].index] = self.dirichlet self.gbl_stiff = new_gbl_stiff self.gbl_load = new_gbl_load self.dirichlet_applied = True return None class SteadyStructureSolver(Solver): ''' 2-dimensional steady state structure solver. ''' def __init__(self, meshfile): Solver.__init__(self, meshfile, "SSMech")
0.429908
0.35488
import logging from typing import TYPE_CHECKING, List, Optional, Tuple, Union import pandas as pd from datasets import Mode from datasets._typing import ColumnNames, DataFrameType from datasets.context import Context from datasets.dataset_plugin import DatasetPlugin from datasets.exceptions import InvalidOperationException from datasets.plugins.batch.batch_base_plugin import ( BatchBasePlugin, BatchOptions, ) _logger = logging.getLogger(__name__) _logger.setLevel(logging.INFO) if TYPE_CHECKING: import dask.dataframe as dd from pyspark import SparkConf, pandas as ps from pyspark.sql import DataFrame as SparkDataFrame @DatasetPlugin.register(context=Context.BATCH, options_type=BatchOptions) class BatchDataset(BatchBasePlugin): """ The default plugin for the BATCH execution context. """ def __init__( self, name: str, logical_key: str = None, columns: Optional[ColumnNames] = None, run_id: Optional[str] = None, run_time: Optional[int] = None, mode: Mode = Mode.READ, options: Optional[BatchOptions] = BatchOptions(), ): DatasetPlugin._dataset_name_validator(name) super(BatchDataset, self).__init__( name=name, logical_key=logical_key, columns=columns, run_id=run_id, run_time=run_time, mode=mode, options=options, ) self.path = self._path = None if options and isinstance(options, BatchOptions): self.path = options.path self._path: Optional[str] = options.path if options.path: self["path"] = options.path def to_spark_pandas( self, columns: Optional[str] = None, run_id: Optional[str] = None, run_time: Optional[int] = None, conf: Optional["SparkConf"] = None, partitions: Optional[dict] = None, **kwargs, ) -> "ps.DataFrame": return self.to_spark( columns=columns, run_id=run_id, run_time=run_time, conf=conf, partitions=partitions, **kwargs ).to_pandas_on_spark(index_col=kwargs.get("index_col", None)) def to_pandas( self, columns: Optional[str] = None, run_id: Optional[str] = None, run_time: Optional[int] = None, storage_format: str = "parquet", partitions: Optional[dict] = None, **kwargs, ) -> pd.DataFrame: if not (self.mode & Mode.READ): raise InvalidOperationException(f"Cannot read because mode={self.mode}") filters, read_columns = self._get_filters_columns(columns, run_id, run_time, partitions) self._path = self._get_dataset_path() _logger.info( f"to_pandas({self._path=},{read_columns=},{partitions=},{run_id=},{run_time=},{filters=})" ) df: pd.DataFrame if storage_format == "parquet": df = pd.read_parquet( self._path, columns=read_columns, filters=filters, engine=kwargs.get("engine", "pyarrow"), **kwargs, ) elif storage_format == "csv": df = pd.read_csv(self._path, usecols=read_columns, **kwargs) else: raise ValueError(f"{storage_format=} not supported.") for meta_column in self._META_COLUMNS: if meta_column in df and (read_columns is None or meta_column not in read_columns): del df[meta_column] return df def to_dask( self, columns: Optional[str] = None, run_id: Optional[str] = None, run_time: Optional[int] = None, partitions: Optional[dict] = None, **kwargs, ) -> "dd.DataFrame": if not (self.mode & Mode.READ): raise InvalidOperationException(f"Cannot read because mode={self.mode}") import dask.dataframe as dd filters, read_columns = self._get_filters_columns(columns, run_id, run_time, partitions) self._path = self._get_dataset_path() _logger.info(f"to_dask({self._path=},{read_columns=},{partitions=},{run_id=},{run_time=},{filters=})") return dd.read_parquet( self._path, columns=read_columns, filters=filters, engine=kwargs.get("engine", "pyarrow"), **kwargs, ) def to_spark( self, columns: Optional[str] = None, run_id: Optional[str] = None, run_time: Optional[int] = None, conf: Optional["SparkConf"] = None, storage_format: str = "parquet", partitions: Optional[dict] = None, **kwargs, ) -> "SparkDataFrame": if not self.mode & Mode.READ: raise InvalidOperationException(f"Cannot read because mode={self.mode}") from pyspark.sql import DataFrame, SparkSession filters, read_columns = self._get_filters_columns(columns, run_id, run_time, partitions) self._path = self._get_dataset_path() read_columns = read_columns if read_columns else ["*"] if (self.run_id or run_id) and "*" not in read_columns and "run_id" not in read_columns: read_columns.append("run_id") if (self.run_time or run_time) and "*" not in read_columns and "run_time" not in read_columns: read_columns.append("run_time") spark_session: SparkSession = BatchBasePlugin._get_spark_builder(conf).getOrCreate() _logger.info(f"to_spark({self._path=}, {read_columns=}, {partitions=}, {run_id=}, {filters=})") df: DataFrame = spark_session.read.load(self._path, format=storage_format, **kwargs).select( *read_columns ) if filters: for name, op, val in filters: df = df.where(df[name] == val) for meta_column in self._META_COLUMNS: if meta_column in df.columns and (read_columns is None or meta_column not in read_columns): df = df.drop(meta_column) return df def write(self, data: Union[pd.DataFrame, "ps.DataFrame", "SparkDataFrame", "dd.DataFrame"], **kwargs): if isinstance(data, pd.DataFrame): return self.write_pandas(data, **kwargs) elif "pyspark.pandas.frame.DataFrame" in str(type(data)): return self.write_spark_pandas(data, **kwargs) elif "pyspark.sql.dataframe.DataFrame" in str(type(data)): return self.write_spark(data, **kwargs) elif "dask.dataframe.core.DataFrame" in str(type(data)): return self.write_dask(data, **kwargs) else: raise ValueError( f"data is of unsupported type {type(data)=}. Maybe PySpark/Dask is not installed?" ) def _path_write_data_frame_prep( self, df: DataFrameType, partition_by: Optional[ColumnNames] = None, ) -> Tuple[DataFrameType, List[str]]: partition_cols: List[str] = self._partition_by_to_list(partition_by) if self.path is None: # partition on run_id if Dataset(path="s3://..") is not given if "run_id" not in partition_cols: partition_cols.append("run_id") if "run_time" not in partition_cols: partition_cols.append("run_time") return self._write_data_frame_prep(df, partition_cols) def write_dask(self, df: "dd.DataFrame", partition_by: Optional[ColumnNames] = None, **kwargs): import dask.dataframe as dd df, partition_cols = self._path_write_data_frame_prep(df, partition_by=partition_by) self._path = self._get_dataset_path() _logger.info(f"write_dask({self._path=}, {partition_cols=})") dd.to_parquet( df, self._path, engine=kwargs.get("engine", "pyarrow"), compression=kwargs.get("compression", "snappy"), partition_on=partition_cols, write_index=kwargs.get("write_index", False), write_metadata_file=kwargs.get("write_metadata_file", False), **kwargs, ) def write_pandas(self, df: pd.DataFrame, partition_by: Optional[ColumnNames] = None, **kwargs): df, partition_cols = self._path_write_data_frame_prep(df, partition_by=partition_by) self._path = self._get_dataset_path() _logger.info(f"write_pandas({self._path=}, {partition_cols=})") df.to_parquet( self._path, engine=kwargs.get("engine", "pyarrow"), compression=kwargs.get("compression", "snappy"), partition_cols=partition_cols, index=kwargs.get("index", False), **kwargs, ) def write_spark_pandas(self, df: "ps.DataFrame", partition_by: Optional[ColumnNames] = None, **kwargs): self.write_spark( df.to_spark(index_col=kwargs.get("index_col", None)), partition_by=partition_by, **kwargs, ) def write_spark(self, df: "SparkDataFrame", partition_by: Optional[ColumnNames] = None, **kwargs): df, partition_cols = self._path_write_data_frame_prep(df, partition_by=partition_by) self._path = self._get_dataset_path() _logger.info(f"write_spark({self._path=}, {partition_cols=})") # TODO: should mode=overwrite be the default policy?? df.write.options(**kwargs).mode(kwargs.get("mode", "overwrite")).parquet( path=self._path, partitionBy=partition_cols, compression=kwargs.get("compression", "snappy"), ) def __repr__(self): return ( f"BatchDataset({self.name=},{self.key=},{self.partition_by=}," f"{self.run_id=},{self.columns=},{self.mode=},{self.path=},{self._path=})" )
datasets/plugins/batch/batch_dataset.py
import logging from typing import TYPE_CHECKING, List, Optional, Tuple, Union import pandas as pd from datasets import Mode from datasets._typing import ColumnNames, DataFrameType from datasets.context import Context from datasets.dataset_plugin import DatasetPlugin from datasets.exceptions import InvalidOperationException from datasets.plugins.batch.batch_base_plugin import ( BatchBasePlugin, BatchOptions, ) _logger = logging.getLogger(__name__) _logger.setLevel(logging.INFO) if TYPE_CHECKING: import dask.dataframe as dd from pyspark import SparkConf, pandas as ps from pyspark.sql import DataFrame as SparkDataFrame @DatasetPlugin.register(context=Context.BATCH, options_type=BatchOptions) class BatchDataset(BatchBasePlugin): """ The default plugin for the BATCH execution context. """ def __init__( self, name: str, logical_key: str = None, columns: Optional[ColumnNames] = None, run_id: Optional[str] = None, run_time: Optional[int] = None, mode: Mode = Mode.READ, options: Optional[BatchOptions] = BatchOptions(), ): DatasetPlugin._dataset_name_validator(name) super(BatchDataset, self).__init__( name=name, logical_key=logical_key, columns=columns, run_id=run_id, run_time=run_time, mode=mode, options=options, ) self.path = self._path = None if options and isinstance(options, BatchOptions): self.path = options.path self._path: Optional[str] = options.path if options.path: self["path"] = options.path def to_spark_pandas( self, columns: Optional[str] = None, run_id: Optional[str] = None, run_time: Optional[int] = None, conf: Optional["SparkConf"] = None, partitions: Optional[dict] = None, **kwargs, ) -> "ps.DataFrame": return self.to_spark( columns=columns, run_id=run_id, run_time=run_time, conf=conf, partitions=partitions, **kwargs ).to_pandas_on_spark(index_col=kwargs.get("index_col", None)) def to_pandas( self, columns: Optional[str] = None, run_id: Optional[str] = None, run_time: Optional[int] = None, storage_format: str = "parquet", partitions: Optional[dict] = None, **kwargs, ) -> pd.DataFrame: if not (self.mode & Mode.READ): raise InvalidOperationException(f"Cannot read because mode={self.mode}") filters, read_columns = self._get_filters_columns(columns, run_id, run_time, partitions) self._path = self._get_dataset_path() _logger.info( f"to_pandas({self._path=},{read_columns=},{partitions=},{run_id=},{run_time=},{filters=})" ) df: pd.DataFrame if storage_format == "parquet": df = pd.read_parquet( self._path, columns=read_columns, filters=filters, engine=kwargs.get("engine", "pyarrow"), **kwargs, ) elif storage_format == "csv": df = pd.read_csv(self._path, usecols=read_columns, **kwargs) else: raise ValueError(f"{storage_format=} not supported.") for meta_column in self._META_COLUMNS: if meta_column in df and (read_columns is None or meta_column not in read_columns): del df[meta_column] return df def to_dask( self, columns: Optional[str] = None, run_id: Optional[str] = None, run_time: Optional[int] = None, partitions: Optional[dict] = None, **kwargs, ) -> "dd.DataFrame": if not (self.mode & Mode.READ): raise InvalidOperationException(f"Cannot read because mode={self.mode}") import dask.dataframe as dd filters, read_columns = self._get_filters_columns(columns, run_id, run_time, partitions) self._path = self._get_dataset_path() _logger.info(f"to_dask({self._path=},{read_columns=},{partitions=},{run_id=},{run_time=},{filters=})") return dd.read_parquet( self._path, columns=read_columns, filters=filters, engine=kwargs.get("engine", "pyarrow"), **kwargs, ) def to_spark( self, columns: Optional[str] = None, run_id: Optional[str] = None, run_time: Optional[int] = None, conf: Optional["SparkConf"] = None, storage_format: str = "parquet", partitions: Optional[dict] = None, **kwargs, ) -> "SparkDataFrame": if not self.mode & Mode.READ: raise InvalidOperationException(f"Cannot read because mode={self.mode}") from pyspark.sql import DataFrame, SparkSession filters, read_columns = self._get_filters_columns(columns, run_id, run_time, partitions) self._path = self._get_dataset_path() read_columns = read_columns if read_columns else ["*"] if (self.run_id or run_id) and "*" not in read_columns and "run_id" not in read_columns: read_columns.append("run_id") if (self.run_time or run_time) and "*" not in read_columns and "run_time" not in read_columns: read_columns.append("run_time") spark_session: SparkSession = BatchBasePlugin._get_spark_builder(conf).getOrCreate() _logger.info(f"to_spark({self._path=}, {read_columns=}, {partitions=}, {run_id=}, {filters=})") df: DataFrame = spark_session.read.load(self._path, format=storage_format, **kwargs).select( *read_columns ) if filters: for name, op, val in filters: df = df.where(df[name] == val) for meta_column in self._META_COLUMNS: if meta_column in df.columns and (read_columns is None or meta_column not in read_columns): df = df.drop(meta_column) return df def write(self, data: Union[pd.DataFrame, "ps.DataFrame", "SparkDataFrame", "dd.DataFrame"], **kwargs): if isinstance(data, pd.DataFrame): return self.write_pandas(data, **kwargs) elif "pyspark.pandas.frame.DataFrame" in str(type(data)): return self.write_spark_pandas(data, **kwargs) elif "pyspark.sql.dataframe.DataFrame" in str(type(data)): return self.write_spark(data, **kwargs) elif "dask.dataframe.core.DataFrame" in str(type(data)): return self.write_dask(data, **kwargs) else: raise ValueError( f"data is of unsupported type {type(data)=}. Maybe PySpark/Dask is not installed?" ) def _path_write_data_frame_prep( self, df: DataFrameType, partition_by: Optional[ColumnNames] = None, ) -> Tuple[DataFrameType, List[str]]: partition_cols: List[str] = self._partition_by_to_list(partition_by) if self.path is None: # partition on run_id if Dataset(path="s3://..") is not given if "run_id" not in partition_cols: partition_cols.append("run_id") if "run_time" not in partition_cols: partition_cols.append("run_time") return self._write_data_frame_prep(df, partition_cols) def write_dask(self, df: "dd.DataFrame", partition_by: Optional[ColumnNames] = None, **kwargs): import dask.dataframe as dd df, partition_cols = self._path_write_data_frame_prep(df, partition_by=partition_by) self._path = self._get_dataset_path() _logger.info(f"write_dask({self._path=}, {partition_cols=})") dd.to_parquet( df, self._path, engine=kwargs.get("engine", "pyarrow"), compression=kwargs.get("compression", "snappy"), partition_on=partition_cols, write_index=kwargs.get("write_index", False), write_metadata_file=kwargs.get("write_metadata_file", False), **kwargs, ) def write_pandas(self, df: pd.DataFrame, partition_by: Optional[ColumnNames] = None, **kwargs): df, partition_cols = self._path_write_data_frame_prep(df, partition_by=partition_by) self._path = self._get_dataset_path() _logger.info(f"write_pandas({self._path=}, {partition_cols=})") df.to_parquet( self._path, engine=kwargs.get("engine", "pyarrow"), compression=kwargs.get("compression", "snappy"), partition_cols=partition_cols, index=kwargs.get("index", False), **kwargs, ) def write_spark_pandas(self, df: "ps.DataFrame", partition_by: Optional[ColumnNames] = None, **kwargs): self.write_spark( df.to_spark(index_col=kwargs.get("index_col", None)), partition_by=partition_by, **kwargs, ) def write_spark(self, df: "SparkDataFrame", partition_by: Optional[ColumnNames] = None, **kwargs): df, partition_cols = self._path_write_data_frame_prep(df, partition_by=partition_by) self._path = self._get_dataset_path() _logger.info(f"write_spark({self._path=}, {partition_cols=})") # TODO: should mode=overwrite be the default policy?? df.write.options(**kwargs).mode(kwargs.get("mode", "overwrite")).parquet( path=self._path, partitionBy=partition_cols, compression=kwargs.get("compression", "snappy"), ) def __repr__(self): return ( f"BatchDataset({self.name=},{self.key=},{self.partition_by=}," f"{self.run_id=},{self.columns=},{self.mode=},{self.path=},{self._path=})" )
0.837288
0.237886
import numpy as np from mxnet import ndarray as nd def calculate_indexes(current_index, shape, gradients_cumulative, coordinates): if len(coordinates) == 1: return gradients_cumulative[current_index] + coordinates[0] if len(coordinates) == 2: return gradients_cumulative[current_index] + (coordinates[0] * shape[1] + coordinates[1]) return None def build_message_map(idx, gradients_cumulative, numpy_delta_positive, numpy_delta_negative, zero_setter, one_setter): map_ups = np.where(numpy_delta_positive == 1) ups = calculate_indexes(idx, numpy_delta_positive.shape, gradients_cumulative, map_ups) ups = one_setter(ups) map_downs = np.where(numpy_delta_negative == 1) downs = calculate_indexes(idx, numpy_delta_negative.shape, gradients_cumulative, map_downs) downs = zero_setter(downs) return np.concatenate((ups, downs)) def get_indices(ups_or_downs, gradients_cumulative, gradients_blueprint): first_indices = [ 0 if t == 0 else len(gradients_cumulative) - 1 if gradients_cumulative[-1] <= t else \ list(map(lambda x: x > t, gradients_cumulative)).index(True) - 1 for t in ups_or_downs] offsets = [(t - gradients_cumulative[first_indices[i]]) for i, t in enumerate(ups_or_downs)] all_indices = [] for idx, t in enumerate(ups_or_downs): if len(gradients_blueprint[first_indices[idx]]) == 1: all_indices.append((first_indices[idx], offsets[idx],)) elif len(gradients_blueprint[first_indices[idx]]) == 2: all_indices.append( (first_indices[idx], offsets[idx] // gradients_blueprint[first_indices[idx]][1], offsets[idx] % gradients_blueprint[first_indices[idx]][1])) return all_indices def decode_message_map(ctx, weight_indices, gradients_blueprint, gradients_cumulative, tau, zero_setter): message_map = np.array(weight_indices) sign_detector = np.vectorize(lambda int_type: int_type & (1 << 31) > 0, otypes=[np.bool]) signs = sign_detector(message_map) ups = zero_setter(message_map[signs]) downs = message_map[np.logical_not(signs)] peer_gradients = [nd.zeros(shape=blueprint, ctx=ctx) for blueprint in gradients_blueprint] up_indices = get_indices(ups, gradients_cumulative, gradients_blueprint) down_indices = get_indices(downs, gradients_cumulative, gradients_blueprint) for up in up_indices: if len(up) == 2: peer_gradients[up[0]][up[1]] = tau elif len(up) == 3: peer_gradients[up[0]][up[1]][up[2]] = tau for down in down_indices: if len(down) == 2: peer_gradients[down[0]][down[1]] = -tau elif len(down) == 3: peer_gradients[down[0]][down[1]][down[2]] = -tau return peer_gradients
pai/pouw/message_map.py
import numpy as np from mxnet import ndarray as nd def calculate_indexes(current_index, shape, gradients_cumulative, coordinates): if len(coordinates) == 1: return gradients_cumulative[current_index] + coordinates[0] if len(coordinates) == 2: return gradients_cumulative[current_index] + (coordinates[0] * shape[1] + coordinates[1]) return None def build_message_map(idx, gradients_cumulative, numpy_delta_positive, numpy_delta_negative, zero_setter, one_setter): map_ups = np.where(numpy_delta_positive == 1) ups = calculate_indexes(idx, numpy_delta_positive.shape, gradients_cumulative, map_ups) ups = one_setter(ups) map_downs = np.where(numpy_delta_negative == 1) downs = calculate_indexes(idx, numpy_delta_negative.shape, gradients_cumulative, map_downs) downs = zero_setter(downs) return np.concatenate((ups, downs)) def get_indices(ups_or_downs, gradients_cumulative, gradients_blueprint): first_indices = [ 0 if t == 0 else len(gradients_cumulative) - 1 if gradients_cumulative[-1] <= t else \ list(map(lambda x: x > t, gradients_cumulative)).index(True) - 1 for t in ups_or_downs] offsets = [(t - gradients_cumulative[first_indices[i]]) for i, t in enumerate(ups_or_downs)] all_indices = [] for idx, t in enumerate(ups_or_downs): if len(gradients_blueprint[first_indices[idx]]) == 1: all_indices.append((first_indices[idx], offsets[idx],)) elif len(gradients_blueprint[first_indices[idx]]) == 2: all_indices.append( (first_indices[idx], offsets[idx] // gradients_blueprint[first_indices[idx]][1], offsets[idx] % gradients_blueprint[first_indices[idx]][1])) return all_indices def decode_message_map(ctx, weight_indices, gradients_blueprint, gradients_cumulative, tau, zero_setter): message_map = np.array(weight_indices) sign_detector = np.vectorize(lambda int_type: int_type & (1 << 31) > 0, otypes=[np.bool]) signs = sign_detector(message_map) ups = zero_setter(message_map[signs]) downs = message_map[np.logical_not(signs)] peer_gradients = [nd.zeros(shape=blueprint, ctx=ctx) for blueprint in gradients_blueprint] up_indices = get_indices(ups, gradients_cumulative, gradients_blueprint) down_indices = get_indices(downs, gradients_cumulative, gradients_blueprint) for up in up_indices: if len(up) == 2: peer_gradients[up[0]][up[1]] = tau elif len(up) == 3: peer_gradients[up[0]][up[1]][up[2]] = tau for down in down_indices: if len(down) == 2: peer_gradients[down[0]][down[1]] = -tau elif len(down) == 3: peer_gradients[down[0]][down[1]][down[2]] = -tau return peer_gradients
0.515132
0.688768
import os import re import subprocess from time import sleep class File(object): def __init__(self, path): self.path = path self.last_update = None self.existed = True def updated(self): if self.existed and not os.path.exists(self.path): self.existed = False return True if not self.existed: return False fs_stat = os.stat(self.path) current_last_update = fs_stat.st_mtime if not self.last_update: self.last_update = current_last_update return False elif self.last_update == current_last_update: return False self.last_update = current_last_update return True class FileSystemManager(object): def __init__(self, callback, *paths, **options): self.paths = paths self.fileMap = {} self.activated = True self.callback = callback def update(self): for path in self.paths: local_updates = self.local_updates(path) if not local_updates: continue self.callback(local_updates) def local_updates(self, path): local_paths = os.listdir(path) local_updates = [] for local_path in local_paths: rel_path = os.path.join(path, local_path) if local_path[0] == '.' or re.search('\.pyc$', local_path): continue if os.path.isdir(rel_path): local_updates.extend(self.local_updates(rel_path)) continue if rel_path not in self.fileMap: self.fileMap[rel_path] = File(rel_path) local_updates.append(rel_path) print('ADDED: {}'.format(rel_path)) elif self.fileMap[rel_path].updated(): print('UPDATED: {}'.format(rel_path)) local_updates.append(rel_path) return local_updates def recompile(update_files): print('Updating...') #subprocess.call(['make', 'clean']) subprocess.call(['make', 'html']) print('Updated') book_manager = FileSystemManager(recompile, 'source', '../tori') print('Monitoring changes...') while book_manager.activated: try: sleep(1) book_manager.update() except KeyboardInterrupt: print('\rDeactivated') book_manager.activated = False print('The manager has just signed off.')
docs/monitor.py
import os import re import subprocess from time import sleep class File(object): def __init__(self, path): self.path = path self.last_update = None self.existed = True def updated(self): if self.existed and not os.path.exists(self.path): self.existed = False return True if not self.existed: return False fs_stat = os.stat(self.path) current_last_update = fs_stat.st_mtime if not self.last_update: self.last_update = current_last_update return False elif self.last_update == current_last_update: return False self.last_update = current_last_update return True class FileSystemManager(object): def __init__(self, callback, *paths, **options): self.paths = paths self.fileMap = {} self.activated = True self.callback = callback def update(self): for path in self.paths: local_updates = self.local_updates(path) if not local_updates: continue self.callback(local_updates) def local_updates(self, path): local_paths = os.listdir(path) local_updates = [] for local_path in local_paths: rel_path = os.path.join(path, local_path) if local_path[0] == '.' or re.search('\.pyc$', local_path): continue if os.path.isdir(rel_path): local_updates.extend(self.local_updates(rel_path)) continue if rel_path not in self.fileMap: self.fileMap[rel_path] = File(rel_path) local_updates.append(rel_path) print('ADDED: {}'.format(rel_path)) elif self.fileMap[rel_path].updated(): print('UPDATED: {}'.format(rel_path)) local_updates.append(rel_path) return local_updates def recompile(update_files): print('Updating...') #subprocess.call(['make', 'clean']) subprocess.call(['make', 'html']) print('Updated') book_manager = FileSystemManager(recompile, 'source', '../tori') print('Monitoring changes...') while book_manager.activated: try: sleep(1) book_manager.update() except KeyboardInterrupt: print('\rDeactivated') book_manager.activated = False print('The manager has just signed off.')
0.1151
0.055541
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from typing import TYPE_CHECKING from gunicorn.app.base import Application from simple_di import Provide, inject from bentoml.configuration.containers import BentoMLContainer marshal_logger = logging.getLogger("bentoml.marshal") if TYPE_CHECKING: # make type checkers happy from bentoml.marshal.marshal import MarshalApp class GunicornMarshalServer(Application): # pylint: disable=abstract-method @inject(squeeze_none=True) def __init__( self, *, workers: int = Provide[BentoMLContainer.config.bento_server.microbatch.workers], timeout: int = Provide[BentoMLContainer.config.bento_server.timeout], max_request_size: int = Provide[ BentoMLContainer.config.bento_server.max_request_size ], host: str = Provide[BentoMLContainer.service_host], port: int = Provide[BentoMLContainer.service_port], loglevel: str = Provide[BentoMLContainer.config.bento_server.logging.level], ): self.port = port self.options = { "bind": "%s:%s" % (host, port), "timeout": timeout, "limit_request_line": max_request_size, "loglevel": loglevel.upper(), "worker_class": "aiohttp.worker.GunicornWebWorker", } if workers: self.options['workers'] = workers super().__init__() def load_config(self): self.load_config_from_file("python:bentoml.server.gunicorn_config") # override config with self.options assert self.cfg, "gunicorn config must be loaded" for k, v in self.options.items(): if k.lower() in self.cfg.settings and v is not None: self.cfg.set(k.lower(), v) @property @inject def app(self, app: "MarshalApp" = Provide[BentoMLContainer.proxy_app]): return app def load(self): return self.app.get_app() def run(self): marshal_logger.info("Running micro batch service on :%d", self.port) super().run()
bentoml/server/gunicorn_marshal_server.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from typing import TYPE_CHECKING from gunicorn.app.base import Application from simple_di import Provide, inject from bentoml.configuration.containers import BentoMLContainer marshal_logger = logging.getLogger("bentoml.marshal") if TYPE_CHECKING: # make type checkers happy from bentoml.marshal.marshal import MarshalApp class GunicornMarshalServer(Application): # pylint: disable=abstract-method @inject(squeeze_none=True) def __init__( self, *, workers: int = Provide[BentoMLContainer.config.bento_server.microbatch.workers], timeout: int = Provide[BentoMLContainer.config.bento_server.timeout], max_request_size: int = Provide[ BentoMLContainer.config.bento_server.max_request_size ], host: str = Provide[BentoMLContainer.service_host], port: int = Provide[BentoMLContainer.service_port], loglevel: str = Provide[BentoMLContainer.config.bento_server.logging.level], ): self.port = port self.options = { "bind": "%s:%s" % (host, port), "timeout": timeout, "limit_request_line": max_request_size, "loglevel": loglevel.upper(), "worker_class": "aiohttp.worker.GunicornWebWorker", } if workers: self.options['workers'] = workers super().__init__() def load_config(self): self.load_config_from_file("python:bentoml.server.gunicorn_config") # override config with self.options assert self.cfg, "gunicorn config must be loaded" for k, v in self.options.items(): if k.lower() in self.cfg.settings and v is not None: self.cfg.set(k.lower(), v) @property @inject def app(self, app: "MarshalApp" = Provide[BentoMLContainer.proxy_app]): return app def load(self): return self.app.get_app() def run(self): marshal_logger.info("Running micro batch service on :%d", self.port) super().run()
0.863276
0.176122
from aio2ch import ( Api, Board, Thread, Image, Video, Sticker ) import pytest @pytest.fixture async def client(): async with Api(timeout=10.0) as api_client: yield api_client @pytest.fixture async def client_ujson(): from ujson import loads as ujson_loads async with Api(json_loads=ujson_loads) as api_client: yield api_client @pytest.fixture async def client_orjson(): from orjson import loads as orjson_loads async with Api(json_loads=orjson_loads) as api_client: yield api_client @pytest.fixture def board(): test_board_data = { "bump_limit": "", "category": "", "default_name": "", "id": "test", "info": "", "name": "test", "threads": "" } return Board(test_board_data) @pytest.fixture def thread(thread_as_number): test_thread_data = { "comment": "", "num": thread_as_number, "posts_count": "", "score": "", "subject": "", "timestamp": "", "views": "" } test_board = "test" return Thread(test_thread_data, test_board) @pytest.fixture def thread_as_number(): return 29322 @pytest.fixture def thread_url(thread_as_number): return f"https://2ch.hk/test/res/{thread_as_number}.html" @pytest.fixture def invalid_thread(): return "invalid-thread" @pytest.fixture def invalid_board(): return "thisboarddoesntexist" @pytest.fixture def number_of_threads(number=5): return number @pytest.fixture def raw_text(): return "КУКУ ТАМ ОНЛИФЕНС СЛИЛИ, ЕСТЬ ЧТО У КОГО?<br>" \ "<a href=\"https:&#47;&#47;tjournal.ru&#47;internet&#47;146526-v-set-popali-terabayty-" \ "dannyh-onlyfans-sayta-gde-pornozvezdy-i-modeli-razmeshchayut-platnye-eroticheskie-foto-i-video\" " \ "target=\"_blank\" rel=\"nofollow noopener noreferrer\">https:&#47;&#47;tjournal.ru&#47;internet&#47;" \ "146526-v-set-popali-terabayty-dannyh-onlyfans-sayta-gde-pornozvezdy-i-modeli-razmeshchayut-platnye-" \ "eroticheskie-foto-i-video</a><br><br>Давайте братья скажите где скачать эти терабайты" @pytest.fixture def clean_text(): return "КУКУ ТАМ ОНЛИФЕНС СЛИЛИ, ЕСТЬ ЧТО У КОГО?\n" \ "https://tjournal.ru/internet/146526-v-set-popali-terabayty-dannyh-onlyfans-" \ "sayta-gde-pornozvezdy-i-modeli-razmeshchayut-platnye-eroticheskie-foto-i-video\n\n" \ "Давайте братья скажите где скачать эти терабайты" @pytest.fixture def thread_media(): image_data = { "displayname": "pnX1uujobqQ.jpg", "fullname": "pnX1uujobqQ.jpg", "height": 600, "md5": "50a7ca2ed41d00a0f49dd81bbc32074b", "name": "14989172638190.jpg", "nsfw": 0, "path": "/test/src/30972/14989172638190.jpg", "size": 62, "thumbnail": "/test/thumb/30972/14989172638190s.jpg", "tn_height": 250, "tn_width": 250, "type": 1, "width": 600 } video_data = { "displayname": ".mp4", "duration": "00:04:35", "duration_secs": 275, "fullname": ".mp4", "height": 500, "md5": "8614c802cff48b420d54ed62a18fe21c", "name": "15752983961530.mp4", "nsfw": 0, "path": "/test/src/30972/15752983961530.mp4", "size": 5613, "thumbnail": "/test/thumb/30972/15752983961530s.jpg", "tn_height": 200, "tn_width": 200, "type": 10, "width": 500 } sticker_data = { "displayname": "Стикер", "height": 512, "install": "/makaba/stickers/show/n5xSPtEw", "name": "lKfUbr3j.png", "pack": "n5xSPtEw", "path": "/stickers/n5xSPtEw/lKfUbr3j.png", "size": 383, "sticker": "lKfUbr3j", "thumbnail": "/stickers/n5xSPtEw/lKfUbr3j_thumb.png", "tn_height": 200, "tn_width": 200, "type": 100, "width": 512 } return Image(image_data), Video(video_data), Sticker(sticker_data)
tests/conftest.py
from aio2ch import ( Api, Board, Thread, Image, Video, Sticker ) import pytest @pytest.fixture async def client(): async with Api(timeout=10.0) as api_client: yield api_client @pytest.fixture async def client_ujson(): from ujson import loads as ujson_loads async with Api(json_loads=ujson_loads) as api_client: yield api_client @pytest.fixture async def client_orjson(): from orjson import loads as orjson_loads async with Api(json_loads=orjson_loads) as api_client: yield api_client @pytest.fixture def board(): test_board_data = { "bump_limit": "", "category": "", "default_name": "", "id": "test", "info": "", "name": "test", "threads": "" } return Board(test_board_data) @pytest.fixture def thread(thread_as_number): test_thread_data = { "comment": "", "num": thread_as_number, "posts_count": "", "score": "", "subject": "", "timestamp": "", "views": "" } test_board = "test" return Thread(test_thread_data, test_board) @pytest.fixture def thread_as_number(): return 29322 @pytest.fixture def thread_url(thread_as_number): return f"https://2ch.hk/test/res/{thread_as_number}.html" @pytest.fixture def invalid_thread(): return "invalid-thread" @pytest.fixture def invalid_board(): return "thisboarddoesntexist" @pytest.fixture def number_of_threads(number=5): return number @pytest.fixture def raw_text(): return "КУКУ ТАМ ОНЛИФЕНС СЛИЛИ, ЕСТЬ ЧТО У КОГО?<br>" \ "<a href=\"https:&#47;&#47;tjournal.ru&#47;internet&#47;146526-v-set-popali-terabayty-" \ "dannyh-onlyfans-sayta-gde-pornozvezdy-i-modeli-razmeshchayut-platnye-eroticheskie-foto-i-video\" " \ "target=\"_blank\" rel=\"nofollow noopener noreferrer\">https:&#47;&#47;tjournal.ru&#47;internet&#47;" \ "146526-v-set-popali-terabayty-dannyh-onlyfans-sayta-gde-pornozvezdy-i-modeli-razmeshchayut-platnye-" \ "eroticheskie-foto-i-video</a><br><br>Давайте братья скажите где скачать эти терабайты" @pytest.fixture def clean_text(): return "КУКУ ТАМ ОНЛИФЕНС СЛИЛИ, ЕСТЬ ЧТО У КОГО?\n" \ "https://tjournal.ru/internet/146526-v-set-popali-terabayty-dannyh-onlyfans-" \ "sayta-gde-pornozvezdy-i-modeli-razmeshchayut-platnye-eroticheskie-foto-i-video\n\n" \ "Давайте братья скажите где скачать эти терабайты" @pytest.fixture def thread_media(): image_data = { "displayname": "pnX1uujobqQ.jpg", "fullname": "pnX1uujobqQ.jpg", "height": 600, "md5": "50a7ca2ed41d00a0f49dd81bbc32074b", "name": "14989172638190.jpg", "nsfw": 0, "path": "/test/src/30972/14989172638190.jpg", "size": 62, "thumbnail": "/test/thumb/30972/14989172638190s.jpg", "tn_height": 250, "tn_width": 250, "type": 1, "width": 600 } video_data = { "displayname": ".mp4", "duration": "00:04:35", "duration_secs": 275, "fullname": ".mp4", "height": 500, "md5": "8614c802cff48b420d54ed62a18fe21c", "name": "15752983961530.mp4", "nsfw": 0, "path": "/test/src/30972/15752983961530.mp4", "size": 5613, "thumbnail": "/test/thumb/30972/15752983961530s.jpg", "tn_height": 200, "tn_width": 200, "type": 10, "width": 500 } sticker_data = { "displayname": "Стикер", "height": 512, "install": "/makaba/stickers/show/n5xSPtEw", "name": "lKfUbr3j.png", "pack": "n5xSPtEw", "path": "/stickers/n5xSPtEw/lKfUbr3j.png", "size": 383, "sticker": "lKfUbr3j", "thumbnail": "/stickers/n5xSPtEw/lKfUbr3j_thumb.png", "tn_height": 200, "tn_width": 200, "type": 100, "width": 512 } return Image(image_data), Video(video_data), Sticker(sticker_data)
0.387574
0.32017
import torch import numpy as np from torch import nn class BatchRelationalModule(nn.Module): def __init__(self, input_feature_dim, use_coordinates=False, num_layers=2, num_units=64): super(BatchRelationalModule, self).__init__() self.input_feature_dim = input_feature_dim self.block_dict = nn.ModuleDict() self.first_time = True self.use_coordinates = use_coordinates self.num_layers = num_layers self.num_units = num_units self.build_block() def build_block(self): print("Assuming input is of size (b=4, num_object=4, input_feature_dim=%d)" % self.input_feature_dim) out_img = torch.zeros((4, 4, self.input_feature_dim)) """g""" b, length, c = out_img.shape print(out_img.shape) # x_flat = (64 x 25 x 24) if self.use_coordinates: self.coord_tensor = [] for i in range(length): self.coord_tensor.append(torch.Tensor(np.array([i]))) self.coord_tensor = torch.stack(self.coord_tensor, dim=0).unsqueeze(0) if self.coord_tensor.shape[0] != out_img.shape[0]: self.coord_tensor = self.coord_tensor[0].unsqueeze(0).repeat([out_img.shape[0], 1, 1]) out_img = torch.cat([out_img, self.coord_tensor], dim=2) x_i = torch.unsqueeze(out_img, 1) # (1xh*wxc) x_i = x_i.repeat(1, length, 1, 1) # (h*wxh*wxc) x_j = torch.unsqueeze(out_img, 2) # (h*wx1xc) x_j = x_j.repeat(1, 1, length, 1) # (h*wxh*wxc) # concatenate all together per_location_feature = torch.cat([x_i, x_j], 3) # (h*wxh*wx2*c) out = per_location_feature.view( per_location_feature.shape[0] * per_location_feature.shape[1] * per_location_feature.shape[2], per_location_feature.shape[3]) print(out.shape) for idx_layer in range(self.num_layers): self.block_dict['g_fcc_{}'.format(idx_layer)] = nn.Linear(out.shape[1], out_features=self.num_units, bias=True) out = self.block_dict['g_fcc_{}'.format(idx_layer)].forward(out) self.block_dict['LeakyReLU_{}'.format(idx_layer)] = nn.LeakyReLU() out = self.block_dict['LeakyReLU_{}'.format(idx_layer)].forward(out) # reshape again and sum print(out.shape) out = out.view(per_location_feature.shape[0], per_location_feature.shape[1], per_location_feature.shape[2], -1) out = out.sum(1).sum(1) print('here', out.shape) """f""" self.post_processing_layer = nn.Linear(in_features=out.shape[1], out_features=self.num_units) out = self.post_processing_layer.forward(out) self.block_dict['LeakyReLU_post_processing'] = nn.LeakyReLU() out = self.block_dict['LeakyReLU_post_processing'].forward(out) self.output_layer = nn.Linear(in_features=out.shape[1], out_features=self.num_units) out = self.output_layer.forward(out) self.block_dict['LeakyReLU_output'] = nn.LeakyReLU() out = self.block_dict['LeakyReLU_output'].forward(out) print('Block built with output volume shape', out.shape) def forward(self, x_img): if isinstance(x_img, list): # variable length feature count batch_size = len(x_img) length_per_batch = [] batch_to_g_size = 0 # size of batch that will go into the g network for x_img1 in x_img: length, c = x_img1.shape length_per_batch.append(length) batch_to_g_size += length out = torch.Tensor() out_list = [None] * batch_size for b, x_img1 in enumerate(x_img): out_img = x_img1 """g""" length, c = out_img.shape if self.use_coordinates: if self.coord_tensor.shape[0] != out_img.shape[0]: self.coord_tensor = self.coord_tensor[0].unsqueeze(0).repeat([out_img.shape[0], 1, 1]) #print(self.coord_tensor) out_img = torch.cat([out_img, self.coord_tensor.to(x_img1.device)], dim=2) # x_flat = (64 x 25 x 24) # print('out_img', out_img.shape) x_i = torch.unsqueeze(out_img, 0) # (1xh*wxc) x_i = x_i.repeat(length, 1, 1) # (h*wxh*wxc) x_j = torch.unsqueeze(out_img, 1) # (h*wx1xc) x_j = x_j.repeat(1, length, 1) # (h*wxh*wxc) # concatenate all together per_location_feature = torch.cat([x_i, x_j], 2) # (h*wxh*wx2*c) out_list[b] = per_location_feature.view( per_location_feature.shape[0] * per_location_feature.shape[1], per_location_feature.shape[2]) out = torch.cat(out_list) #print(out.shape) for idx_layer in range(self.num_layers): out = self.block_dict['g_fcc_{}'.format(idx_layer)].forward(out) out = self.block_dict['LeakyReLU_{}'.format(idx_layer)].forward(out) #print(out.shape) # reshape again and sum out_idx = 0 #out_list = [None] * batch_size for b in range(batch_size): out_list[b] = out[out_idx:out_idx+length_per_batch[b] ** 2].view(length_per_batch[b], length_per_batch[b], -1) out_list[b] = out_list[b].sum(0).sum(0).unsqueeze(0) out_idx += length_per_batch[b] ** 2 out = torch.cat(out_list, 0) #print(out.shape) """f""" out = self.post_processing_layer.forward(out) out = self.block_dict['LeakyReLU_post_processing'].forward(out) out = self.output_layer.forward(out) out = self.block_dict['LeakyReLU_output'].forward(out) # print('Block built with output volume shape', out.shape) return out else: # constant feature count out_img = x_img """g""" b, length, c = out_img.shape if self.use_coordinates: if self.coord_tensor.shape[0] != out_img.shape[0]: self.coord_tensor = self.coord_tensor[0].unsqueeze(0).repeat([out_img.shape[0], 1, 1]) #print(self.coord_tensor) out_img = torch.cat([out_img, self.coord_tensor.to(x_img.device)], dim=2) # x_flat = (64 x 25 x 24) # print('out_img', out_img.shape) x_i = torch.unsqueeze(out_img, 1) # (1xh*wxc) x_i = x_i.repeat(1, length, 1, 1) # (h*wxh*wxc) x_j = torch.unsqueeze(out_img, 2) # (h*wx1xc) x_j = x_j.repeat(1, 1, length, 1) # (h*wxh*wxc) # concatenate all together per_location_feature = torch.cat([x_i, x_j], 3) # (h*wxh*wx2*c) out = per_location_feature.view( per_location_feature.shape[0] * per_location_feature.shape[1] * per_location_feature.shape[2], per_location_feature.shape[3]) for idx_layer in range(self.num_layers): out = self.block_dict['g_fcc_{}'.format(idx_layer)].forward(out) out = self.block_dict['LeakyReLU_{}'.format(idx_layer)].forward(out) # reshape again and sum # print(out.shape) out = out.view(per_location_feature.shape[0], per_location_feature.shape[1], per_location_feature.shape[2], -1) #out = out.sum(1).sum(1) out = out.mean(1).mean(1) """f""" out = self.post_processing_layer.forward(out) out = self.block_dict['LeakyReLU_post_processing'].forward(out) out = self.output_layer.forward(out) out = self.block_dict['LeakyReLU_output'].forward(out) # print('Block built with output volume shape', out.shape) return out
pyvideoai/models/epic/BatchRelationalModule1D.py
import torch import numpy as np from torch import nn class BatchRelationalModule(nn.Module): def __init__(self, input_feature_dim, use_coordinates=False, num_layers=2, num_units=64): super(BatchRelationalModule, self).__init__() self.input_feature_dim = input_feature_dim self.block_dict = nn.ModuleDict() self.first_time = True self.use_coordinates = use_coordinates self.num_layers = num_layers self.num_units = num_units self.build_block() def build_block(self): print("Assuming input is of size (b=4, num_object=4, input_feature_dim=%d)" % self.input_feature_dim) out_img = torch.zeros((4, 4, self.input_feature_dim)) """g""" b, length, c = out_img.shape print(out_img.shape) # x_flat = (64 x 25 x 24) if self.use_coordinates: self.coord_tensor = [] for i in range(length): self.coord_tensor.append(torch.Tensor(np.array([i]))) self.coord_tensor = torch.stack(self.coord_tensor, dim=0).unsqueeze(0) if self.coord_tensor.shape[0] != out_img.shape[0]: self.coord_tensor = self.coord_tensor[0].unsqueeze(0).repeat([out_img.shape[0], 1, 1]) out_img = torch.cat([out_img, self.coord_tensor], dim=2) x_i = torch.unsqueeze(out_img, 1) # (1xh*wxc) x_i = x_i.repeat(1, length, 1, 1) # (h*wxh*wxc) x_j = torch.unsqueeze(out_img, 2) # (h*wx1xc) x_j = x_j.repeat(1, 1, length, 1) # (h*wxh*wxc) # concatenate all together per_location_feature = torch.cat([x_i, x_j], 3) # (h*wxh*wx2*c) out = per_location_feature.view( per_location_feature.shape[0] * per_location_feature.shape[1] * per_location_feature.shape[2], per_location_feature.shape[3]) print(out.shape) for idx_layer in range(self.num_layers): self.block_dict['g_fcc_{}'.format(idx_layer)] = nn.Linear(out.shape[1], out_features=self.num_units, bias=True) out = self.block_dict['g_fcc_{}'.format(idx_layer)].forward(out) self.block_dict['LeakyReLU_{}'.format(idx_layer)] = nn.LeakyReLU() out = self.block_dict['LeakyReLU_{}'.format(idx_layer)].forward(out) # reshape again and sum print(out.shape) out = out.view(per_location_feature.shape[0], per_location_feature.shape[1], per_location_feature.shape[2], -1) out = out.sum(1).sum(1) print('here', out.shape) """f""" self.post_processing_layer = nn.Linear(in_features=out.shape[1], out_features=self.num_units) out = self.post_processing_layer.forward(out) self.block_dict['LeakyReLU_post_processing'] = nn.LeakyReLU() out = self.block_dict['LeakyReLU_post_processing'].forward(out) self.output_layer = nn.Linear(in_features=out.shape[1], out_features=self.num_units) out = self.output_layer.forward(out) self.block_dict['LeakyReLU_output'] = nn.LeakyReLU() out = self.block_dict['LeakyReLU_output'].forward(out) print('Block built with output volume shape', out.shape) def forward(self, x_img): if isinstance(x_img, list): # variable length feature count batch_size = len(x_img) length_per_batch = [] batch_to_g_size = 0 # size of batch that will go into the g network for x_img1 in x_img: length, c = x_img1.shape length_per_batch.append(length) batch_to_g_size += length out = torch.Tensor() out_list = [None] * batch_size for b, x_img1 in enumerate(x_img): out_img = x_img1 """g""" length, c = out_img.shape if self.use_coordinates: if self.coord_tensor.shape[0] != out_img.shape[0]: self.coord_tensor = self.coord_tensor[0].unsqueeze(0).repeat([out_img.shape[0], 1, 1]) #print(self.coord_tensor) out_img = torch.cat([out_img, self.coord_tensor.to(x_img1.device)], dim=2) # x_flat = (64 x 25 x 24) # print('out_img', out_img.shape) x_i = torch.unsqueeze(out_img, 0) # (1xh*wxc) x_i = x_i.repeat(length, 1, 1) # (h*wxh*wxc) x_j = torch.unsqueeze(out_img, 1) # (h*wx1xc) x_j = x_j.repeat(1, length, 1) # (h*wxh*wxc) # concatenate all together per_location_feature = torch.cat([x_i, x_j], 2) # (h*wxh*wx2*c) out_list[b] = per_location_feature.view( per_location_feature.shape[0] * per_location_feature.shape[1], per_location_feature.shape[2]) out = torch.cat(out_list) #print(out.shape) for idx_layer in range(self.num_layers): out = self.block_dict['g_fcc_{}'.format(idx_layer)].forward(out) out = self.block_dict['LeakyReLU_{}'.format(idx_layer)].forward(out) #print(out.shape) # reshape again and sum out_idx = 0 #out_list = [None] * batch_size for b in range(batch_size): out_list[b] = out[out_idx:out_idx+length_per_batch[b] ** 2].view(length_per_batch[b], length_per_batch[b], -1) out_list[b] = out_list[b].sum(0).sum(0).unsqueeze(0) out_idx += length_per_batch[b] ** 2 out = torch.cat(out_list, 0) #print(out.shape) """f""" out = self.post_processing_layer.forward(out) out = self.block_dict['LeakyReLU_post_processing'].forward(out) out = self.output_layer.forward(out) out = self.block_dict['LeakyReLU_output'].forward(out) # print('Block built with output volume shape', out.shape) return out else: # constant feature count out_img = x_img """g""" b, length, c = out_img.shape if self.use_coordinates: if self.coord_tensor.shape[0] != out_img.shape[0]: self.coord_tensor = self.coord_tensor[0].unsqueeze(0).repeat([out_img.shape[0], 1, 1]) #print(self.coord_tensor) out_img = torch.cat([out_img, self.coord_tensor.to(x_img.device)], dim=2) # x_flat = (64 x 25 x 24) # print('out_img', out_img.shape) x_i = torch.unsqueeze(out_img, 1) # (1xh*wxc) x_i = x_i.repeat(1, length, 1, 1) # (h*wxh*wxc) x_j = torch.unsqueeze(out_img, 2) # (h*wx1xc) x_j = x_j.repeat(1, 1, length, 1) # (h*wxh*wxc) # concatenate all together per_location_feature = torch.cat([x_i, x_j], 3) # (h*wxh*wx2*c) out = per_location_feature.view( per_location_feature.shape[0] * per_location_feature.shape[1] * per_location_feature.shape[2], per_location_feature.shape[3]) for idx_layer in range(self.num_layers): out = self.block_dict['g_fcc_{}'.format(idx_layer)].forward(out) out = self.block_dict['LeakyReLU_{}'.format(idx_layer)].forward(out) # reshape again and sum # print(out.shape) out = out.view(per_location_feature.shape[0], per_location_feature.shape[1], per_location_feature.shape[2], -1) #out = out.sum(1).sum(1) out = out.mean(1).mean(1) """f""" out = self.post_processing_layer.forward(out) out = self.block_dict['LeakyReLU_post_processing'].forward(out) out = self.output_layer.forward(out) out = self.block_dict['LeakyReLU_output'].forward(out) # print('Block built with output volume shape', out.shape) return out
0.792745
0.475727
r""" A set of utilities to create/open postgres databases for SQLAlchemy. Note, prior to running this scripts, an empty database should be available. This may be created with the following instructions: postgres=# create database <db_name> owner=<user>; @file sessions_postgres.py @author <NAME>, <NAME> """ from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import scoped_session from sqlalchemy.pool import NullPool from m4db_database.configuration import read_config_from_environ from m4db_database.decorators import static from m4db_database import global_vars @static(engine=None, Session=None) def get_session(user=None, database=None, host=None, password=None, scoped=False, echo=False, nullpool=False): r""" Retrieve an open database connection session, if user, database and host are None then attempt to use data stored in M4DB_CONFIG environment variable. Args: user: the database user. database: the name of the database under which to create database objects. host: the host on which the database lives. password: <PASSWORD>. scoped: if true return a 'scoped' session otherwise don't. echo: boolean (default False) set to True if verbose SQLAlchemy output is required. nullpool: boolean (default False) we should use the null pool instead of pooled connections. Returns: A session connection to the database. """ if get_session.engine is None: if user is None and database is None and host is None: config = read_config_from_environ() db_uri = config["db_uri"] else: if user is None and host is None and password is None: db_uri = global_vars.POSTGRES_DATABASE_URI.format( database=database ) elif password is None: db_uri = global_vars.POSTGRES_DATABASE_USER_HOST_URI.format( user=user, host=host, database=database ) else: db_uri = global_vars.POSTGRES_DATABASE_USER_HOST_PASSWORD_URI.format( user=user, host=host, database=database, password=password ) if nullpool: get_session.engine = create_engine(db_uri, echo=echo, poolclass=NullPool) else: get_session.engine = create_engine(db_uri, echo=echo) if get_session.Session is None: get_session.Session = sessionmaker( bind=get_session.engine, autoflush=True, autocommit=False ) if scoped: return scoped_session(get_session.Session) else: return get_session.Session()
lib/m4db_database/sessions_postgres.py
r""" A set of utilities to create/open postgres databases for SQLAlchemy. Note, prior to running this scripts, an empty database should be available. This may be created with the following instructions: postgres=# create database <db_name> owner=<user>; @file sessions_postgres.py @author <NAME>, <NAME> """ from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import scoped_session from sqlalchemy.pool import NullPool from m4db_database.configuration import read_config_from_environ from m4db_database.decorators import static from m4db_database import global_vars @static(engine=None, Session=None) def get_session(user=None, database=None, host=None, password=None, scoped=False, echo=False, nullpool=False): r""" Retrieve an open database connection session, if user, database and host are None then attempt to use data stored in M4DB_CONFIG environment variable. Args: user: the database user. database: the name of the database under which to create database objects. host: the host on which the database lives. password: <PASSWORD>. scoped: if true return a 'scoped' session otherwise don't. echo: boolean (default False) set to True if verbose SQLAlchemy output is required. nullpool: boolean (default False) we should use the null pool instead of pooled connections. Returns: A session connection to the database. """ if get_session.engine is None: if user is None and database is None and host is None: config = read_config_from_environ() db_uri = config["db_uri"] else: if user is None and host is None and password is None: db_uri = global_vars.POSTGRES_DATABASE_URI.format( database=database ) elif password is None: db_uri = global_vars.POSTGRES_DATABASE_USER_HOST_URI.format( user=user, host=host, database=database ) else: db_uri = global_vars.POSTGRES_DATABASE_USER_HOST_PASSWORD_URI.format( user=user, host=host, database=database, password=password ) if nullpool: get_session.engine = create_engine(db_uri, echo=echo, poolclass=NullPool) else: get_session.engine = create_engine(db_uri, echo=echo) if get_session.Session is None: get_session.Session = sessionmaker( bind=get_session.engine, autoflush=True, autocommit=False ) if scoped: return scoped_session(get_session.Session) else: return get_session.Session()
0.684475
0.180323
from time import sleep from schedule import clear, every, get_jobs, run_pending from src.config.constants import INTERNAL_SCHEDULING from src.scripts.checkin import random_checkin from src.scripts.checkout import random_checkout from src.utils.logger import PlxLogger from src.utils.plextime_session import PlextimeSession LOGGER = PlxLogger.get_logger("start") DAYS = { 1: "monday", 2: "tuesday", 3: "wednesday", 4: "thursday", 5: "friday", 6: "saturday", 7: "sunday", } def schedule_tasks() -> None: if get_jobs("check"): LOGGER.info("Cleaning up old schedulings") clear("check") timetable = PlextimeSession().retrieve_current_timetable() if timetable: LOGGER.info("Starting scheduling") for day_schedule in timetable: day_name = DAYS[day_schedule["week_day"]] checkin_hour = day_schedule["hour_in"] checkout_hour = day_schedule["hour_out"] getattr(every(), day_name).at(checkin_hour).do(random_checkin).tag( "check", "checkin-tasks" ) getattr(every(), day_name).at(checkout_hour).do(random_checkout).tag( "check", "checkout-tasks" ) LOGGER.info( f"{day_name.capitalize()} scheduled: check-in at {checkin_hour} and" f" check-out at {checkout_hour}" ) def main() -> None: if INTERNAL_SCHEDULING: LOGGER.info("Internal scheduling enabled") timetable_update_weekday = DAYS[1] timetable_update_time = "03:00" getattr(every(), timetable_update_weekday).at(timetable_update_time).do( schedule_tasks ).tag("schedule") LOGGER.info( "Timetable updating task enabled for" f" {timetable_update_weekday.capitalize()}s at {timetable_update_time}" ) schedule_tasks() while True: run_pending() sleep(1) else: LOGGER.info("Using external scheduling") while True: LOGGER.info("External scheduling: keep-alive") sleep(60 * 60 * 8) if __name__ == "__main__": main()
start.py
from time import sleep from schedule import clear, every, get_jobs, run_pending from src.config.constants import INTERNAL_SCHEDULING from src.scripts.checkin import random_checkin from src.scripts.checkout import random_checkout from src.utils.logger import PlxLogger from src.utils.plextime_session import PlextimeSession LOGGER = PlxLogger.get_logger("start") DAYS = { 1: "monday", 2: "tuesday", 3: "wednesday", 4: "thursday", 5: "friday", 6: "saturday", 7: "sunday", } def schedule_tasks() -> None: if get_jobs("check"): LOGGER.info("Cleaning up old schedulings") clear("check") timetable = PlextimeSession().retrieve_current_timetable() if timetable: LOGGER.info("Starting scheduling") for day_schedule in timetable: day_name = DAYS[day_schedule["week_day"]] checkin_hour = day_schedule["hour_in"] checkout_hour = day_schedule["hour_out"] getattr(every(), day_name).at(checkin_hour).do(random_checkin).tag( "check", "checkin-tasks" ) getattr(every(), day_name).at(checkout_hour).do(random_checkout).tag( "check", "checkout-tasks" ) LOGGER.info( f"{day_name.capitalize()} scheduled: check-in at {checkin_hour} and" f" check-out at {checkout_hour}" ) def main() -> None: if INTERNAL_SCHEDULING: LOGGER.info("Internal scheduling enabled") timetable_update_weekday = DAYS[1] timetable_update_time = "03:00" getattr(every(), timetable_update_weekday).at(timetable_update_time).do( schedule_tasks ).tag("schedule") LOGGER.info( "Timetable updating task enabled for" f" {timetable_update_weekday.capitalize()}s at {timetable_update_time}" ) schedule_tasks() while True: run_pending() sleep(1) else: LOGGER.info("Using external scheduling") while True: LOGGER.info("External scheduling: keep-alive") sleep(60 * 60 * 8) if __name__ == "__main__": main()
0.457864
0.207576
import os import pickle from astropy.table import Table from jianbing import scatter from jianbing import wlensing TOPN_DIR = '/tigress/sh19/work/topn/' # Lensing data using medium photo-z quality cut s16a_lensing = os.path.join(TOPN_DIR, 'prepare', 's16a_weak_lensing_medium.hdf5') # Random s16a_rand = Table.read(s16a_lensing, path='random') # Pre-compute results using medium photo-z quality cut s16a_precompute_med = os.path.join( TOPN_DIR, 'precompute', 'topn_public_s16a_medium_precompute.hdf5') # Pre-compute results for each individual samples # HSC massive galaxies hsc = Table.read(s16a_precompute_med, path='hsc_extra') # TopN bins topn_bins = Table.read( os.path.join(TOPN_DIR, 'precompute', 'topn_bins.fits')) # Tablulated simulation results sim_cat = Table.read( os.path.join(TOPN_DIR, 'precompute', 'sim_merge_all_dsig.fits')) # HSC properties to use # Stellar or halo mass measurements for HSC galaxies hsc_mass = [ 'logm_cmod', 'logm_5', 'logm_10', 'logm_15', 'logm_25', 'logm_30', 'logm_40', 'logm_50', 'logm_60', 'logm_75', 'logm_100', 'logm_120', 'logm_150', 'logm_max', 'logmh_vir_forest', 'logmh_vir_plane', 'logmh_vir_symbol', 'logm_extra_120', 'logm_extra_150', 'logm_extra_200', 'logm_extra_300', 'logm_r50', 'logm_r50_half', 'logm_2_r50', 'logm_3_r50', 'logm_4_r50', 'logm_5_r50', 'logm_6_r50', 'logm_10_100', 'logm_30_100', 'logm_40_100', 'logm_50_100', 'logm_60_100', 'logm_50_150', 'logm_60_150', 'logm_75_150', 'logm_40_120', 'logm_50_120', 'logm_60_120', 'logm_75_120', 'logm_50_120_extra', 'logm_50_150_extra', 'logm_50_200_extra', 'logm_50_300_extra', 'logm_2_4_r50', 'logm_2_6_r50', 'logm_3_4_r50', 'logm_3_5_r50', 'logm_3_6_r50', 'logm_4_6_r50' ] # Size measurements for HSC galaxies hsc_size = ['r50_100', 'r80_100', 'r90_100', 'r50_120', 'r80_120', 'r90_120', 'r50_max', 'r80_max', 'r90_max', 'logr_vir_forest'] # S18A bright star mask bsm_s18a = hsc['flag'] > 0 # General mask for HSC galaxies mask = ( (hsc['c82_100'] <= 18.) & (hsc['logm_100'] - hsc['logm_50'] <= 0.2) & bsm_s18a ) # General mask for HSC size measurements size_mask = ( mask & (hsc['logm_max'] >= 11.3) & (hsc['r80_100'] <= 60.0) & (hsc['r90_100'] <= 60.0) ) # Mask to select "central" galaxies cen_mask_1 = hsc['cen_mask_1'] > 0 cen_mask_2 = hsc['cen_mask_2'] > 0 cen_mask_3 = hsc['cen_mask_3'] > 0 n_rand = 200000 n_boot = 1000 n_jobs = 8 topn_galaxies = {} topn_galaxies_sum = {} # Stellar mass related for col in hsc_mass: # Default test with both jackknife and bootstrap error topn_galaxies[col] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=mask, n_rand=n_rand, n_boot=n_boot, verbose=True, n_jobs=n_jobs) topn_galaxies_sum[col] = scatter.compare_model_dsigma( topn_galaxies[col], sim_cat, model_err=False, poly=True, verbose=True) # The whole sample, without applying any mask; no bootstrap error topn_galaxies[col + '_all'] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=None, n_rand=n_rand, verbose=False, n_jobs=n_jobs, n_boot=200) topn_galaxies_sum[col + '_all'] = scatter.compare_model_dsigma( topn_galaxies[col + '_all'], sim_cat, model_err=False, poly=True, verbose=False) # Applying central mask 1; no bootstrap error topn_galaxies[col + '_cen1'] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=(mask & cen_mask_1), n_rand=n_rand, verbose=False, n_jobs=n_jobs, n_boot=200) topn_galaxies_sum[col + '_cen1'] = scatter.compare_model_dsigma( topn_galaxies[col + '_cen1'], sim_cat, model_err=False, poly=True, verbose=False) # Applying central mask 2; no bootstrap error topn_galaxies[col + '_cen2'] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=(mask & cen_mask_2), n_rand=n_rand, verbose=False, n_jobs=n_jobs, n_boot=200) topn_galaxies_sum[col + '_cen2'] = scatter.compare_model_dsigma( topn_galaxies[col + '_cen2'], sim_cat, model_err=False, poly=True, verbose=False) # Applying central mask 3; no bootstrap error topn_galaxies[col + '_cen3'] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=(mask & cen_mask_3), n_rand=n_rand, verbose=False, n_jobs=n_jobs, n_boot=200) topn_galaxies_sum[col + '_cen3'] = scatter.compare_model_dsigma( topn_galaxies[col + '_cen3'], sim_cat, model_err=False, poly=True, verbose=False) # Galaxy size related for col in hsc_size: # Default test with both jackknife and bootstrap error topn_galaxies[col] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=(mask & size_mask), n_rand=n_rand, n_boot=n_boot, verbose=True, n_jobs=n_jobs) topn_galaxies_sum[col] = scatter.compare_model_dsigma( topn_galaxies[col], sim_cat, model_err=False, poly=True, verbose=False) # The whole sample, without applying any mask; no bootstrap error topn_galaxies[col + '_all'] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=None, n_rand=n_rand, verbose=False, n_jobs=n_jobs, n_boot=200) topn_galaxies_sum[col + '_all'] = scatter.compare_model_dsigma( topn_galaxies[col + '_all'], sim_cat, model_err=False, poly=True, verbose=False) # Applying central mask 1; no bootstrap error topn_galaxies[col + '_cen1'] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=(mask & size_mask & cen_mask_1), n_rand=n_rand, n_boot=n_boot, verbose=False, n_jobs=n_jobs) topn_galaxies_sum[col + '_cen1'] = scatter.compare_model_dsigma( topn_galaxies[col + '_cen1'], sim_cat, model_err=False, poly=True, verbose=False) # Applying central mask 2; no bootstrap error topn_galaxies[col + '_cen2'] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=(mask & size_mask & cen_mask_2), n_rand=n_rand, n_boot=n_boot, verbose=False) topn_galaxies_sum[col + '_cen2'] = scatter.compare_model_dsigma( topn_galaxies[col + '_cen2'], sim_cat, model_err=False, poly=True, verbose=False) # Applying central mask 3; no bootstrap error topn_galaxies[col + '_cen3'] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=(mask & size_mask & cen_mask_3), n_rand=n_rand, n_boot=n_boot, verbose=False) topn_galaxies_sum[col + '_cen3'] = scatter.compare_model_dsigma( topn_galaxies[col + '_cen3'], sim_cat, model_err=False, poly=True, verbose=False) pickle.dump( topn_galaxies, open(os.path.join(TOPN_DIR, 'topn_galaxies.pkl'), "wb")) pickle.dump( topn_galaxies_sum, open(os.path.join(TOPN_DIR, 'topn_galaxies_sum.pkl'), "wb"))
script/compute_dsigma_galaxies.py
import os import pickle from astropy.table import Table from jianbing import scatter from jianbing import wlensing TOPN_DIR = '/tigress/sh19/work/topn/' # Lensing data using medium photo-z quality cut s16a_lensing = os.path.join(TOPN_DIR, 'prepare', 's16a_weak_lensing_medium.hdf5') # Random s16a_rand = Table.read(s16a_lensing, path='random') # Pre-compute results using medium photo-z quality cut s16a_precompute_med = os.path.join( TOPN_DIR, 'precompute', 'topn_public_s16a_medium_precompute.hdf5') # Pre-compute results for each individual samples # HSC massive galaxies hsc = Table.read(s16a_precompute_med, path='hsc_extra') # TopN bins topn_bins = Table.read( os.path.join(TOPN_DIR, 'precompute', 'topn_bins.fits')) # Tablulated simulation results sim_cat = Table.read( os.path.join(TOPN_DIR, 'precompute', 'sim_merge_all_dsig.fits')) # HSC properties to use # Stellar or halo mass measurements for HSC galaxies hsc_mass = [ 'logm_cmod', 'logm_5', 'logm_10', 'logm_15', 'logm_25', 'logm_30', 'logm_40', 'logm_50', 'logm_60', 'logm_75', 'logm_100', 'logm_120', 'logm_150', 'logm_max', 'logmh_vir_forest', 'logmh_vir_plane', 'logmh_vir_symbol', 'logm_extra_120', 'logm_extra_150', 'logm_extra_200', 'logm_extra_300', 'logm_r50', 'logm_r50_half', 'logm_2_r50', 'logm_3_r50', 'logm_4_r50', 'logm_5_r50', 'logm_6_r50', 'logm_10_100', 'logm_30_100', 'logm_40_100', 'logm_50_100', 'logm_60_100', 'logm_50_150', 'logm_60_150', 'logm_75_150', 'logm_40_120', 'logm_50_120', 'logm_60_120', 'logm_75_120', 'logm_50_120_extra', 'logm_50_150_extra', 'logm_50_200_extra', 'logm_50_300_extra', 'logm_2_4_r50', 'logm_2_6_r50', 'logm_3_4_r50', 'logm_3_5_r50', 'logm_3_6_r50', 'logm_4_6_r50' ] # Size measurements for HSC galaxies hsc_size = ['r50_100', 'r80_100', 'r90_100', 'r50_120', 'r80_120', 'r90_120', 'r50_max', 'r80_max', 'r90_max', 'logr_vir_forest'] # S18A bright star mask bsm_s18a = hsc['flag'] > 0 # General mask for HSC galaxies mask = ( (hsc['c82_100'] <= 18.) & (hsc['logm_100'] - hsc['logm_50'] <= 0.2) & bsm_s18a ) # General mask for HSC size measurements size_mask = ( mask & (hsc['logm_max'] >= 11.3) & (hsc['r80_100'] <= 60.0) & (hsc['r90_100'] <= 60.0) ) # Mask to select "central" galaxies cen_mask_1 = hsc['cen_mask_1'] > 0 cen_mask_2 = hsc['cen_mask_2'] > 0 cen_mask_3 = hsc['cen_mask_3'] > 0 n_rand = 200000 n_boot = 1000 n_jobs = 8 topn_galaxies = {} topn_galaxies_sum = {} # Stellar mass related for col in hsc_mass: # Default test with both jackknife and bootstrap error topn_galaxies[col] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=mask, n_rand=n_rand, n_boot=n_boot, verbose=True, n_jobs=n_jobs) topn_galaxies_sum[col] = scatter.compare_model_dsigma( topn_galaxies[col], sim_cat, model_err=False, poly=True, verbose=True) # The whole sample, without applying any mask; no bootstrap error topn_galaxies[col + '_all'] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=None, n_rand=n_rand, verbose=False, n_jobs=n_jobs, n_boot=200) topn_galaxies_sum[col + '_all'] = scatter.compare_model_dsigma( topn_galaxies[col + '_all'], sim_cat, model_err=False, poly=True, verbose=False) # Applying central mask 1; no bootstrap error topn_galaxies[col + '_cen1'] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=(mask & cen_mask_1), n_rand=n_rand, verbose=False, n_jobs=n_jobs, n_boot=200) topn_galaxies_sum[col + '_cen1'] = scatter.compare_model_dsigma( topn_galaxies[col + '_cen1'], sim_cat, model_err=False, poly=True, verbose=False) # Applying central mask 2; no bootstrap error topn_galaxies[col + '_cen2'] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=(mask & cen_mask_2), n_rand=n_rand, verbose=False, n_jobs=n_jobs, n_boot=200) topn_galaxies_sum[col + '_cen2'] = scatter.compare_model_dsigma( topn_galaxies[col + '_cen2'], sim_cat, model_err=False, poly=True, verbose=False) # Applying central mask 3; no bootstrap error topn_galaxies[col + '_cen3'] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=(mask & cen_mask_3), n_rand=n_rand, verbose=False, n_jobs=n_jobs, n_boot=200) topn_galaxies_sum[col + '_cen3'] = scatter.compare_model_dsigma( topn_galaxies[col + '_cen3'], sim_cat, model_err=False, poly=True, verbose=False) # Galaxy size related for col in hsc_size: # Default test with both jackknife and bootstrap error topn_galaxies[col] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=(mask & size_mask), n_rand=n_rand, n_boot=n_boot, verbose=True, n_jobs=n_jobs) topn_galaxies_sum[col] = scatter.compare_model_dsigma( topn_galaxies[col], sim_cat, model_err=False, poly=True, verbose=False) # The whole sample, without applying any mask; no bootstrap error topn_galaxies[col + '_all'] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=None, n_rand=n_rand, verbose=False, n_jobs=n_jobs, n_boot=200) topn_galaxies_sum[col + '_all'] = scatter.compare_model_dsigma( topn_galaxies[col + '_all'], sim_cat, model_err=False, poly=True, verbose=False) # Applying central mask 1; no bootstrap error topn_galaxies[col + '_cen1'] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=(mask & size_mask & cen_mask_1), n_rand=n_rand, n_boot=n_boot, verbose=False, n_jobs=n_jobs) topn_galaxies_sum[col + '_cen1'] = scatter.compare_model_dsigma( topn_galaxies[col + '_cen1'], sim_cat, model_err=False, poly=True, verbose=False) # Applying central mask 2; no bootstrap error topn_galaxies[col + '_cen2'] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=(mask & size_mask & cen_mask_2), n_rand=n_rand, n_boot=n_boot, verbose=False) topn_galaxies_sum[col + '_cen2'] = scatter.compare_model_dsigma( topn_galaxies[col + '_cen2'], sim_cat, model_err=False, poly=True, verbose=False) # Applying central mask 3; no bootstrap error topn_galaxies[col + '_cen3'] = wlensing.gather_topn_dsigma_profiles( hsc, s16a_rand, topn_bins, col, mask=(mask & size_mask & cen_mask_3), n_rand=n_rand, n_boot=n_boot, verbose=False) topn_galaxies_sum[col + '_cen3'] = scatter.compare_model_dsigma( topn_galaxies[col + '_cen3'], sim_cat, model_err=False, poly=True, verbose=False) pickle.dump( topn_galaxies, open(os.path.join(TOPN_DIR, 'topn_galaxies.pkl'), "wb")) pickle.dump( topn_galaxies_sum, open(os.path.join(TOPN_DIR, 'topn_galaxies_sum.pkl'), "wb"))
0.456894
0.20199
import bleach from flask import Markup def format_approve_button(s): messages = { "INTERNAL_REVIEW": "Save &amp; Send to review", "DEPARTMENT_REVIEW": "Send to department for review", "APPROVED": "Approve for publishing", } return messages.get(s, "") def format_friendly_date(date): if date is None: return "" return date.strftime("%d %B %Y").lstrip("0") def format_friendly_short_date_with_year(date): if date is None: return "" return date.strftime("%d %b %Y").lstrip("0") def format_friendly_short_date(date): if date is None: return "" return date.strftime("%d %b").lstrip("0") def index_of_last_initial_zero(list_): index_of_last_zero = None for index, value in enumerate(list_): if value == 0: index_of_last_zero = index else: break if index_of_last_zero is None: raise ValueError("List contains no 0 values") return index_of_last_zero def format_status(state): status_names = { "DRAFT": "Draft", "INTERNAL_REVIEW": "Internal&nbsp;review", "DEPARTMENT_REVIEW": "Department&nbsp;review", "APPROVED": "Published", "REJECTED": "Rejected", } return status_names.get(state, state.replace("_", "&nbsp;").capitalize()) def yesno(state): if state is True: return "yes" elif state is False: return "no" return state def models_to_dicts(items): """Call `.to_dict()` on each item of a list; useful for converting a list of model instances into a list of dictionaries suitable for e.g. converting to JSON.""" return [item.to_dict() for item in items] # This is used in the "Export" page to preserve line breaks in saved text area data to make any Markdown # (e.g. bullet points) copy-and-pasteable from the exported version back into the form fields def html_line_breaks(string): return Markup(bleach.clean(string).replace("\n", "<br />") if string else "") def url_with_line_breaks(string): return string.replace("/", "/\N{ZERO WIDTH SPACE}").replace("&", "&\N{ZERO WIDTH SPACE}") if string else string
application/cms/filters.py
import bleach from flask import Markup def format_approve_button(s): messages = { "INTERNAL_REVIEW": "Save &amp; Send to review", "DEPARTMENT_REVIEW": "Send to department for review", "APPROVED": "Approve for publishing", } return messages.get(s, "") def format_friendly_date(date): if date is None: return "" return date.strftime("%d %B %Y").lstrip("0") def format_friendly_short_date_with_year(date): if date is None: return "" return date.strftime("%d %b %Y").lstrip("0") def format_friendly_short_date(date): if date is None: return "" return date.strftime("%d %b").lstrip("0") def index_of_last_initial_zero(list_): index_of_last_zero = None for index, value in enumerate(list_): if value == 0: index_of_last_zero = index else: break if index_of_last_zero is None: raise ValueError("List contains no 0 values") return index_of_last_zero def format_status(state): status_names = { "DRAFT": "Draft", "INTERNAL_REVIEW": "Internal&nbsp;review", "DEPARTMENT_REVIEW": "Department&nbsp;review", "APPROVED": "Published", "REJECTED": "Rejected", } return status_names.get(state, state.replace("_", "&nbsp;").capitalize()) def yesno(state): if state is True: return "yes" elif state is False: return "no" return state def models_to_dicts(items): """Call `.to_dict()` on each item of a list; useful for converting a list of model instances into a list of dictionaries suitable for e.g. converting to JSON.""" return [item.to_dict() for item in items] # This is used in the "Export" page to preserve line breaks in saved text area data to make any Markdown # (e.g. bullet points) copy-and-pasteable from the exported version back into the form fields def html_line_breaks(string): return Markup(bleach.clean(string).replace("\n", "<br />") if string else "") def url_with_line_breaks(string): return string.replace("/", "/\N{ZERO WIDTH SPACE}").replace("&", "&\N{ZERO WIDTH SPACE}") if string else string
0.569853
0.231343
import PyQt5.QtWidgets as Qtw import PyQt5.QtGui as QtGui import PyQt5.QtCore as QtCore from PyQt5.QtCore import Qt from widgets.flow_layout import FlowLayout class LabelWidget(Qtw.QLabel): """ A widget displaying a single label, with it's color """ clicked = QtCore.pyqtSignal() def __init__(self, parent, identifier, name, color): super(LabelWidget, self).__init__(parent) self.color = QtGui.QColor(color) self.identifier = identifier self.setText(name+u" <strong>\x00\xd7</strong>") self.setStyleSheet(""" QLabel{{ border-radius: 5px; border: 1px solid black; background-color: {}; }} """.format(color)) def mousePressEvent(self, event): self.clicked.emit() class NewLabelWidget(Qtw.QLineEdit): """ A widget enabling adding a single label by typing in it """ validate_new = QtCore.pyqtSignal(int) def __init__(self, parent, all_labels): super(NewLabelWidget, self).__init__(parent) self.all_labels = all_labels self.setStyleSheet(""" QLineEdit{{ border-radius: 5px; border: 1px dashed grey; background-color: #f5f5f5; }} """.format()) self.propositions = NewLabelPropositionWidget(self, all_labels) self.propositions.validate_new.connect(lambda e: self.validate_new.emit(e)) self.textChanged.connect(self.handle_change) self.editingFinished.connect(self.handle_editing_finished) def focusInEvent(self, event): print("show prop") self.propositions.show() self.propositions.move(self.mapToGlobal(QtCore.QPoint(0, self.height()))) def focusOutEvent(self, event): print("hide prop") self.propositions.hide() def handle_change(self, text): self.propositions.set_search(text) def handle_editing_finished(self): pass class NewLabelPropositionWidget(Qtw.QWidget): """ A widget displaying propositions for labels, used as a drop-down help list when entering text in a NewLabelWidget """ validate_new = QtCore.pyqtSignal(int) def __init__(self, parent, all_labels): super(NewLabelPropositionWidget, self).__init__(parent) self.all_labels = all_labels self.search_term = "" self.setWindowFlag(Qt.Widget) layout = Qtw.QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.setWindowFlag(Qt.Window + Qt.FramelessWindowHint + Qt.WindowDoesNotAcceptFocus) # self.setWindowModality(Qt.NonModal) self.setStyleSheet(""" QWidget{ border: 1px solid grey; padding: 0; margin 0; background-color: #ffffff; } """) self.update_list() def set_search(self, text): """ Update the propositions, by hiding those not matching the text """ self.search_term = text self.update_list() def update_list(self): # clear sub-widgets while True: item = self.layout().takeAt(0) if item is None: break item.widget().setParent(None) # make the list of propositions, using the search term props = [] if len(self.search_term) == 0: props = self.all_labels else: for label_id, name, color in self.all_labels: if self.search_term.lower() in name.lower(): props.append((label_id, name, color)) # add the propositions for label_id, name, color in props: label = NewLabelDropdownEntry(self, name, color) label.clicked.connect(lambda ident=label_id: self.validate_new.emit(ident)) self.layout().addWidget(label) # text to display if no label is available if len(props) == 0: label = Qtw.QLabel("Pas d'étiquette trouvée") label.setStyleSheet(""" QLabel{ border: 0; margin: 0; background-color: #f5f5f5; color: #858585; } """) self.layout().addWidget(label) self.setFixedSize(self.sizeHint()) class NewLabelDropdownEntry(Qtw.QLabel): """ A widget which is a single dropdown entry in the proposition widget, basically a colorable clickable label """ clicked = QtCore.pyqtSignal() def __init__(self, parent, text, color): super(NewLabelDropdownEntry, self).__init__(text, parent) self.setStyleSheet(""" QLabel{{ border: 0; margin: 0; background-color: {}; color: #020304; }} """.format(color)) def mousePressEvent(self, event): self.clicked.emit() class LabelsWidget(Qtw.QWidget): """ A widget showing all the labels of a transaction """ def __init__(self, parent, all_labels): super(LabelsWidget, self).__init__(parent) layout = FlowLayout(self) self.all_labels = all_labels self.labels = [] self.setLayout(layout) self.update_labels() def add_label(self, identifier): print("added:", identifier) if identifier not in self.labels and identifier in [lb[0] for lb in self.all_labels]: self.labels.append(identifier) self.labels.sort() self.update_labels() def remove_label(self, identifier): print("removed:", identifier) if identifier in self.labels and identifier in [lb[0] for lb in self.all_labels]: self.labels.remove(identifier) self.labels.sort() self.update_labels() def set_labels(self, labels): self.labels = labels self.update_labels() def update_labels(self): # remove all previous labels (+ editor) while True: item = self.layout().takeAt(0) if item is None: break item.widget().setParent(None) # add all the labels for identifier, name, color in self.all_labels: if identifier in self.labels: label = LabelWidget(self, identifier, name, color) label.clicked.connect(lambda ident=identifier: self.remove_label(ident)) self.layout().addWidget(label) # append the editor editor = NewLabelWidget(self, self.all_labels) editor.validate_new.connect(lambda e: self.add_label(e)) self.layout().addWidget(editor)
widgets/labels.py
import PyQt5.QtWidgets as Qtw import PyQt5.QtGui as QtGui import PyQt5.QtCore as QtCore from PyQt5.QtCore import Qt from widgets.flow_layout import FlowLayout class LabelWidget(Qtw.QLabel): """ A widget displaying a single label, with it's color """ clicked = QtCore.pyqtSignal() def __init__(self, parent, identifier, name, color): super(LabelWidget, self).__init__(parent) self.color = QtGui.QColor(color) self.identifier = identifier self.setText(name+u" <strong>\x00\xd7</strong>") self.setStyleSheet(""" QLabel{{ border-radius: 5px; border: 1px solid black; background-color: {}; }} """.format(color)) def mousePressEvent(self, event): self.clicked.emit() class NewLabelWidget(Qtw.QLineEdit): """ A widget enabling adding a single label by typing in it """ validate_new = QtCore.pyqtSignal(int) def __init__(self, parent, all_labels): super(NewLabelWidget, self).__init__(parent) self.all_labels = all_labels self.setStyleSheet(""" QLineEdit{{ border-radius: 5px; border: 1px dashed grey; background-color: #f5f5f5; }} """.format()) self.propositions = NewLabelPropositionWidget(self, all_labels) self.propositions.validate_new.connect(lambda e: self.validate_new.emit(e)) self.textChanged.connect(self.handle_change) self.editingFinished.connect(self.handle_editing_finished) def focusInEvent(self, event): print("show prop") self.propositions.show() self.propositions.move(self.mapToGlobal(QtCore.QPoint(0, self.height()))) def focusOutEvent(self, event): print("hide prop") self.propositions.hide() def handle_change(self, text): self.propositions.set_search(text) def handle_editing_finished(self): pass class NewLabelPropositionWidget(Qtw.QWidget): """ A widget displaying propositions for labels, used as a drop-down help list when entering text in a NewLabelWidget """ validate_new = QtCore.pyqtSignal(int) def __init__(self, parent, all_labels): super(NewLabelPropositionWidget, self).__init__(parent) self.all_labels = all_labels self.search_term = "" self.setWindowFlag(Qt.Widget) layout = Qtw.QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.setWindowFlag(Qt.Window + Qt.FramelessWindowHint + Qt.WindowDoesNotAcceptFocus) # self.setWindowModality(Qt.NonModal) self.setStyleSheet(""" QWidget{ border: 1px solid grey; padding: 0; margin 0; background-color: #ffffff; } """) self.update_list() def set_search(self, text): """ Update the propositions, by hiding those not matching the text """ self.search_term = text self.update_list() def update_list(self): # clear sub-widgets while True: item = self.layout().takeAt(0) if item is None: break item.widget().setParent(None) # make the list of propositions, using the search term props = [] if len(self.search_term) == 0: props = self.all_labels else: for label_id, name, color in self.all_labels: if self.search_term.lower() in name.lower(): props.append((label_id, name, color)) # add the propositions for label_id, name, color in props: label = NewLabelDropdownEntry(self, name, color) label.clicked.connect(lambda ident=label_id: self.validate_new.emit(ident)) self.layout().addWidget(label) # text to display if no label is available if len(props) == 0: label = Qtw.QLabel("Pas d'étiquette trouvée") label.setStyleSheet(""" QLabel{ border: 0; margin: 0; background-color: #f5f5f5; color: #858585; } """) self.layout().addWidget(label) self.setFixedSize(self.sizeHint()) class NewLabelDropdownEntry(Qtw.QLabel): """ A widget which is a single dropdown entry in the proposition widget, basically a colorable clickable label """ clicked = QtCore.pyqtSignal() def __init__(self, parent, text, color): super(NewLabelDropdownEntry, self).__init__(text, parent) self.setStyleSheet(""" QLabel{{ border: 0; margin: 0; background-color: {}; color: #020304; }} """.format(color)) def mousePressEvent(self, event): self.clicked.emit() class LabelsWidget(Qtw.QWidget): """ A widget showing all the labels of a transaction """ def __init__(self, parent, all_labels): super(LabelsWidget, self).__init__(parent) layout = FlowLayout(self) self.all_labels = all_labels self.labels = [] self.setLayout(layout) self.update_labels() def add_label(self, identifier): print("added:", identifier) if identifier not in self.labels and identifier in [lb[0] for lb in self.all_labels]: self.labels.append(identifier) self.labels.sort() self.update_labels() def remove_label(self, identifier): print("removed:", identifier) if identifier in self.labels and identifier in [lb[0] for lb in self.all_labels]: self.labels.remove(identifier) self.labels.sort() self.update_labels() def set_labels(self, labels): self.labels = labels self.update_labels() def update_labels(self): # remove all previous labels (+ editor) while True: item = self.layout().takeAt(0) if item is None: break item.widget().setParent(None) # add all the labels for identifier, name, color in self.all_labels: if identifier in self.labels: label = LabelWidget(self, identifier, name, color) label.clicked.connect(lambda ident=identifier: self.remove_label(ident)) self.layout().addWidget(label) # append the editor editor = NewLabelWidget(self, self.all_labels) editor.validate_new.connect(lambda e: self.add_label(e)) self.layout().addWidget(editor)
0.555918
0.152158
from typing import Tuple, Dict import numpy as np from qecsim.model import Decoder from ...models import ToricCode3D from ...models import Toric3DPauli Indexer = Dict[Tuple[int, int, int], int] class SweepDecoder3D(Decoder): label: str = 'Toric 3D Sweep Decoder' _rng: np.random.Generator max_sweep_factor: int def __init__(self, seed: int = 0, max_sweep_factor: int = 32): self._rng = np.random.default_rng(seed) self.max_sweep_factor = max_sweep_factor def get_face_syndromes( self, code: ToricCode3D, full_syndrome: np.ndarray ) -> np.ndarray: """Get only the syndromes for the vertex Z stabilizers. Z vertex stabiziliers syndromes are discarded for this decoder. """ n_faces = code.Hz.shape[0] face_syndromes = full_syndrome[:n_faces] return face_syndromes def flip_edge( self, index: Tuple, signs: Indexer, code: ToricCode3D ): """Flip signs at index and update correction.""" x, y, z = index edge = tuple(np.mod(index, 2)) L_x, L_y, L_z = code.size limits = (2*L_x, 2*L_y, 2*L_z) if edge == (1, 0, 0): face_1 = (x, y + 1, z) face_2 = (x, y - 1, z) face_3 = (x, y, z + 1) face_4 = (x, y, z - 1) elif edge == (0, 1, 0): face_1 = (x, y, z + 1) face_2 = (x, y, z - 1) face_3 = (x + 1, y, z) face_4 = (x - 1, y, z) elif edge == (0, 0, 1): face_1 = (x + 1, y, z) face_2 = (x - 1, y, z) face_3 = (x, y + 1, z) face_4 = (x, y - 1, z) # Impose periodic boundary conditions. index_1 = tuple(np.mod(face_1, limits)) index_2 = tuple(np.mod(face_2, limits)) index_3 = tuple(np.mod(face_3, limits)) index_4 = tuple(np.mod(face_4, limits)) # Flip the signs (well actually 0s and 1s). signs[index_1] = 1 - signs[index_1] # type: ignore signs[index_2] = 1 - signs[index_2] # type: ignore signs[index_3] = 1 - signs[index_3] # type: ignore signs[index_4] = 1 - signs[index_4] # type: ignore def get_default_direction(self): """The default direction when all faces are excited.""" direction = int(self._rng.choice([0, 1, 2], size=1)) return direction # TODO: make this more space-efficient, don't store zeros. def get_initial_state( self, code: ToricCode3D, syndrome: np.ndarray ) -> Indexer: """Get initial cellular automaton state from syndrome.""" n_faces = len(code.face_index) face_syndromes = syndrome[:n_faces] signs = dict() for face, index in code.face_index.items(): signs[face] = int(face_syndromes[index]) return signs def decode( self, code: ToricCode3D, syndrome: np.ndarray ) -> np.ndarray: """Get Z corrections given measured syndrome.""" # Maximum number of times to sweep before giving up. max_sweeps = self.max_sweep_factor*int(max(code.size)) # The syndromes represented as an array of 0s and 1s. signs = self.get_initial_state(code, syndrome) # Keep track of the correction needed. correction = Toric3DPauli(code) # Initialize the number of sweeps. i_sweep = 0 # Keep sweeping until there are no syndromes. while any(signs.values()) and i_sweep < max_sweeps: signs = self.sweep_move(signs, correction, code) i_sweep += 1 return correction.to_bsf() def sweep_move( self, signs: Indexer, correction: Toric3DPauli, code: ToricCode3D ) -> Indexer: """Apply the sweep move once.""" new_signs = signs.copy() flip_locations = [] L_x, L_y, L_z = code.size limits = (2*L_x, 2*L_y, 2*L_z) # Sweep through every edge. for x, y, z in code.vertex_index.keys(): # Get the syndromes on each face in sweep direction. x_face = signs[tuple(np.mod((x, y + 1, z + 1), limits))] # type: ignore # noqa: E501 y_face = signs[tuple(np.mod((x + 1, y, z + 1), limits))] # type: ignore # noqa: E501 z_face = signs[tuple(np.mod((x + 1, y + 1, z), limits))] # type: ignore # noqa: E501 x_edge = tuple(np.mod((x + 1, y, z), limits)) y_edge = tuple(np.mod((x, y + 1, z), limits)) z_edge = tuple(np.mod((x, y, z + 1), limits)) if x_face and y_face and z_face: direction = self.get_default_direction() flip_locations.append( {0: x_edge, 1: y_edge, 2: z_edge}[direction] ) elif y_face and z_face: flip_locations.append(x_edge) elif x_face and z_face: flip_locations.append(y_edge) elif x_face and y_face: flip_locations.append(z_edge) for location in flip_locations: self.flip_edge(location, new_signs, code) correction.site('Z', location) return new_signs
bn3d/decoders/sweepmatch/_sweep_decoder_3d.py
from typing import Tuple, Dict import numpy as np from qecsim.model import Decoder from ...models import ToricCode3D from ...models import Toric3DPauli Indexer = Dict[Tuple[int, int, int], int] class SweepDecoder3D(Decoder): label: str = 'Toric 3D Sweep Decoder' _rng: np.random.Generator max_sweep_factor: int def __init__(self, seed: int = 0, max_sweep_factor: int = 32): self._rng = np.random.default_rng(seed) self.max_sweep_factor = max_sweep_factor def get_face_syndromes( self, code: ToricCode3D, full_syndrome: np.ndarray ) -> np.ndarray: """Get only the syndromes for the vertex Z stabilizers. Z vertex stabiziliers syndromes are discarded for this decoder. """ n_faces = code.Hz.shape[0] face_syndromes = full_syndrome[:n_faces] return face_syndromes def flip_edge( self, index: Tuple, signs: Indexer, code: ToricCode3D ): """Flip signs at index and update correction.""" x, y, z = index edge = tuple(np.mod(index, 2)) L_x, L_y, L_z = code.size limits = (2*L_x, 2*L_y, 2*L_z) if edge == (1, 0, 0): face_1 = (x, y + 1, z) face_2 = (x, y - 1, z) face_3 = (x, y, z + 1) face_4 = (x, y, z - 1) elif edge == (0, 1, 0): face_1 = (x, y, z + 1) face_2 = (x, y, z - 1) face_3 = (x + 1, y, z) face_4 = (x - 1, y, z) elif edge == (0, 0, 1): face_1 = (x + 1, y, z) face_2 = (x - 1, y, z) face_3 = (x, y + 1, z) face_4 = (x, y - 1, z) # Impose periodic boundary conditions. index_1 = tuple(np.mod(face_1, limits)) index_2 = tuple(np.mod(face_2, limits)) index_3 = tuple(np.mod(face_3, limits)) index_4 = tuple(np.mod(face_4, limits)) # Flip the signs (well actually 0s and 1s). signs[index_1] = 1 - signs[index_1] # type: ignore signs[index_2] = 1 - signs[index_2] # type: ignore signs[index_3] = 1 - signs[index_3] # type: ignore signs[index_4] = 1 - signs[index_4] # type: ignore def get_default_direction(self): """The default direction when all faces are excited.""" direction = int(self._rng.choice([0, 1, 2], size=1)) return direction # TODO: make this more space-efficient, don't store zeros. def get_initial_state( self, code: ToricCode3D, syndrome: np.ndarray ) -> Indexer: """Get initial cellular automaton state from syndrome.""" n_faces = len(code.face_index) face_syndromes = syndrome[:n_faces] signs = dict() for face, index in code.face_index.items(): signs[face] = int(face_syndromes[index]) return signs def decode( self, code: ToricCode3D, syndrome: np.ndarray ) -> np.ndarray: """Get Z corrections given measured syndrome.""" # Maximum number of times to sweep before giving up. max_sweeps = self.max_sweep_factor*int(max(code.size)) # The syndromes represented as an array of 0s and 1s. signs = self.get_initial_state(code, syndrome) # Keep track of the correction needed. correction = Toric3DPauli(code) # Initialize the number of sweeps. i_sweep = 0 # Keep sweeping until there are no syndromes. while any(signs.values()) and i_sweep < max_sweeps: signs = self.sweep_move(signs, correction, code) i_sweep += 1 return correction.to_bsf() def sweep_move( self, signs: Indexer, correction: Toric3DPauli, code: ToricCode3D ) -> Indexer: """Apply the sweep move once.""" new_signs = signs.copy() flip_locations = [] L_x, L_y, L_z = code.size limits = (2*L_x, 2*L_y, 2*L_z) # Sweep through every edge. for x, y, z in code.vertex_index.keys(): # Get the syndromes on each face in sweep direction. x_face = signs[tuple(np.mod((x, y + 1, z + 1), limits))] # type: ignore # noqa: E501 y_face = signs[tuple(np.mod((x + 1, y, z + 1), limits))] # type: ignore # noqa: E501 z_face = signs[tuple(np.mod((x + 1, y + 1, z), limits))] # type: ignore # noqa: E501 x_edge = tuple(np.mod((x + 1, y, z), limits)) y_edge = tuple(np.mod((x, y + 1, z), limits)) z_edge = tuple(np.mod((x, y, z + 1), limits)) if x_face and y_face and z_face: direction = self.get_default_direction() flip_locations.append( {0: x_edge, 1: y_edge, 2: z_edge}[direction] ) elif y_face and z_face: flip_locations.append(x_edge) elif x_face and z_face: flip_locations.append(y_edge) elif x_face and y_face: flip_locations.append(z_edge) for location in flip_locations: self.flip_edge(location, new_signs, code) correction.site('Z', location) return new_signs
0.861713
0.567637
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from math import * from decimal import Decimal from scipy.spatial import distance def get_all_params(items): all_params = {} for item in items: params = item['PARAMS'] for param in params: if all_params.get(param) == None: all_params[param] = [] all_params[param].append(params[param]) return all_params def create_DataFrame(items): params = get_all_params(items) dataset = [] ids = [] for item in items: item_params = item['PARAMS'] observation = [] for prm in params: observation.append(item_params.get(prm)) dataset.append(observation) ids.append(item['ITEM_ID']) dataset = np.array(dataset) return pd.DataFrame(dataset, columns=params), ids class Distance(): def __init__(self, items, drop=[]): self._items = items self.df, self.ids = create_DataFrame(items) self._drop_columns(drop) print('Distance obj: Creting DataFrame') self._remove_unsignificant_columns() print('Distance obj: Removing unsignificant columns') self._encode_color() print('Distance obj: Encoding special columns') self._fit() print('Distance obj: Fitting') def _drop_columns(self, columns): [x.decode('utf-8') for x in columns] for item in columns: self.df = self.df.drop(item.decode('utf-8'), 1) def _remove_unsignificant_columns(self): for col in self.df: v = self.df[col] percentage = sum(x == None for x in v) / len(v) if percentage > 0.9: self.df = self.df.drop(col, 1) def _encode_color(self): try: index = self.df.columns.get_loc('Barva') print(index) color_column = [] for item in self.df.iloc[:, index]: if item == None: color_column.append(0) else: color_column.append(int('0x{}'.format(COLORS[item]), 16)) self.df.iloc[:, index] = np.array(color_column) except KeyError: print('No color in DataFrame') def _fit(self): dummy_df = pd.get_dummies(self.df, drop_first=True) # add price product_price = [item['PRICE_VAT'] for item in self._items] dummy_df['PRICE_VAT'] = pd.Series(product_price, index=dummy_df.index) self.dummy_df = dummy_df X = self.dummy_df.iloc[:, :].values X = X.astype(np.float64) sc_X = MinMaxScaler(feature_range=(0, 1)) # sc_X = StandardScaler() self.X = sc_X.fit_transform(X) def train_euclidean(self, observation): y = [] for xi in self.X: y.append(np.sqrt(np.sum((self.X[observation, :] - xi) ** 2))) return y def train_cosine(self, observation): y = [] for xi in self.X: y.append(distance.cosine(self.X[observation, :], xi)) return y def train_manhattan(self, observation): y = [] for xi in self.X: y.append(sum(abs(a - b) for a, b in zip(xi, self.X[observation, :]))) return y def nth_root(self, value, n_root): root_value = 1 / float(n_root) return round(Decimal(value) ** Decimal(root_value), 3) def train_minkowski(self, observation, p_value): y = [] for xi in self.X: y.append(self.nth_root(sum(pow(abs(a - b), p_value) for a, b in zip(xi, self.X[observation, :])), p_value)) return y def get_df(self, observation): df = pd.DataFrame(self.df) #df['Distance_eucl'] = pd.Series(self.train_euclidean(observation), index=df.index) df['Distance_cos'] = pd.Series(self.train_cosine(observation), index=df.index) #df['Distance_manh'] = pd.Series(self.train_manhattan(observation), index=df.index) #df['Distance_mink'] = pd.Series(self.train_minkowski(observation, 3), index=df.index) product_names = [item['PRODUCTNAME'] for item in self._items] product_desc = [item['DESCRIPTION'] for item in self._items] product_price = [item['PRICE_VAT'] for item in self._items] df['PRODUCTNAME'] = pd.Series(product_names, index=df.index) df['DESCRIPTION'] = pd.Series(product_desc, index=df.index) df['PRICE_VAT'] = pd.Series(product_price, index=df.index) return df def get_items(self, observation): print('get items', observation) items = self._items distances = self.train_cosine(observation) stacked = np.column_stack((distances, items)) sorted = stacked[stacked[:,0].argsort()] return sorted[:,1] COLORS = { 'None': '0', 'nerozlišuje se': '0', 'vícebarevná': '0', 'azurová': '00FFFF', 'béžová': 'F5F5DC', 'bílá': 'FFFFFF', 'bílá/hnědá': 'FFFFFF', 'bílá/růžová': 'FFFFFF', 'bílá/stříbrná': 'FFFFFF', 'bílá/zlatá': 'FFFFFF', 'bílá/černá': 'FFFFFF', 'bílá/červená': 'FFFFFF', 'bílá/šedá': 'FFFFFF', 'chrom': '808080', 'cihlová': 'B22222', 'dub': 'A52A2A', 'fialová': 'EE82EE', 'grafitově šedá': '808080', 'hnědá': 'A52A2A', 'hnědá/zelená': 'A52A2A', 'khaki': 'F0E68C', 'kávová/žula': 'A52A2A', 'matná': '0000FF', 'modrá': '0000FF', 'modrá/oranžová': '0000FF', 'modrá/tmavě modrá': '0000FF', 'modrá/zelená': '0000FF', 'modrá/černá': '0000FF', 'měď': 'A52A2A', 'námořní modrá': '0000FF', 'oranžová': 'FFA500', 'purpurová světlá': '9370DB', 'růžová': 'FFC0CB', 'růžová/fialová': 'FFC0CB', 'stříbrná': 'C0C0C0', 'stříbrná/modrá': 'C0C0C0', 'stříbrná/růžová': 'C0C0C0', 'stříbrná/černá': 'C0C0C0', 'stříbrná/šedá': 'C0C0C0', 'světle hnědá': 'A52A2A', 'světle modrá': '0000FF', 'světle růžová': 'FFC0CB', 'světle zelená': '008000', 'světle šedá': '808080', 'titan': 'C0C0C0', 'tmavě fialová': 'EE82EE', 'tmavě modrá': '0000FF', 'tmavě šedá': '808080', 'tyrkysová': '0000FF', 'vínová': 'FF0000', 'zelená': '008000', 'zlatá': 'FFD700', 'zlatá/hnědá': 'FFD700', 'černá': '000000', 'černá/bílá': '000000', 'černá/lesk': '000000', 'černá/mat': '000000', 'černá/modrá': '000000', 'černá/oranžová': '000000', 'černá/stříbrná': '000000', 'černá/tmavě šedá': '000000', 'černá/zelená': '000000', 'černá/zlatá': '000000', 'černá/červená': '000000', 'černá/šedá': '000000', 'černá/žlutá': '000000', 'červená': 'FF0000', 'červená/modrá': 'FF0000', 'červená/černá': 'FF0000', 'čirá': '808080', 'šedá': '808080', 'šedá/zelená': '808080', 'šedá/černá': '808080', 'žlutá': 'FFFF00', 'žlutá/modrá': 'FFFF00', 'žlutá/černá': 'FFFF00', }
distance.py
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from math import * from decimal import Decimal from scipy.spatial import distance def get_all_params(items): all_params = {} for item in items: params = item['PARAMS'] for param in params: if all_params.get(param) == None: all_params[param] = [] all_params[param].append(params[param]) return all_params def create_DataFrame(items): params = get_all_params(items) dataset = [] ids = [] for item in items: item_params = item['PARAMS'] observation = [] for prm in params: observation.append(item_params.get(prm)) dataset.append(observation) ids.append(item['ITEM_ID']) dataset = np.array(dataset) return pd.DataFrame(dataset, columns=params), ids class Distance(): def __init__(self, items, drop=[]): self._items = items self.df, self.ids = create_DataFrame(items) self._drop_columns(drop) print('Distance obj: Creting DataFrame') self._remove_unsignificant_columns() print('Distance obj: Removing unsignificant columns') self._encode_color() print('Distance obj: Encoding special columns') self._fit() print('Distance obj: Fitting') def _drop_columns(self, columns): [x.decode('utf-8') for x in columns] for item in columns: self.df = self.df.drop(item.decode('utf-8'), 1) def _remove_unsignificant_columns(self): for col in self.df: v = self.df[col] percentage = sum(x == None for x in v) / len(v) if percentage > 0.9: self.df = self.df.drop(col, 1) def _encode_color(self): try: index = self.df.columns.get_loc('Barva') print(index) color_column = [] for item in self.df.iloc[:, index]: if item == None: color_column.append(0) else: color_column.append(int('0x{}'.format(COLORS[item]), 16)) self.df.iloc[:, index] = np.array(color_column) except KeyError: print('No color in DataFrame') def _fit(self): dummy_df = pd.get_dummies(self.df, drop_first=True) # add price product_price = [item['PRICE_VAT'] for item in self._items] dummy_df['PRICE_VAT'] = pd.Series(product_price, index=dummy_df.index) self.dummy_df = dummy_df X = self.dummy_df.iloc[:, :].values X = X.astype(np.float64) sc_X = MinMaxScaler(feature_range=(0, 1)) # sc_X = StandardScaler() self.X = sc_X.fit_transform(X) def train_euclidean(self, observation): y = [] for xi in self.X: y.append(np.sqrt(np.sum((self.X[observation, :] - xi) ** 2))) return y def train_cosine(self, observation): y = [] for xi in self.X: y.append(distance.cosine(self.X[observation, :], xi)) return y def train_manhattan(self, observation): y = [] for xi in self.X: y.append(sum(abs(a - b) for a, b in zip(xi, self.X[observation, :]))) return y def nth_root(self, value, n_root): root_value = 1 / float(n_root) return round(Decimal(value) ** Decimal(root_value), 3) def train_minkowski(self, observation, p_value): y = [] for xi in self.X: y.append(self.nth_root(sum(pow(abs(a - b), p_value) for a, b in zip(xi, self.X[observation, :])), p_value)) return y def get_df(self, observation): df = pd.DataFrame(self.df) #df['Distance_eucl'] = pd.Series(self.train_euclidean(observation), index=df.index) df['Distance_cos'] = pd.Series(self.train_cosine(observation), index=df.index) #df['Distance_manh'] = pd.Series(self.train_manhattan(observation), index=df.index) #df['Distance_mink'] = pd.Series(self.train_minkowski(observation, 3), index=df.index) product_names = [item['PRODUCTNAME'] for item in self._items] product_desc = [item['DESCRIPTION'] for item in self._items] product_price = [item['PRICE_VAT'] for item in self._items] df['PRODUCTNAME'] = pd.Series(product_names, index=df.index) df['DESCRIPTION'] = pd.Series(product_desc, index=df.index) df['PRICE_VAT'] = pd.Series(product_price, index=df.index) return df def get_items(self, observation): print('get items', observation) items = self._items distances = self.train_cosine(observation) stacked = np.column_stack((distances, items)) sorted = stacked[stacked[:,0].argsort()] return sorted[:,1] COLORS = { 'None': '0', 'nerozlišuje se': '0', 'vícebarevná': '0', 'azurová': '00FFFF', 'béžová': 'F5F5DC', 'bílá': 'FFFFFF', 'bílá/hnědá': 'FFFFFF', 'bílá/růžová': 'FFFFFF', 'bílá/stříbrná': 'FFFFFF', 'bílá/zlatá': 'FFFFFF', 'bílá/černá': 'FFFFFF', 'bílá/červená': 'FFFFFF', 'bílá/šedá': 'FFFFFF', 'chrom': '808080', 'cihlová': 'B22222', 'dub': 'A52A2A', 'fialová': 'EE82EE', 'grafitově šedá': '808080', 'hnědá': 'A52A2A', 'hnědá/zelená': 'A52A2A', 'khaki': 'F0E68C', 'kávová/žula': 'A52A2A', 'matná': '0000FF', 'modrá': '0000FF', 'modrá/oranžová': '0000FF', 'modrá/tmavě modrá': '0000FF', 'modrá/zelená': '0000FF', 'modrá/černá': '0000FF', 'měď': 'A52A2A', 'námořní modrá': '0000FF', 'oranžová': 'FFA500', 'purpurová světlá': '9370DB', 'růžová': 'FFC0CB', 'růžová/fialová': 'FFC0CB', 'stříbrná': 'C0C0C0', 'stříbrná/modrá': 'C0C0C0', 'stříbrná/růžová': 'C0C0C0', 'stříbrná/černá': 'C0C0C0', 'stříbrná/šedá': 'C0C0C0', 'světle hnědá': 'A52A2A', 'světle modrá': '0000FF', 'světle růžová': 'FFC0CB', 'světle zelená': '008000', 'světle šedá': '808080', 'titan': 'C0C0C0', 'tmavě fialová': 'EE82EE', 'tmavě modrá': '0000FF', 'tmavě šedá': '808080', 'tyrkysová': '0000FF', 'vínová': 'FF0000', 'zelená': '008000', 'zlatá': 'FFD700', 'zlatá/hnědá': 'FFD700', 'černá': '000000', 'černá/bílá': '000000', 'černá/lesk': '000000', 'černá/mat': '000000', 'černá/modrá': '000000', 'černá/oranžová': '000000', 'černá/stříbrná': '000000', 'černá/tmavě šedá': '000000', 'černá/zelená': '000000', 'černá/zlatá': '000000', 'černá/červená': '000000', 'černá/šedá': '000000', 'černá/žlutá': '000000', 'červená': 'FF0000', 'červená/modrá': 'FF0000', 'červená/černá': 'FF0000', 'čirá': '808080', 'šedá': '808080', 'šedá/zelená': '808080', 'šedá/černá': '808080', 'žlutá': 'FFFF00', 'žlutá/modrá': 'FFFF00', 'žlutá/černá': 'FFFF00', }
0.483648
0.334562
import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MAIN_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) SECRET_KEY = 'secret_key' GOOGLE_API_KEY = 'api_key' # General security settings ALLOWED_HOSTS = ['www.dandeliondiary.com',] SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True # prevent reading via javascript CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True # prevent reading via javascript SESSION_EXPIRE_AT_BROWSER_CLOSE=True SECURE_SSL_REDIRECT = True # allow access via https only SECURE_CONTENT_TYPE_NOSNIFF = True # force browser to always use the type provided in the Content-Type header SECURE_BROWSER_XSS_FILTER = True # enable browsers to block content that appears to be an XSS attack # Default database definition # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'dandeliondiary', 'USER': 'user', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '5432', } } # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.humanize', 'django.contrib.staticfiles', 'guardian', 'storages', 'django_q', 'bootstrap3', 'account', 'core', 'household', 'capture', 'compare', 'contribute', 'forums', 'public', 'avatar', ] SITE_ID = 1 WSGI_APPLICATION = 'dandeliondiary.wsgi.application' # This is the proper way to do this in Django 1.10 but am using MIDDLEWARE_CLASSES below until account package is fixed. #MIDDLEWARE = [ # 'django.middleware.security.SecurityMiddleware', # 'django.contrib.sessions.middleware.SessionMiddleware', # 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', # 'django.contrib.auth.middleware.AuthenticationMiddleware', # 'django.contrib.messages.middleware.MessageMiddleware', # 'django.middleware.clickjacking.XFrameOptionsMiddleware', # 'account.middleware.LocaleMiddleware', # 'account.middleware.TimezoneMiddleware', #] # Used for package "Account"; this is deprecated in Django 1.10 and will need to change soon. MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', #'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'account.middleware.LocaleMiddleware', 'account.middleware.TimezoneMiddleware', ] ROOT_URLCONF = 'dandeliondiary.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, '..', 'household/templates/household'), os.path.join(BASE_DIR, '..', 'capture/templates/capture'), os.path.join(BASE_DIR, '..', 'compare/templates/compare'), os.path.join(BASE_DIR, '..', 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.static', 'django.template.context_processors.media', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'account.context_processors.account', 'dandeliondiary.context_processors.google_analytics', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', # this is default 'guardian.backends.ObjectPermissionBackend', ) GUARDIAN_RENDER_403 = True # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Account application settings ACCOUNT_SIGNUP_REDIRECT_URL = "household:household_dashboard" ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = "household:household_dashboard" ACCOUNT_LOGIN_REDIRECT_URL = "compare:compare_dashboard" ACCOUNT_LOGOUT_REDIRECT_URL = "public:home" ACCOUNT_PASSWORD_CHANGE_REDIRECT_URL = "household:my_info" ACCOUNT_EMAIL_UNIQUE = True ACCOUNT_EMAIL_CONFIRMATION_REQUIRED = False ACCOUNT_EMAIL_CONFIRMATION_EMAIL = True ACCOUNT_USE_AUTH_AUTHENTICATE = False DEFAULT_HTTP_PROTOCOL = "https" # Override Django login to account URL LOGIN_URL = '/account/login/' # Avatar application settings AVATAR_AUTO_GENERATE_SIZES = (80, 64, 50,) AVATAR_DEFAULT_SIZE = 64 AVATAR_GRAVATAR_BACKUP = False AVATAR_CHANGE_TEMPLATE = "avatar/avatar.html" # Google analytics GOOGLE_ANALYTICS_PROPERTY_ID = 'UA-92296339-1' GOOGLE_ANALYTICS_DOMAIN = 'dandeliondiary.com' # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True
dandeliondiary/dandeliondiary/settings/base.py
import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MAIN_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) SECRET_KEY = 'secret_key' GOOGLE_API_KEY = 'api_key' # General security settings ALLOWED_HOSTS = ['www.dandeliondiary.com',] SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True # prevent reading via javascript CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True # prevent reading via javascript SESSION_EXPIRE_AT_BROWSER_CLOSE=True SECURE_SSL_REDIRECT = True # allow access via https only SECURE_CONTENT_TYPE_NOSNIFF = True # force browser to always use the type provided in the Content-Type header SECURE_BROWSER_XSS_FILTER = True # enable browsers to block content that appears to be an XSS attack # Default database definition # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'dandeliondiary', 'USER': 'user', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '5432', } } # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.humanize', 'django.contrib.staticfiles', 'guardian', 'storages', 'django_q', 'bootstrap3', 'account', 'core', 'household', 'capture', 'compare', 'contribute', 'forums', 'public', 'avatar', ] SITE_ID = 1 WSGI_APPLICATION = 'dandeliondiary.wsgi.application' # This is the proper way to do this in Django 1.10 but am using MIDDLEWARE_CLASSES below until account package is fixed. #MIDDLEWARE = [ # 'django.middleware.security.SecurityMiddleware', # 'django.contrib.sessions.middleware.SessionMiddleware', # 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', # 'django.contrib.auth.middleware.AuthenticationMiddleware', # 'django.contrib.messages.middleware.MessageMiddleware', # 'django.middleware.clickjacking.XFrameOptionsMiddleware', # 'account.middleware.LocaleMiddleware', # 'account.middleware.TimezoneMiddleware', #] # Used for package "Account"; this is deprecated in Django 1.10 and will need to change soon. MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', #'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'account.middleware.LocaleMiddleware', 'account.middleware.TimezoneMiddleware', ] ROOT_URLCONF = 'dandeliondiary.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, '..', 'household/templates/household'), os.path.join(BASE_DIR, '..', 'capture/templates/capture'), os.path.join(BASE_DIR, '..', 'compare/templates/compare'), os.path.join(BASE_DIR, '..', 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.static', 'django.template.context_processors.media', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'account.context_processors.account', 'dandeliondiary.context_processors.google_analytics', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', # this is default 'guardian.backends.ObjectPermissionBackend', ) GUARDIAN_RENDER_403 = True # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Account application settings ACCOUNT_SIGNUP_REDIRECT_URL = "household:household_dashboard" ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = "household:household_dashboard" ACCOUNT_LOGIN_REDIRECT_URL = "compare:compare_dashboard" ACCOUNT_LOGOUT_REDIRECT_URL = "public:home" ACCOUNT_PASSWORD_CHANGE_REDIRECT_URL = "household:my_info" ACCOUNT_EMAIL_UNIQUE = True ACCOUNT_EMAIL_CONFIRMATION_REQUIRED = False ACCOUNT_EMAIL_CONFIRMATION_EMAIL = True ACCOUNT_USE_AUTH_AUTHENTICATE = False DEFAULT_HTTP_PROTOCOL = "https" # Override Django login to account URL LOGIN_URL = '/account/login/' # Avatar application settings AVATAR_AUTO_GENERATE_SIZES = (80, 64, 50,) AVATAR_DEFAULT_SIZE = 64 AVATAR_GRAVATAR_BACKUP = False AVATAR_CHANGE_TEMPLATE = "avatar/avatar.html" # Google analytics GOOGLE_ANALYTICS_PROPERTY_ID = 'UA-92296339-1' GOOGLE_ANALYTICS_DOMAIN = 'dandeliondiary.com' # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True
0.378
0.052279
from __future__ import generator_stop import csv import os from typing import Dict, List, TextIO import warnings from ..exceptions import WriteIsatabException, WriteIsatabWarning from ..constants import investigation_headers from .helpers import is_ontology_term_ref from . import models __author__ = ( "<NAME> <<EMAIL>>, " "<NAME> <<EMAIL>>" ) # Helper to extract comments and align them into rows def _extract_comments(section_objects: list): names = sorted({comment.name for obj in section_objects for comment in obj.comments}) comments = {name: [""] * len(section_objects) for name in names} for i, obj in enumerate(section_objects): for comment in obj.comments: comments[comment.name][i] = comment.value return comments # Helper to extract a section header def _extract_section_header(first_entry, section_name): """ Extract reference header from first entry (column) in a section, assuming all entries have the same header resp. same corresponding values available. """ if first_entry and first_entry.headers: # TODO: check that headers and attributes match return first_entry.headers else: tpl = "No reference headers available for section {}. Applying default order." msg = tpl.format(section_name) warnings.warn(msg, WriteIsatabWarning) return None # Helper to create a dict with keys to empty lists def _init_multi_column_section(section_keys) -> dict: return {key: [] for key in section_keys} class InvestigationWriter: """ Main class to write an investigation file from an ``InvestigationInfo`` object. :type investigation: models.InvestigationInfo :param investigation: The investigation model to write :type output_file: TextIO :param output_file: Output ISA-Tab investigation file :type quote: str :param quote: Optional quoting character (none by default) :type lineterminator: str :param lineterminator: Optional line terminator (OS specific by default) """ @classmethod def from_stream( cls, investigation: models.InvestigationInfo, output_file: TextIO, quote=None, lineterminator=None, ): """Construct from file-like object""" return InvestigationWriter(investigation, output_file, quote, lineterminator) def __init__( self, investigation: models.InvestigationInfo, output_file: TextIO, quote=None, lineterminator=None, ): # Investigation model self.investigation = investigation # Investigation output file self.output_file = output_file # Quote for csv export self.quote = quote # Csv file writer self._writer = csv.writer( output_file, delimiter="\t", lineterminator=lineterminator or os.linesep, quoting=csv.QUOTE_NONE, # Can't use no quoting without escaping, so use different dummy quote here escapechar="\\", quotechar="|", ) def write(self): """Write investigation file""" self._write_ontology_source_reference() self._write_basic_info() self._write_publications() self._write_contacts() self._write_studies() def _write_line(self, header, values): # Write an investigation line with header and values (potentially quoted) if self.quote: tpl = "".join((self.quote, "{}", self.quote)) values = [tpl.format(v) for v in values] self._writer.writerow((header, *values)) # Writer for headers and content of sections def _write_section( self, section_name: str, section: Dict[str, list], comments: Dict[str, list], headers: List[str] = None, ): # Add comments to section dict if comments: for key, value in comments.items(): section["Comment[{}]".format(key)] = value # Write the section name self._writer.writerow((section_name,)) # Write the lines in this section. if headers: # Use header order self._write_section_by_header_order(headers, section, section_name) else: # Use dict order for header, values in section.items(): self._write_line(header, values) def _write_section_by_header_order(self, headers, section, section_name): # Write section based on header order for header in headers: if header in section: values = section.pop(header) self._write_line(header, values) else: # pragma: no cover tpl = "No data found for header {} in section {}" msg = tpl.format(header, section_name) raise WriteIsatabException(msg) if len(section) > 0: # pragma: no cover tpl = "Leftover rows found in section {}:\n{}" msg = tpl.format(section_name, section) raise WriteIsatabException(msg) def _write_ontology_source_reference(self): # Write ONTOLOGY SOURCE REFERENCE section section = _init_multi_column_section(investigation_headers.ONTOLOGY_SOURCE_REF_KEYS) for ontology_ref in self.investigation.ontology_source_refs.values(): section[investigation_headers.TERM_SOURCE_NAME].append(ontology_ref.name) section[investigation_headers.TERM_SOURCE_FILE].append(ontology_ref.file) section[investigation_headers.TERM_SOURCE_VERSION].append(ontology_ref.version) section[investigation_headers.TERM_SOURCE_DESCRIPTION].append(ontology_ref.description) comments = _extract_comments(self.investigation.ontology_source_refs.values()) headers = _extract_section_header( list(self.investigation.ontology_source_refs.values())[0] if self.investigation.ontology_source_refs else None, investigation_headers.ONTOLOGY_SOURCE_REFERENCE, ) self._write_section( investigation_headers.ONTOLOGY_SOURCE_REFERENCE, section, comments, headers ) def _write_basic_info(self): # Write INVESTIGATION section basic_info = self.investigation.info section = { investigation_headers.INVESTIGATION_IDENTIFIER: [basic_info.identifier], investigation_headers.INVESTIGATION_TITLE: [basic_info.title], investigation_headers.INVESTIGATION_DESCRIPTION: [basic_info.description], investigation_headers.INVESTIGATION_SUBMISSION_DATE: [basic_info.submission_date], investigation_headers.INVESTIGATION_PUBLIC_RELEASE_DATE: [ basic_info.public_release_date ], } comments = _extract_comments([basic_info]) headers = _extract_section_header( self.investigation.info, investigation_headers.INVESTIGATION ) self._write_section(investigation_headers.INVESTIGATION, section, comments, headers) def _write_publications(self): # Write INVESTIGATION PUBLICATIONS section section = _init_multi_column_section(investigation_headers.INVESTIGATION_PUBLICATIONS_KEYS) for publication in self.investigation.publications: section[investigation_headers.INVESTIGATION_PUBMED_ID].append(publication.pubmed_id) section[investigation_headers.INVESTIGATION_PUBLICATION_DOI].append(publication.doi) section[investigation_headers.INVESTIGATION_PUBLICATION_AUTHOR_LIST].append( publication.authors ) section[investigation_headers.INVESTIGATION_PUBLICATION_TITLE].append(publication.title) if is_ontology_term_ref(publication.status): section[investigation_headers.INVESTIGATION_PUBLICATION_STATUS].append( publication.status.name or "" ) section[ investigation_headers.INVESTIGATION_PUBLICATION_STATUS_TERM_ACCESSION_NUMBER ].append(publication.status.accession or "") section[ investigation_headers.INVESTIGATION_PUBLICATION_STATUS_TERM_SOURCE_REF ].append(publication.status.ontology_name or "") else: section[investigation_headers.INVESTIGATION_PUBLICATION_STATUS].append( publication.status ) section[ investigation_headers.INVESTIGATION_PUBLICATION_STATUS_TERM_ACCESSION_NUMBER ].append("") section[ investigation_headers.INVESTIGATION_PUBLICATION_STATUS_TERM_SOURCE_REF ].append("") comments = _extract_comments(self.investigation.publications) headers = _extract_section_header( list(self.investigation.publications)[0] if self.investigation.publications else None, investigation_headers.INVESTIGATION_PUBLICATIONS, ) self._write_section( investigation_headers.INVESTIGATION_PUBLICATIONS, section, comments, headers ) def _write_contacts(self): # Write INVESTIGATION CONTACTS section section = _init_multi_column_section(investigation_headers.INVESTIGATION_CONTACTS_KEYS) for contact in self.investigation.contacts: section[investigation_headers.INVESTIGATION_PERSON_LAST_NAME].append(contact.last_name) section[investigation_headers.INVESTIGATION_PERSON_FIRST_NAME].append( contact.first_name ) section[investigation_headers.INVESTIGATION_PERSON_MID_INITIALS].append( contact.mid_initial ) section[investigation_headers.INVESTIGATION_PERSON_EMAIL].append(contact.email) section[investigation_headers.INVESTIGATION_PERSON_PHONE].append(contact.phone) section[investigation_headers.INVESTIGATION_PERSON_FAX].append(contact.fax) section[investigation_headers.INVESTIGATION_PERSON_ADDRESS].append(contact.address) section[investigation_headers.INVESTIGATION_PERSON_AFFILIATION].append( contact.affiliation ) if is_ontology_term_ref(contact.role): section[investigation_headers.INVESTIGATION_PERSON_ROLES].append( contact.role.name or "" ) section[ investigation_headers.INVESTIGATION_PERSON_ROLES_TERM_ACCESSION_NUMBER ].append(contact.role.accession or "") section[investigation_headers.INVESTIGATION_PERSON_ROLES_TERM_SOURCE_REF].append( contact.role.ontology_name or "" ) else: section[investigation_headers.INVESTIGATION_PERSON_ROLES].append(contact.role) section[ investigation_headers.INVESTIGATION_PERSON_ROLES_TERM_ACCESSION_NUMBER ].append("") section[investigation_headers.INVESTIGATION_PERSON_ROLES_TERM_SOURCE_REF].append("") comments = _extract_comments(self.investigation.contacts) headers = _extract_section_header( list(self.investigation.contacts)[0] if self.investigation.contacts else None, investigation_headers.INVESTIGATION_CONTACTS, ) self._write_section( investigation_headers.INVESTIGATION_CONTACTS, section, comments, headers ) def _write_studies(self): # Write STUDY sections for study in self.investigation.studies: self._write_study_basic_info(study) self._write_study_design_descriptors(study) self._write_study_publications(study) self._write_study_factors(study) self._write_study_assays(study) self._write_study_protocols(study) self._write_study_contacts(study) def _write_study_basic_info(self, study: models.StudyInfo): # Read STUDY INFO section basic_info = study.info section = { investigation_headers.STUDY_IDENTIFIER: [basic_info.identifier], investigation_headers.STUDY_TITLE: [basic_info.title], investigation_headers.STUDY_DESCRIPTION: [basic_info.description], investigation_headers.STUDY_SUBMISSION_DATE: [basic_info.submission_date], investigation_headers.STUDY_PUBLIC_RELEASE_DATE: [basic_info.public_release_date], investigation_headers.STUDY_FILE_NAME: [basic_info.path or ""], } comments = _extract_comments([basic_info]) headers = _extract_section_header(basic_info, investigation_headers.STUDY) self._write_section(investigation_headers.STUDY, section, comments, headers) def _write_study_design_descriptors(self, study: models.StudyInfo): # Read STUDY DESIGN DESCRIPTORS section section = _init_multi_column_section(investigation_headers.STUDY_DESIGN_DESCR_KEYS) for design in study.designs: if is_ontology_term_ref(design.type): section[investigation_headers.STUDY_DESIGN_TYPE].append(design.type.name or "") section[investigation_headers.STUDY_DESIGN_TYPE_TERM_ACCESSION_NUMBER].append( design.type.accession or "" ) section[investigation_headers.STUDY_DESIGN_TYPE_TERM_SOURCE_REF].append( design.type.ontology_name or "" ) else: section[investigation_headers.STUDY_DESIGN_TYPE].append(design.type) section[investigation_headers.STUDY_DESIGN_TYPE_TERM_ACCESSION_NUMBER].append("") section[investigation_headers.STUDY_DESIGN_TYPE_TERM_SOURCE_REF].append("") comments = _extract_comments(study.designs) headers = _extract_section_header( list(study.designs)[0] if study.designs else None, investigation_headers.STUDY_DESIGN_DESCRIPTORS, ) self._write_section( investigation_headers.STUDY_DESIGN_DESCRIPTORS, section, comments, headers ) def _write_study_publications(self, study: models.StudyInfo): # Write STUDY PUBLICATIONS section section = _init_multi_column_section(investigation_headers.STUDY_PUBLICATIONS_KEYS) for publication in study.publications: section[investigation_headers.STUDY_PUBMED_ID].append(publication.pubmed_id) section[investigation_headers.STUDY_PUBLICATION_DOI].append(publication.doi) section[investigation_headers.STUDY_PUBLICATION_AUTHOR_LIST].append(publication.authors) section[investigation_headers.STUDY_PUBLICATION_TITLE].append(publication.title) if is_ontology_term_ref(publication.status): section[investigation_headers.STUDY_PUBLICATION_STATUS].append( publication.status.name or "" ) section[ investigation_headers.STUDY_PUBLICATION_STATUS_TERM_ACCESSION_NUMBER ].append(publication.status.accession or "") section[investigation_headers.STUDY_PUBLICATION_STATUS_TERM_SOURCE_REF].append( publication.status.ontology_name or "" ) else: section[investigation_headers.STUDY_PUBLICATION_STATUS].append(publication.status) section[ investigation_headers.STUDY_PUBLICATION_STATUS_TERM_ACCESSION_NUMBER ].append("") section[investigation_headers.STUDY_PUBLICATION_STATUS_TERM_SOURCE_REF].append("") comments = _extract_comments(study.publications) headers = _extract_section_header( list(study.publications)[0] if study.publications else None, investigation_headers.STUDY_PUBLICATIONS, ) self._write_section(investigation_headers.STUDY_PUBLICATIONS, section, comments, headers) def _write_study_factors(self, study: models.StudyInfo): # Write STUDY FACTORS section section = _init_multi_column_section(investigation_headers.STUDY_FACTORS_KEYS) for factor in study.factors.values(): section[investigation_headers.STUDY_FACTOR_NAME].append(factor.name) if is_ontology_term_ref(factor.type): section[investigation_headers.STUDY_FACTOR_TYPE].append(factor.type.name) section[investigation_headers.STUDY_FACTOR_TYPE_TERM_ACCESSION_NUMBER].append( factor.type.accession ) section[investigation_headers.STUDY_FACTOR_TYPE_TERM_SOURCE_REF].append( factor.type.ontology_name ) else: section[investigation_headers.STUDY_FACTOR_TYPE].append(factor.type) section[investigation_headers.STUDY_FACTOR_TYPE_TERM_ACCESSION_NUMBER].append("") section[investigation_headers.STUDY_FACTOR_TYPE_TERM_SOURCE_REF].append("") comments = _extract_comments(study.factors.values()) headers = _extract_section_header( list(study.factors.values())[0] if study.factors else None, investigation_headers.STUDY_FACTORS, ) self._write_section(investigation_headers.STUDY_FACTORS, section, comments, headers) def _write_study_assays(self, study: models.StudyInfo): # Write STUDY ASSAYS section section = _init_multi_column_section(investigation_headers.STUDY_ASSAYS_KEYS) for assay in study.assays: section[investigation_headers.STUDY_ASSAY_FILE_NAME].append(assay.path or "") if is_ontology_term_ref(assay.measurement_type): section[investigation_headers.STUDY_ASSAY_MEASUREMENT_TYPE].append( assay.measurement_type.name or "" ) section[ investigation_headers.STUDY_ASSAY_MEASUREMENT_TYPE_TERM_ACCESSION_NUMBER ].append(assay.measurement_type.accession or "") section[investigation_headers.STUDY_ASSAY_MEASUREMENT_TYPE_TERM_SOURCE_REF].append( assay.measurement_type.ontology_name or "" ) else: section[investigation_headers.STUDY_ASSAY_MEASUREMENT_TYPE].append( assay.measurement_type ) section[ investigation_headers.STUDY_ASSAY_MEASUREMENT_TYPE_TERM_ACCESSION_NUMBER ].append("") section[investigation_headers.STUDY_ASSAY_MEASUREMENT_TYPE_TERM_SOURCE_REF].append( "" ) if is_ontology_term_ref(assay.technology_type): section[investigation_headers.STUDY_ASSAY_TECHNOLOGY_TYPE].append( assay.technology_type.name or "" ) section[ investigation_headers.STUDY_ASSAY_TECHNOLOGY_TYPE_TERM_ACCESSION_NUMBER ].append(assay.technology_type.accession or "") section[investigation_headers.STUDY_ASSAY_TECHNOLOGY_TYPE_TERM_SOURCE_REF].append( assay.technology_type.ontology_name or "" ) else: section[investigation_headers.STUDY_ASSAY_TECHNOLOGY_TYPE].append( assay.technology_type ) section[ investigation_headers.STUDY_ASSAY_TECHNOLOGY_TYPE_TERM_ACCESSION_NUMBER ].append("") section[investigation_headers.STUDY_ASSAY_TECHNOLOGY_TYPE_TERM_SOURCE_REF].append( "" ) section[investigation_headers.STUDY_ASSAY_TECHNOLOGY_PLATFORM].append(assay.platform) comments = _extract_comments(study.assays) headers = _extract_section_header( list(study.assays)[0] if study.assays else None, investigation_headers.STUDY_ASSAYS ) self._write_section(investigation_headers.STUDY_ASSAYS, section, comments, headers) def _write_study_protocols(self, study: models.StudyInfo): # Write STUDY PROTOCOLS section section = _init_multi_column_section(investigation_headers.STUDY_PROTOCOLS_KEYS) for protocol in study.protocols.values(): section[investigation_headers.STUDY_PROTOCOL_NAME].append(protocol.name) if is_ontology_term_ref(protocol.type): section[investigation_headers.STUDY_PROTOCOL_TYPE].append(protocol.type.name or "") section[investigation_headers.STUDY_PROTOCOL_TYPE_TERM_ACCESSION_NUMBER].append( protocol.type.accession or "" ) section[investigation_headers.STUDY_PROTOCOL_TYPE_TERM_SOURCE_REF].append( protocol.type.ontology_name or "" ) else: section[investigation_headers.STUDY_PROTOCOL_TYPE].append(protocol.type) section[investigation_headers.STUDY_PROTOCOL_TYPE_TERM_ACCESSION_NUMBER].append("") section[investigation_headers.STUDY_PROTOCOL_TYPE_TERM_SOURCE_REF].append("") section[investigation_headers.STUDY_PROTOCOL_DESCRIPTION].append(protocol.description) section[investigation_headers.STUDY_PROTOCOL_URI].append(protocol.uri) section[investigation_headers.STUDY_PROTOCOL_VERSION].append(protocol.version) names = [] accessions = [] ontologies = [] for parameter in protocol.parameters.values(): if is_ontology_term_ref(parameter): names.append(parameter.name or "") accessions.append(parameter.accession or "") ontologies.append(parameter.ontology_name or "") else: names.append(parameter.name) accessions.append("") ontologies.append("") section[investigation_headers.STUDY_PROTOCOL_PARAMETERS_NAME].append(";".join(names)) section[ investigation_headers.STUDY_PROTOCOL_PARAMETERS_NAME_TERM_ACCESSION_NUMBER ].append(";".join(accessions)) section[investigation_headers.STUDY_PROTOCOL_PARAMETERS_NAME_TERM_SOURCE_REF].append( ";".join(ontologies) ) names = [] types = [] accessions = [] ontologies = [] for component in protocol.components.values(): names.append(component.name) if is_ontology_term_ref(component.type): types.append(component.type.name or "") accessions.append(component.type.accession or "") ontologies.append(component.type.ontology_name or "") else: names.append(component.type) accessions.append("") ontologies.append("") section[investigation_headers.STUDY_PROTOCOL_COMPONENTS_NAME].append(";".join(names)) section[investigation_headers.STUDY_PROTOCOL_COMPONENTS_TYPE].append(";".join(types)) section[ investigation_headers.STUDY_PROTOCOL_COMPONENTS_TYPE_TERM_ACCESSION_NUMBER ].append(";".join(accessions)) section[investigation_headers.STUDY_PROTOCOL_COMPONENTS_TYPE_TERM_SOURCE_REF].append( ";".join(ontologies) ) comments = _extract_comments(study.protocols.values()) headers = _extract_section_header( list(study.protocols.values())[0] if study.protocols else None, investigation_headers.STUDY_PROTOCOLS, ) self._write_section(investigation_headers.STUDY_PROTOCOLS, section, comments, headers) def _write_study_contacts(self, study: models.StudyInfo): # Write STUDY CONTACTS section section = _init_multi_column_section(investigation_headers.STUDY_CONTACTS_KEYS) for contact in study.contacts: section[investigation_headers.STUDY_PERSON_LAST_NAME].append(contact.last_name) section[investigation_headers.STUDY_PERSON_FIRST_NAME].append(contact.first_name) section[investigation_headers.STUDY_PERSON_MID_INITIALS].append(contact.mid_initial) section[investigation_headers.STUDY_PERSON_EMAIL].append(contact.email) section[investigation_headers.STUDY_PERSON_PHONE].append(contact.phone) section[investigation_headers.STUDY_PERSON_FAX].append(contact.fax) section[investigation_headers.STUDY_PERSON_ADDRESS].append(contact.address) section[investigation_headers.STUDY_PERSON_AFFILIATION].append(contact.affiliation) if is_ontology_term_ref(contact.role): section[investigation_headers.STUDY_PERSON_ROLES].append(contact.role.name or "") section[investigation_headers.STUDY_PERSON_ROLES_TERM_ACCESSION_NUMBER].append( contact.role.accession or "" ) section[investigation_headers.STUDY_PERSON_ROLES_TERM_SOURCE_REF].append( contact.role.ontology_name or "" ) else: section[investigation_headers.STUDY_PERSON_ROLES].append(contact.role) section[investigation_headers.STUDY_PERSON_ROLES_TERM_ACCESSION_NUMBER].append("") section[investigation_headers.STUDY_PERSON_ROLES_TERM_SOURCE_REF].append("") comments = _extract_comments(study.contacts) headers = _extract_section_header( list(study.contacts)[0] if study.contacts else None, investigation_headers.STUDY_CONTACTS, ) self._write_section(investigation_headers.STUDY_CONTACTS, section, comments, headers)
altamisa/isatab/write_investigation.py
from __future__ import generator_stop import csv import os from typing import Dict, List, TextIO import warnings from ..exceptions import WriteIsatabException, WriteIsatabWarning from ..constants import investigation_headers from .helpers import is_ontology_term_ref from . import models __author__ = ( "<NAME> <<EMAIL>>, " "<NAME> <<EMAIL>>" ) # Helper to extract comments and align them into rows def _extract_comments(section_objects: list): names = sorted({comment.name for obj in section_objects for comment in obj.comments}) comments = {name: [""] * len(section_objects) for name in names} for i, obj in enumerate(section_objects): for comment in obj.comments: comments[comment.name][i] = comment.value return comments # Helper to extract a section header def _extract_section_header(first_entry, section_name): """ Extract reference header from first entry (column) in a section, assuming all entries have the same header resp. same corresponding values available. """ if first_entry and first_entry.headers: # TODO: check that headers and attributes match return first_entry.headers else: tpl = "No reference headers available for section {}. Applying default order." msg = tpl.format(section_name) warnings.warn(msg, WriteIsatabWarning) return None # Helper to create a dict with keys to empty lists def _init_multi_column_section(section_keys) -> dict: return {key: [] for key in section_keys} class InvestigationWriter: """ Main class to write an investigation file from an ``InvestigationInfo`` object. :type investigation: models.InvestigationInfo :param investigation: The investigation model to write :type output_file: TextIO :param output_file: Output ISA-Tab investigation file :type quote: str :param quote: Optional quoting character (none by default) :type lineterminator: str :param lineterminator: Optional line terminator (OS specific by default) """ @classmethod def from_stream( cls, investigation: models.InvestigationInfo, output_file: TextIO, quote=None, lineterminator=None, ): """Construct from file-like object""" return InvestigationWriter(investigation, output_file, quote, lineterminator) def __init__( self, investigation: models.InvestigationInfo, output_file: TextIO, quote=None, lineterminator=None, ): # Investigation model self.investigation = investigation # Investigation output file self.output_file = output_file # Quote for csv export self.quote = quote # Csv file writer self._writer = csv.writer( output_file, delimiter="\t", lineterminator=lineterminator or os.linesep, quoting=csv.QUOTE_NONE, # Can't use no quoting without escaping, so use different dummy quote here escapechar="\\", quotechar="|", ) def write(self): """Write investigation file""" self._write_ontology_source_reference() self._write_basic_info() self._write_publications() self._write_contacts() self._write_studies() def _write_line(self, header, values): # Write an investigation line with header and values (potentially quoted) if self.quote: tpl = "".join((self.quote, "{}", self.quote)) values = [tpl.format(v) for v in values] self._writer.writerow((header, *values)) # Writer for headers and content of sections def _write_section( self, section_name: str, section: Dict[str, list], comments: Dict[str, list], headers: List[str] = None, ): # Add comments to section dict if comments: for key, value in comments.items(): section["Comment[{}]".format(key)] = value # Write the section name self._writer.writerow((section_name,)) # Write the lines in this section. if headers: # Use header order self._write_section_by_header_order(headers, section, section_name) else: # Use dict order for header, values in section.items(): self._write_line(header, values) def _write_section_by_header_order(self, headers, section, section_name): # Write section based on header order for header in headers: if header in section: values = section.pop(header) self._write_line(header, values) else: # pragma: no cover tpl = "No data found for header {} in section {}" msg = tpl.format(header, section_name) raise WriteIsatabException(msg) if len(section) > 0: # pragma: no cover tpl = "Leftover rows found in section {}:\n{}" msg = tpl.format(section_name, section) raise WriteIsatabException(msg) def _write_ontology_source_reference(self): # Write ONTOLOGY SOURCE REFERENCE section section = _init_multi_column_section(investigation_headers.ONTOLOGY_SOURCE_REF_KEYS) for ontology_ref in self.investigation.ontology_source_refs.values(): section[investigation_headers.TERM_SOURCE_NAME].append(ontology_ref.name) section[investigation_headers.TERM_SOURCE_FILE].append(ontology_ref.file) section[investigation_headers.TERM_SOURCE_VERSION].append(ontology_ref.version) section[investigation_headers.TERM_SOURCE_DESCRIPTION].append(ontology_ref.description) comments = _extract_comments(self.investigation.ontology_source_refs.values()) headers = _extract_section_header( list(self.investigation.ontology_source_refs.values())[0] if self.investigation.ontology_source_refs else None, investigation_headers.ONTOLOGY_SOURCE_REFERENCE, ) self._write_section( investigation_headers.ONTOLOGY_SOURCE_REFERENCE, section, comments, headers ) def _write_basic_info(self): # Write INVESTIGATION section basic_info = self.investigation.info section = { investigation_headers.INVESTIGATION_IDENTIFIER: [basic_info.identifier], investigation_headers.INVESTIGATION_TITLE: [basic_info.title], investigation_headers.INVESTIGATION_DESCRIPTION: [basic_info.description], investigation_headers.INVESTIGATION_SUBMISSION_DATE: [basic_info.submission_date], investigation_headers.INVESTIGATION_PUBLIC_RELEASE_DATE: [ basic_info.public_release_date ], } comments = _extract_comments([basic_info]) headers = _extract_section_header( self.investigation.info, investigation_headers.INVESTIGATION ) self._write_section(investigation_headers.INVESTIGATION, section, comments, headers) def _write_publications(self): # Write INVESTIGATION PUBLICATIONS section section = _init_multi_column_section(investigation_headers.INVESTIGATION_PUBLICATIONS_KEYS) for publication in self.investigation.publications: section[investigation_headers.INVESTIGATION_PUBMED_ID].append(publication.pubmed_id) section[investigation_headers.INVESTIGATION_PUBLICATION_DOI].append(publication.doi) section[investigation_headers.INVESTIGATION_PUBLICATION_AUTHOR_LIST].append( publication.authors ) section[investigation_headers.INVESTIGATION_PUBLICATION_TITLE].append(publication.title) if is_ontology_term_ref(publication.status): section[investigation_headers.INVESTIGATION_PUBLICATION_STATUS].append( publication.status.name or "" ) section[ investigation_headers.INVESTIGATION_PUBLICATION_STATUS_TERM_ACCESSION_NUMBER ].append(publication.status.accession or "") section[ investigation_headers.INVESTIGATION_PUBLICATION_STATUS_TERM_SOURCE_REF ].append(publication.status.ontology_name or "") else: section[investigation_headers.INVESTIGATION_PUBLICATION_STATUS].append( publication.status ) section[ investigation_headers.INVESTIGATION_PUBLICATION_STATUS_TERM_ACCESSION_NUMBER ].append("") section[ investigation_headers.INVESTIGATION_PUBLICATION_STATUS_TERM_SOURCE_REF ].append("") comments = _extract_comments(self.investigation.publications) headers = _extract_section_header( list(self.investigation.publications)[0] if self.investigation.publications else None, investigation_headers.INVESTIGATION_PUBLICATIONS, ) self._write_section( investigation_headers.INVESTIGATION_PUBLICATIONS, section, comments, headers ) def _write_contacts(self): # Write INVESTIGATION CONTACTS section section = _init_multi_column_section(investigation_headers.INVESTIGATION_CONTACTS_KEYS) for contact in self.investigation.contacts: section[investigation_headers.INVESTIGATION_PERSON_LAST_NAME].append(contact.last_name) section[investigation_headers.INVESTIGATION_PERSON_FIRST_NAME].append( contact.first_name ) section[investigation_headers.INVESTIGATION_PERSON_MID_INITIALS].append( contact.mid_initial ) section[investigation_headers.INVESTIGATION_PERSON_EMAIL].append(contact.email) section[investigation_headers.INVESTIGATION_PERSON_PHONE].append(contact.phone) section[investigation_headers.INVESTIGATION_PERSON_FAX].append(contact.fax) section[investigation_headers.INVESTIGATION_PERSON_ADDRESS].append(contact.address) section[investigation_headers.INVESTIGATION_PERSON_AFFILIATION].append( contact.affiliation ) if is_ontology_term_ref(contact.role): section[investigation_headers.INVESTIGATION_PERSON_ROLES].append( contact.role.name or "" ) section[ investigation_headers.INVESTIGATION_PERSON_ROLES_TERM_ACCESSION_NUMBER ].append(contact.role.accession or "") section[investigation_headers.INVESTIGATION_PERSON_ROLES_TERM_SOURCE_REF].append( contact.role.ontology_name or "" ) else: section[investigation_headers.INVESTIGATION_PERSON_ROLES].append(contact.role) section[ investigation_headers.INVESTIGATION_PERSON_ROLES_TERM_ACCESSION_NUMBER ].append("") section[investigation_headers.INVESTIGATION_PERSON_ROLES_TERM_SOURCE_REF].append("") comments = _extract_comments(self.investigation.contacts) headers = _extract_section_header( list(self.investigation.contacts)[0] if self.investigation.contacts else None, investigation_headers.INVESTIGATION_CONTACTS, ) self._write_section( investigation_headers.INVESTIGATION_CONTACTS, section, comments, headers ) def _write_studies(self): # Write STUDY sections for study in self.investigation.studies: self._write_study_basic_info(study) self._write_study_design_descriptors(study) self._write_study_publications(study) self._write_study_factors(study) self._write_study_assays(study) self._write_study_protocols(study) self._write_study_contacts(study) def _write_study_basic_info(self, study: models.StudyInfo): # Read STUDY INFO section basic_info = study.info section = { investigation_headers.STUDY_IDENTIFIER: [basic_info.identifier], investigation_headers.STUDY_TITLE: [basic_info.title], investigation_headers.STUDY_DESCRIPTION: [basic_info.description], investigation_headers.STUDY_SUBMISSION_DATE: [basic_info.submission_date], investigation_headers.STUDY_PUBLIC_RELEASE_DATE: [basic_info.public_release_date], investigation_headers.STUDY_FILE_NAME: [basic_info.path or ""], } comments = _extract_comments([basic_info]) headers = _extract_section_header(basic_info, investigation_headers.STUDY) self._write_section(investigation_headers.STUDY, section, comments, headers) def _write_study_design_descriptors(self, study: models.StudyInfo): # Read STUDY DESIGN DESCRIPTORS section section = _init_multi_column_section(investigation_headers.STUDY_DESIGN_DESCR_KEYS) for design in study.designs: if is_ontology_term_ref(design.type): section[investigation_headers.STUDY_DESIGN_TYPE].append(design.type.name or "") section[investigation_headers.STUDY_DESIGN_TYPE_TERM_ACCESSION_NUMBER].append( design.type.accession or "" ) section[investigation_headers.STUDY_DESIGN_TYPE_TERM_SOURCE_REF].append( design.type.ontology_name or "" ) else: section[investigation_headers.STUDY_DESIGN_TYPE].append(design.type) section[investigation_headers.STUDY_DESIGN_TYPE_TERM_ACCESSION_NUMBER].append("") section[investigation_headers.STUDY_DESIGN_TYPE_TERM_SOURCE_REF].append("") comments = _extract_comments(study.designs) headers = _extract_section_header( list(study.designs)[0] if study.designs else None, investigation_headers.STUDY_DESIGN_DESCRIPTORS, ) self._write_section( investigation_headers.STUDY_DESIGN_DESCRIPTORS, section, comments, headers ) def _write_study_publications(self, study: models.StudyInfo): # Write STUDY PUBLICATIONS section section = _init_multi_column_section(investigation_headers.STUDY_PUBLICATIONS_KEYS) for publication in study.publications: section[investigation_headers.STUDY_PUBMED_ID].append(publication.pubmed_id) section[investigation_headers.STUDY_PUBLICATION_DOI].append(publication.doi) section[investigation_headers.STUDY_PUBLICATION_AUTHOR_LIST].append(publication.authors) section[investigation_headers.STUDY_PUBLICATION_TITLE].append(publication.title) if is_ontology_term_ref(publication.status): section[investigation_headers.STUDY_PUBLICATION_STATUS].append( publication.status.name or "" ) section[ investigation_headers.STUDY_PUBLICATION_STATUS_TERM_ACCESSION_NUMBER ].append(publication.status.accession or "") section[investigation_headers.STUDY_PUBLICATION_STATUS_TERM_SOURCE_REF].append( publication.status.ontology_name or "" ) else: section[investigation_headers.STUDY_PUBLICATION_STATUS].append(publication.status) section[ investigation_headers.STUDY_PUBLICATION_STATUS_TERM_ACCESSION_NUMBER ].append("") section[investigation_headers.STUDY_PUBLICATION_STATUS_TERM_SOURCE_REF].append("") comments = _extract_comments(study.publications) headers = _extract_section_header( list(study.publications)[0] if study.publications else None, investigation_headers.STUDY_PUBLICATIONS, ) self._write_section(investigation_headers.STUDY_PUBLICATIONS, section, comments, headers) def _write_study_factors(self, study: models.StudyInfo): # Write STUDY FACTORS section section = _init_multi_column_section(investigation_headers.STUDY_FACTORS_KEYS) for factor in study.factors.values(): section[investigation_headers.STUDY_FACTOR_NAME].append(factor.name) if is_ontology_term_ref(factor.type): section[investigation_headers.STUDY_FACTOR_TYPE].append(factor.type.name) section[investigation_headers.STUDY_FACTOR_TYPE_TERM_ACCESSION_NUMBER].append( factor.type.accession ) section[investigation_headers.STUDY_FACTOR_TYPE_TERM_SOURCE_REF].append( factor.type.ontology_name ) else: section[investigation_headers.STUDY_FACTOR_TYPE].append(factor.type) section[investigation_headers.STUDY_FACTOR_TYPE_TERM_ACCESSION_NUMBER].append("") section[investigation_headers.STUDY_FACTOR_TYPE_TERM_SOURCE_REF].append("") comments = _extract_comments(study.factors.values()) headers = _extract_section_header( list(study.factors.values())[0] if study.factors else None, investigation_headers.STUDY_FACTORS, ) self._write_section(investigation_headers.STUDY_FACTORS, section, comments, headers) def _write_study_assays(self, study: models.StudyInfo): # Write STUDY ASSAYS section section = _init_multi_column_section(investigation_headers.STUDY_ASSAYS_KEYS) for assay in study.assays: section[investigation_headers.STUDY_ASSAY_FILE_NAME].append(assay.path or "") if is_ontology_term_ref(assay.measurement_type): section[investigation_headers.STUDY_ASSAY_MEASUREMENT_TYPE].append( assay.measurement_type.name or "" ) section[ investigation_headers.STUDY_ASSAY_MEASUREMENT_TYPE_TERM_ACCESSION_NUMBER ].append(assay.measurement_type.accession or "") section[investigation_headers.STUDY_ASSAY_MEASUREMENT_TYPE_TERM_SOURCE_REF].append( assay.measurement_type.ontology_name or "" ) else: section[investigation_headers.STUDY_ASSAY_MEASUREMENT_TYPE].append( assay.measurement_type ) section[ investigation_headers.STUDY_ASSAY_MEASUREMENT_TYPE_TERM_ACCESSION_NUMBER ].append("") section[investigation_headers.STUDY_ASSAY_MEASUREMENT_TYPE_TERM_SOURCE_REF].append( "" ) if is_ontology_term_ref(assay.technology_type): section[investigation_headers.STUDY_ASSAY_TECHNOLOGY_TYPE].append( assay.technology_type.name or "" ) section[ investigation_headers.STUDY_ASSAY_TECHNOLOGY_TYPE_TERM_ACCESSION_NUMBER ].append(assay.technology_type.accession or "") section[investigation_headers.STUDY_ASSAY_TECHNOLOGY_TYPE_TERM_SOURCE_REF].append( assay.technology_type.ontology_name or "" ) else: section[investigation_headers.STUDY_ASSAY_TECHNOLOGY_TYPE].append( assay.technology_type ) section[ investigation_headers.STUDY_ASSAY_TECHNOLOGY_TYPE_TERM_ACCESSION_NUMBER ].append("") section[investigation_headers.STUDY_ASSAY_TECHNOLOGY_TYPE_TERM_SOURCE_REF].append( "" ) section[investigation_headers.STUDY_ASSAY_TECHNOLOGY_PLATFORM].append(assay.platform) comments = _extract_comments(study.assays) headers = _extract_section_header( list(study.assays)[0] if study.assays else None, investigation_headers.STUDY_ASSAYS ) self._write_section(investigation_headers.STUDY_ASSAYS, section, comments, headers) def _write_study_protocols(self, study: models.StudyInfo): # Write STUDY PROTOCOLS section section = _init_multi_column_section(investigation_headers.STUDY_PROTOCOLS_KEYS) for protocol in study.protocols.values(): section[investigation_headers.STUDY_PROTOCOL_NAME].append(protocol.name) if is_ontology_term_ref(protocol.type): section[investigation_headers.STUDY_PROTOCOL_TYPE].append(protocol.type.name or "") section[investigation_headers.STUDY_PROTOCOL_TYPE_TERM_ACCESSION_NUMBER].append( protocol.type.accession or "" ) section[investigation_headers.STUDY_PROTOCOL_TYPE_TERM_SOURCE_REF].append( protocol.type.ontology_name or "" ) else: section[investigation_headers.STUDY_PROTOCOL_TYPE].append(protocol.type) section[investigation_headers.STUDY_PROTOCOL_TYPE_TERM_ACCESSION_NUMBER].append("") section[investigation_headers.STUDY_PROTOCOL_TYPE_TERM_SOURCE_REF].append("") section[investigation_headers.STUDY_PROTOCOL_DESCRIPTION].append(protocol.description) section[investigation_headers.STUDY_PROTOCOL_URI].append(protocol.uri) section[investigation_headers.STUDY_PROTOCOL_VERSION].append(protocol.version) names = [] accessions = [] ontologies = [] for parameter in protocol.parameters.values(): if is_ontology_term_ref(parameter): names.append(parameter.name or "") accessions.append(parameter.accession or "") ontologies.append(parameter.ontology_name or "") else: names.append(parameter.name) accessions.append("") ontologies.append("") section[investigation_headers.STUDY_PROTOCOL_PARAMETERS_NAME].append(";".join(names)) section[ investigation_headers.STUDY_PROTOCOL_PARAMETERS_NAME_TERM_ACCESSION_NUMBER ].append(";".join(accessions)) section[investigation_headers.STUDY_PROTOCOL_PARAMETERS_NAME_TERM_SOURCE_REF].append( ";".join(ontologies) ) names = [] types = [] accessions = [] ontologies = [] for component in protocol.components.values(): names.append(component.name) if is_ontology_term_ref(component.type): types.append(component.type.name or "") accessions.append(component.type.accession or "") ontologies.append(component.type.ontology_name or "") else: names.append(component.type) accessions.append("") ontologies.append("") section[investigation_headers.STUDY_PROTOCOL_COMPONENTS_NAME].append(";".join(names)) section[investigation_headers.STUDY_PROTOCOL_COMPONENTS_TYPE].append(";".join(types)) section[ investigation_headers.STUDY_PROTOCOL_COMPONENTS_TYPE_TERM_ACCESSION_NUMBER ].append(";".join(accessions)) section[investigation_headers.STUDY_PROTOCOL_COMPONENTS_TYPE_TERM_SOURCE_REF].append( ";".join(ontologies) ) comments = _extract_comments(study.protocols.values()) headers = _extract_section_header( list(study.protocols.values())[0] if study.protocols else None, investigation_headers.STUDY_PROTOCOLS, ) self._write_section(investigation_headers.STUDY_PROTOCOLS, section, comments, headers) def _write_study_contacts(self, study: models.StudyInfo): # Write STUDY CONTACTS section section = _init_multi_column_section(investigation_headers.STUDY_CONTACTS_KEYS) for contact in study.contacts: section[investigation_headers.STUDY_PERSON_LAST_NAME].append(contact.last_name) section[investigation_headers.STUDY_PERSON_FIRST_NAME].append(contact.first_name) section[investigation_headers.STUDY_PERSON_MID_INITIALS].append(contact.mid_initial) section[investigation_headers.STUDY_PERSON_EMAIL].append(contact.email) section[investigation_headers.STUDY_PERSON_PHONE].append(contact.phone) section[investigation_headers.STUDY_PERSON_FAX].append(contact.fax) section[investigation_headers.STUDY_PERSON_ADDRESS].append(contact.address) section[investigation_headers.STUDY_PERSON_AFFILIATION].append(contact.affiliation) if is_ontology_term_ref(contact.role): section[investigation_headers.STUDY_PERSON_ROLES].append(contact.role.name or "") section[investigation_headers.STUDY_PERSON_ROLES_TERM_ACCESSION_NUMBER].append( contact.role.accession or "" ) section[investigation_headers.STUDY_PERSON_ROLES_TERM_SOURCE_REF].append( contact.role.ontology_name or "" ) else: section[investigation_headers.STUDY_PERSON_ROLES].append(contact.role) section[investigation_headers.STUDY_PERSON_ROLES_TERM_ACCESSION_NUMBER].append("") section[investigation_headers.STUDY_PERSON_ROLES_TERM_SOURCE_REF].append("") comments = _extract_comments(study.contacts) headers = _extract_section_header( list(study.contacts)[0] if study.contacts else None, investigation_headers.STUDY_CONTACTS, ) self._write_section(investigation_headers.STUDY_CONTACTS, section, comments, headers)
0.493164
0.22627
import logging import requests import azure.cosmos.cosmos_client as cosmos_client import azure.cosmos.errors as errors import azure.cosmos.documents as documents import time from . import models def load_collection(url, api_key, db_id, collection_id, rows, version): loader = Loader(url, api_key, db_id, collection_id, rows, version) loader.load_subject_documents() class Loader: def __init__(self, cosmosdb_uri, cosmos_key, db_id, collection_id, rows, version): master_key = "masterKey" self.cosmos_db_client = cosmos_client.CosmosClient( url_connection=cosmosdb_uri, auth={master_key: cosmos_key} ) self.collection_link = "dbs/" + db_id + "/colls/" + collection_id self.db_id = db_id self.collection_id = collection_id self.rows = rows self.version = version def load_subject_documents(self): options = {"partitionKey": str(self.version)} sproc_link = self.collection_link + "/sprocs/bulkImport" subject_count = 0 new_docs = [] sproc_count = 0 for row in self.rows: subject_count += 1 sproc_count += 1 if subject_count == 1: logging.info("skipping header row") continue # Transform row into json object new_docs.append(models.build_subject_doc(row, self.version)) if sproc_count == 100: logging.info(f"Begining execution of stored procedure for {sproc_count} documents") self.cosmos_db_client.ExecuteStoredProcedure(sproc_link, [new_docs], options) logging.info(f"Successfully loaded another {sproc_count} documents") # Reset values new_docs = [] sproc_count = 0 time.sleep(2) if sproc_count > 0: logging.info(f"Begining execution of stored procedure for {sproc_count} documents") self.cosmos_db_client.ExecuteStoredProcedure(sproc_link, [new_docs], options) logging.info(f"Successfully loaded another {sproc_count} documents") logging.info( f"loaded {subject_count - 1} into {self.collection_id} collection in {self.db_id} database" )
SubjectBuilder/database.py
import logging import requests import azure.cosmos.cosmos_client as cosmos_client import azure.cosmos.errors as errors import azure.cosmos.documents as documents import time from . import models def load_collection(url, api_key, db_id, collection_id, rows, version): loader = Loader(url, api_key, db_id, collection_id, rows, version) loader.load_subject_documents() class Loader: def __init__(self, cosmosdb_uri, cosmos_key, db_id, collection_id, rows, version): master_key = "masterKey" self.cosmos_db_client = cosmos_client.CosmosClient( url_connection=cosmosdb_uri, auth={master_key: cosmos_key} ) self.collection_link = "dbs/" + db_id + "/colls/" + collection_id self.db_id = db_id self.collection_id = collection_id self.rows = rows self.version = version def load_subject_documents(self): options = {"partitionKey": str(self.version)} sproc_link = self.collection_link + "/sprocs/bulkImport" subject_count = 0 new_docs = [] sproc_count = 0 for row in self.rows: subject_count += 1 sproc_count += 1 if subject_count == 1: logging.info("skipping header row") continue # Transform row into json object new_docs.append(models.build_subject_doc(row, self.version)) if sproc_count == 100: logging.info(f"Begining execution of stored procedure for {sproc_count} documents") self.cosmos_db_client.ExecuteStoredProcedure(sproc_link, [new_docs], options) logging.info(f"Successfully loaded another {sproc_count} documents") # Reset values new_docs = [] sproc_count = 0 time.sleep(2) if sproc_count > 0: logging.info(f"Begining execution of stored procedure for {sproc_count} documents") self.cosmos_db_client.ExecuteStoredProcedure(sproc_link, [new_docs], options) logging.info(f"Successfully loaded another {sproc_count} documents") logging.info( f"loaded {subject_count - 1} into {self.collection_id} collection in {self.db_id} database" )
0.446977
0.096068
from channels.generic.websocket import JsonWebsocketConsumer from asgiref.sync import async_to_sync from .models import Topic, ChatMessage from django.contrib.auth.models import User from django.utils.html import escape from django.core import serializers import markdown import bleach import re from django.conf import settings from django.urls import reverse import time, datetime from django.core.cache import cache from django.core.exceptions import ObjectDoesNotExist from django.utils import timezone from hackerschat import celery class ChatConsumer(JsonWebsocketConsumer): def connect(self): topic_name = self.scope['url_route']['kwargs']['topic_name'] try: topic = Topic.objects.get(name=topic_name) except ObjectDoesNotExist: self.close() return async_to_sync(self.channel_layer.group_add)(topic_name, self.channel_name) user_info = {'last_seen' : time.time(), 'reply_channel' : self.channel_name, 'topic' : topic_name} #update user_list in redis if self.scope["user"].is_authenticated: user_info['username'] = self.scope["user"].username else: user_info['username'] = None user_list = cache.get('user_list') if user_list == None: user_list = list() user_list.append(user_info) cache.set('user_list', user_list) else: user_updated = False for item in user_list: if item['reply_channel'] == user_info['reply_channel']: user_list.remove(item) user_list.append(user_info) user_updated = True if not user_updated: user_list.append(user_info) cache.set('user_list', user_list) self.accept() #send presence info to user topic_users = cache.get('topic_users') topic_anon_count = cache.get('topic_anon_count') if topic_users == None or topic_anon_count == None or topic_name not in topic_users or topic_name not in topic_anon_count: return self.send_json( { 'message_type': 'presence', 'payload': { 'channel_name': topic_name, 'members': list(topic_users[topic_name]), 'lurkers': topic_anon_count[topic_name], } } ) def receive_json(self, content): topic_name = self.scope['url_route']['kwargs']['topic_name'] try: topic = Topic.objects.get(name=topic_name) except ObjectDoesNotExist: return if type(content) is not dict: return message = content.get('message', None) heartbeat = content.get('heartbeat', None) last_message_id = content.get('last_message_id', None) if message == None and heartbeat == None and last_message_id == None: return #heartbeat if heartbeat: self.heartbeat(topic_name) return #scrollback if last_message_id: self.scrollback(topic, last_message_id) return #chat message if message: self.handle_chat_message(message, topic) def disconnect(self, code): topic_name = self.scope['url_route']['kwargs']['topic_name'] try: topic = Topic.objects.get(name=topic_name) except ObjectDoesNotExist: return async_to_sync(self.channel_layer.group_discard)(topic_name, self.channel_name) user_info = {'last_seen' : time.time(), 'reply_channel' : self.channel_name, 'topic' : topic_name} #remove from redis user_list = cache.get('user_list') if user_list != None: for item in user_list: if item['reply_channel'] == user_info['reply_channel']: user_list.remove(item) cache.set('user_list', user_list) def heartbeat(self, topic_name): user_info = {'last_seen' : time.time(), 'reply_channel' : self.channel_name, 'topic' : topic_name} #add to redis if self.scope["user"].is_authenticated: user_info['username'] = self.scope["user"].username else: user_info['username'] = None user_list = cache.get('user_list') if user_list != None: user_updated = False for item in user_list: if item['reply_channel'] == user_info['reply_channel']: user_list.remove(item) item['last_seen'] = time.time() user_list.append(item) cache.set('user_list', user_list) user_updated = True if not user_updated: user_list.append(user_info) cache.set('user_list', user_list) def scrollback(self, topic, last_message_id): try: last_message_id = int(last_message_id) except ValueError: return chat_queryset = ChatMessage.objects.filter(topic=topic).filter(id__lte=last_message_id).order_by("-created")[:10] chat_message_count = len(chat_queryset) if chat_message_count > 0: first_message_id = chat_queryset[len(chat_queryset)-1].id else: first_message_id = -1 previous_id = -1 if first_message_id != -1: try: previous_id = ChatMessage.objects.filter(topic=topic).filter(pk__lt=first_message_id).order_by("-pk")[:1][0].id except IndexError: previous_id = -1 chat_messages = reversed(chat_queryset) cleaned_chat_messages = list() for item in chat_messages: current_message = item.message_html user_profile_url = reverse('user_auth:public_user_profile', args=[item.user.username]) cleaned_item = {'user' : item.user.username, 'message' : current_message, 'user_profile_url' : user_profile_url} cleaned_chat_messages.append(cleaned_item) my_dict = { 'messages' : cleaned_chat_messages, 'previous_id' : previous_id } self.send_json( { 'message_type' : 'scrollback', 'messages' : cleaned_chat_messages, 'previous_id' : previous_id, }, ) def handle_chat_message(self, message, topic): if len(message) > 1500: self.send_json({ 'type': 'error', 'payload': { 'message': "Maximum message size is 1500 characters.", } }) return topic_name = topic.name #ignore message if user is not authenticated if not self.scope["user"].is_authenticated or not message: return #check if rate limit has been reached if ChatMessage.objects.filter(user=self.scope["user"]).filter(created__gte=timezone.now() - datetime.timedelta(minutes=1)).count() >= 10: self.send_json({ 'type': 'error', 'payload': { 'message': "Rate limit reached. You can send 10 messages per minute.", } }) return current_message = escape(message) urlRegex = re.compile( u'(?isu)(\\b(?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)[^\\s()<' u'>\\[\\]]+[^\\s`!()\\[\\]{};:\'".,<>?\xab\xbb\u201c\u201d\u2018\u2019])' ) processed_urls = list() for obj in urlRegex.finditer(current_message): old_url = obj.group(0) if old_url in processed_urls: continue processed_urls.append(old_url) new_url = old_url if not old_url.startswith(('http://', 'https://')): new_url = 'http://' + new_url new_url = '<a href="' + new_url + '" rel="noopener noreferrer nofollow" target="_blank">' + new_url + "</a>" current_message = current_message.replace(old_url, new_url) m = ChatMessage(user=self.scope["user"],topic=topic, message=message, message_html=current_message) m.save() celery.check_message_toxicity.delay(m.id) user_profile_url = reverse('user_auth:public_user_profile', args=[m.user.username]) my_dict = {'user' : m.user.username, 'message' : current_message, 'user_profile_url' : user_profile_url} async_to_sync(self.channel_layer.group_send)( topic_name, { "type": "group.message", 'user' : m.user.username, 'message' : current_message, 'user_profile_url' : user_profile_url }, ) def group_message(self, event): self.send_json({ 'user' : event['user'], 'message' : event['message'], 'user_profile_url' : event['user_profile_url'] }) def presence_data(self, event): self.send_json({ 'message_type': 'presence', 'payload': event['payload'] })
mainapp/consumers.py
from channels.generic.websocket import JsonWebsocketConsumer from asgiref.sync import async_to_sync from .models import Topic, ChatMessage from django.contrib.auth.models import User from django.utils.html import escape from django.core import serializers import markdown import bleach import re from django.conf import settings from django.urls import reverse import time, datetime from django.core.cache import cache from django.core.exceptions import ObjectDoesNotExist from django.utils import timezone from hackerschat import celery class ChatConsumer(JsonWebsocketConsumer): def connect(self): topic_name = self.scope['url_route']['kwargs']['topic_name'] try: topic = Topic.objects.get(name=topic_name) except ObjectDoesNotExist: self.close() return async_to_sync(self.channel_layer.group_add)(topic_name, self.channel_name) user_info = {'last_seen' : time.time(), 'reply_channel' : self.channel_name, 'topic' : topic_name} #update user_list in redis if self.scope["user"].is_authenticated: user_info['username'] = self.scope["user"].username else: user_info['username'] = None user_list = cache.get('user_list') if user_list == None: user_list = list() user_list.append(user_info) cache.set('user_list', user_list) else: user_updated = False for item in user_list: if item['reply_channel'] == user_info['reply_channel']: user_list.remove(item) user_list.append(user_info) user_updated = True if not user_updated: user_list.append(user_info) cache.set('user_list', user_list) self.accept() #send presence info to user topic_users = cache.get('topic_users') topic_anon_count = cache.get('topic_anon_count') if topic_users == None or topic_anon_count == None or topic_name not in topic_users or topic_name not in topic_anon_count: return self.send_json( { 'message_type': 'presence', 'payload': { 'channel_name': topic_name, 'members': list(topic_users[topic_name]), 'lurkers': topic_anon_count[topic_name], } } ) def receive_json(self, content): topic_name = self.scope['url_route']['kwargs']['topic_name'] try: topic = Topic.objects.get(name=topic_name) except ObjectDoesNotExist: return if type(content) is not dict: return message = content.get('message', None) heartbeat = content.get('heartbeat', None) last_message_id = content.get('last_message_id', None) if message == None and heartbeat == None and last_message_id == None: return #heartbeat if heartbeat: self.heartbeat(topic_name) return #scrollback if last_message_id: self.scrollback(topic, last_message_id) return #chat message if message: self.handle_chat_message(message, topic) def disconnect(self, code): topic_name = self.scope['url_route']['kwargs']['topic_name'] try: topic = Topic.objects.get(name=topic_name) except ObjectDoesNotExist: return async_to_sync(self.channel_layer.group_discard)(topic_name, self.channel_name) user_info = {'last_seen' : time.time(), 'reply_channel' : self.channel_name, 'topic' : topic_name} #remove from redis user_list = cache.get('user_list') if user_list != None: for item in user_list: if item['reply_channel'] == user_info['reply_channel']: user_list.remove(item) cache.set('user_list', user_list) def heartbeat(self, topic_name): user_info = {'last_seen' : time.time(), 'reply_channel' : self.channel_name, 'topic' : topic_name} #add to redis if self.scope["user"].is_authenticated: user_info['username'] = self.scope["user"].username else: user_info['username'] = None user_list = cache.get('user_list') if user_list != None: user_updated = False for item in user_list: if item['reply_channel'] == user_info['reply_channel']: user_list.remove(item) item['last_seen'] = time.time() user_list.append(item) cache.set('user_list', user_list) user_updated = True if not user_updated: user_list.append(user_info) cache.set('user_list', user_list) def scrollback(self, topic, last_message_id): try: last_message_id = int(last_message_id) except ValueError: return chat_queryset = ChatMessage.objects.filter(topic=topic).filter(id__lte=last_message_id).order_by("-created")[:10] chat_message_count = len(chat_queryset) if chat_message_count > 0: first_message_id = chat_queryset[len(chat_queryset)-1].id else: first_message_id = -1 previous_id = -1 if first_message_id != -1: try: previous_id = ChatMessage.objects.filter(topic=topic).filter(pk__lt=first_message_id).order_by("-pk")[:1][0].id except IndexError: previous_id = -1 chat_messages = reversed(chat_queryset) cleaned_chat_messages = list() for item in chat_messages: current_message = item.message_html user_profile_url = reverse('user_auth:public_user_profile', args=[item.user.username]) cleaned_item = {'user' : item.user.username, 'message' : current_message, 'user_profile_url' : user_profile_url} cleaned_chat_messages.append(cleaned_item) my_dict = { 'messages' : cleaned_chat_messages, 'previous_id' : previous_id } self.send_json( { 'message_type' : 'scrollback', 'messages' : cleaned_chat_messages, 'previous_id' : previous_id, }, ) def handle_chat_message(self, message, topic): if len(message) > 1500: self.send_json({ 'type': 'error', 'payload': { 'message': "Maximum message size is 1500 characters.", } }) return topic_name = topic.name #ignore message if user is not authenticated if not self.scope["user"].is_authenticated or not message: return #check if rate limit has been reached if ChatMessage.objects.filter(user=self.scope["user"]).filter(created__gte=timezone.now() - datetime.timedelta(minutes=1)).count() >= 10: self.send_json({ 'type': 'error', 'payload': { 'message': "Rate limit reached. You can send 10 messages per minute.", } }) return current_message = escape(message) urlRegex = re.compile( u'(?isu)(\\b(?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)[^\\s()<' u'>\\[\\]]+[^\\s`!()\\[\\]{};:\'".,<>?\xab\xbb\u201c\u201d\u2018\u2019])' ) processed_urls = list() for obj in urlRegex.finditer(current_message): old_url = obj.group(0) if old_url in processed_urls: continue processed_urls.append(old_url) new_url = old_url if not old_url.startswith(('http://', 'https://')): new_url = 'http://' + new_url new_url = '<a href="' + new_url + '" rel="noopener noreferrer nofollow" target="_blank">' + new_url + "</a>" current_message = current_message.replace(old_url, new_url) m = ChatMessage(user=self.scope["user"],topic=topic, message=message, message_html=current_message) m.save() celery.check_message_toxicity.delay(m.id) user_profile_url = reverse('user_auth:public_user_profile', args=[m.user.username]) my_dict = {'user' : m.user.username, 'message' : current_message, 'user_profile_url' : user_profile_url} async_to_sync(self.channel_layer.group_send)( topic_name, { "type": "group.message", 'user' : m.user.username, 'message' : current_message, 'user_profile_url' : user_profile_url }, ) def group_message(self, event): self.send_json({ 'user' : event['user'], 'message' : event['message'], 'user_profile_url' : event['user_profile_url'] }) def presence_data(self, event): self.send_json({ 'message_type': 'presence', 'payload': event['payload'] })
0.331661
0.057071
from selenium import webdriver from bs4 import BeautifulSoup import string class StockMarket(object): def __init__(self, driver, symbols_file=None): super(StockMarket, self).__init__() self.driver = driver if symbols_file is not None: self.symbols = self.stock_symbols_from_file(symbols_file) else: self.symbols = self.default_stock_symbols() # Method used to get stock symbols a stock exchange def stock_symbols_for_exchange(self, exchange): stock_symols = [] # Goes alphabetically through each page to scrape each stock symbol for c in string.ascii_uppercase: list_page = 'http://www.eoddata.com/stocklist/'+exchange+'/'+c+'.htm' self.driver.get(list_page) content = self.driver.page_source soup = BeautifulSoup(content, 'lxml') parent_box = soup.find('table', attrs={'class': 'quotes'}) for child in parent_box.findAll('a'): if len(child.text) > 0: stock_symols.append(child.text) return stock_symols def stock_symbols_for_exchanges(self, list_of_exchanges): stock_symbols = [] for exchange in list_of_exchanges: stock_symbols.extend(self.stock_symbols_for_exchange(exchange)) return stock_symbols def stock_symbols_from_file(self, file_name): symbols = [] try: with open(file_name, 'r') as filehandle: for line in filehandle: # remove linebreak which is the last character of the string symbol = line[:-1] # add item to the list symbols.append(symbol) except Exception: return None return symbols def default_stock_symbols(self): symbols = self.stock_symbols_from_file('default_stock_symbols.txt') if symbols == None: # If not able to read from disk, try to get from internt again if len(symbols) == 0: symbols = self.stock_symbols_for_exchanges(['NYSE', 'NASDAQ']) with open('default_stock_symbols.txt', 'a+') as filehandle: for symbol in symbols: filehandle.write("%s\n" % symbol) return symbols
Classes/market.py
from selenium import webdriver from bs4 import BeautifulSoup import string class StockMarket(object): def __init__(self, driver, symbols_file=None): super(StockMarket, self).__init__() self.driver = driver if symbols_file is not None: self.symbols = self.stock_symbols_from_file(symbols_file) else: self.symbols = self.default_stock_symbols() # Method used to get stock symbols a stock exchange def stock_symbols_for_exchange(self, exchange): stock_symols = [] # Goes alphabetically through each page to scrape each stock symbol for c in string.ascii_uppercase: list_page = 'http://www.eoddata.com/stocklist/'+exchange+'/'+c+'.htm' self.driver.get(list_page) content = self.driver.page_source soup = BeautifulSoup(content, 'lxml') parent_box = soup.find('table', attrs={'class': 'quotes'}) for child in parent_box.findAll('a'): if len(child.text) > 0: stock_symols.append(child.text) return stock_symols def stock_symbols_for_exchanges(self, list_of_exchanges): stock_symbols = [] for exchange in list_of_exchanges: stock_symbols.extend(self.stock_symbols_for_exchange(exchange)) return stock_symbols def stock_symbols_from_file(self, file_name): symbols = [] try: with open(file_name, 'r') as filehandle: for line in filehandle: # remove linebreak which is the last character of the string symbol = line[:-1] # add item to the list symbols.append(symbol) except Exception: return None return symbols def default_stock_symbols(self): symbols = self.stock_symbols_from_file('default_stock_symbols.txt') if symbols == None: # If not able to read from disk, try to get from internt again if len(symbols) == 0: symbols = self.stock_symbols_for_exchanges(['NYSE', 'NASDAQ']) with open('default_stock_symbols.txt', 'a+') as filehandle: for symbol in symbols: filehandle.write("%s\n" % symbol) return symbols
0.428473
0.091382
from networkx.exception import NetworkXError import matplotlib.pyplot as plt class Graph(object): node_dict_factory = dict node_attr_dict_factory = dict adjlist_outer_dict_factory = dict adjlist_inner_dict_factory = dict edge_attr_dict_factory = dict graph_attr_dict_factory = dict def __init__(self, incoming_graph_data=None, **attr): self.graph_attr_dict_factory = self.graph_attr_dict_factory self.node_dict_factory = self.node_dict_factory self.node_attr_dict_factory = self.node_attr_dict_factory self.adjlist_outer_dict_factory = self.adjlist_outer_dict_factory self.adjlist_inner_dict_factory = self.adjlist_inner_dict_factory self.edge_attr_dict_factory = self.edge_attr_dict_factory self.graph = self.graph_attr_dict_factory() self._node = self.node_dict_factory() self._adj = self.adjlist_outer_dict_factory() ''' if incoming_graph_data is not None: convert.to_networkx_graph(incoming_graph_data, create_using=self) self.graph.update(attr) ''' def add_node(self, node_for_adding, **attr): #addnode if node_for_adding not in self._node: self._adj[node_for_adding] = self.adjlist_inner_dict_factory() attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory() attr_dict.update(attr) else: self._node[node_for_adding].update(attr) def update(self, edges=None, nodes=None): if edges is not None: if nodes is not None: self.add_nodes_from(nodes) self.add_edges_from(edges) else: try: graph_nodes = edges.nodes graph_edges = edges.edges except AttributeError: self.add_edges_from(edges) else: self.add_nodes_from(graph_nodes.data()) self.add_edges_from(graph_edges.data()) self.graph.update(edges.graph) elif nodes is not None: self.add_nodes_from(nodes) else: raise NetworkXError("update needs nodes or edges input") def add_nodes_from(self, nodes_for_adding, **attr): #add nodes from for n in nodes_for_adding: try: if n not in self._node: self._adj[n] = self.adjlist_inner_dict_factory() attr_dict = self._node[n] = self.node_attr_dict_factory() attr_dict.update(attr) else: self._node[n].update(attr) except TypeError: nn, ndict = n if nn not in self._node: self.adj[nn] = self.adjlist_inner_dict_factory() newdict = attr.copy() newdict.update(newdict) attr_dict = self._node[nn] = self.node_attr_dict_factory() attr_dict.update(newdict) else: olddict = self._node[nn] olddict.update(attr) olddict.update(ndict) def add_edges_from(self, ebunch_to_add, **attr): for e in ebunch_to_add: ne = len(e) if ne == 3: u, v, dd = e elif ne == 2: u, v = e dd = {} else: raise NetworkXError("Egde tuple %s must be a 2-tuple or 3tuple"%(e,)) if u not in self._node: self._adj[u] = self.adjlist_inner_dict_factory() self._node[u] = self.node_attr_dict_factory() if v not in self._node: self._adj[v] = self.adjlist_inner_dict_factory() self._node[v] = self.node_attr_dict_factory() datadict = self._adj[u].get(v, self.edge_attr_dict_factory()) datadict.update(attr) datadict.update(dd) self._adj[u][v] = datadict self._adj[v][u] = datadict g = Graph() mylist = tuple([(1,2), (2,6), (2,3), (3,4), (3,5)]) g.add_edges_from(mylist) h = plt.draw(g)
graphcu/graph.py
from networkx.exception import NetworkXError import matplotlib.pyplot as plt class Graph(object): node_dict_factory = dict node_attr_dict_factory = dict adjlist_outer_dict_factory = dict adjlist_inner_dict_factory = dict edge_attr_dict_factory = dict graph_attr_dict_factory = dict def __init__(self, incoming_graph_data=None, **attr): self.graph_attr_dict_factory = self.graph_attr_dict_factory self.node_dict_factory = self.node_dict_factory self.node_attr_dict_factory = self.node_attr_dict_factory self.adjlist_outer_dict_factory = self.adjlist_outer_dict_factory self.adjlist_inner_dict_factory = self.adjlist_inner_dict_factory self.edge_attr_dict_factory = self.edge_attr_dict_factory self.graph = self.graph_attr_dict_factory() self._node = self.node_dict_factory() self._adj = self.adjlist_outer_dict_factory() ''' if incoming_graph_data is not None: convert.to_networkx_graph(incoming_graph_data, create_using=self) self.graph.update(attr) ''' def add_node(self, node_for_adding, **attr): #addnode if node_for_adding not in self._node: self._adj[node_for_adding] = self.adjlist_inner_dict_factory() attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory() attr_dict.update(attr) else: self._node[node_for_adding].update(attr) def update(self, edges=None, nodes=None): if edges is not None: if nodes is not None: self.add_nodes_from(nodes) self.add_edges_from(edges) else: try: graph_nodes = edges.nodes graph_edges = edges.edges except AttributeError: self.add_edges_from(edges) else: self.add_nodes_from(graph_nodes.data()) self.add_edges_from(graph_edges.data()) self.graph.update(edges.graph) elif nodes is not None: self.add_nodes_from(nodes) else: raise NetworkXError("update needs nodes or edges input") def add_nodes_from(self, nodes_for_adding, **attr): #add nodes from for n in nodes_for_adding: try: if n not in self._node: self._adj[n] = self.adjlist_inner_dict_factory() attr_dict = self._node[n] = self.node_attr_dict_factory() attr_dict.update(attr) else: self._node[n].update(attr) except TypeError: nn, ndict = n if nn not in self._node: self.adj[nn] = self.adjlist_inner_dict_factory() newdict = attr.copy() newdict.update(newdict) attr_dict = self._node[nn] = self.node_attr_dict_factory() attr_dict.update(newdict) else: olddict = self._node[nn] olddict.update(attr) olddict.update(ndict) def add_edges_from(self, ebunch_to_add, **attr): for e in ebunch_to_add: ne = len(e) if ne == 3: u, v, dd = e elif ne == 2: u, v = e dd = {} else: raise NetworkXError("Egde tuple %s must be a 2-tuple or 3tuple"%(e,)) if u not in self._node: self._adj[u] = self.adjlist_inner_dict_factory() self._node[u] = self.node_attr_dict_factory() if v not in self._node: self._adj[v] = self.adjlist_inner_dict_factory() self._node[v] = self.node_attr_dict_factory() datadict = self._adj[u].get(v, self.edge_attr_dict_factory()) datadict.update(attr) datadict.update(dd) self._adj[u][v] = datadict self._adj[v][u] = datadict g = Graph() mylist = tuple([(1,2), (2,6), (2,3), (3,4), (3,5)]) g.add_edges_from(mylist) h = plt.draw(g)
0.369543
0.19235
from collections import namedtuple import logging import re import mock import socket import sys from calico.felix.config import Config, ConfigException if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest # Logger log = logging.getLogger(__name__) class TestConfig(unittest.TestCase): def setUp(self): super(TestConfig, self).setUp() self.ghbn_patch = mock.patch("socket.gethostbyname", autospec=True) self.m_gethostbyname = self.ghbn_patch.start() self.m_gethostbyname.side_effect = self.dummy_gethostbyname def dummy_gethostbyname(self, host): if host in ("localhost", "127.0.0.1"): return "127.0.0.1" elif re.match(r"\d+\.\d+\.\d+\.\d+", host): return host else: raise socket.gaierror("Dummy test error") def tearDown(self): self.ghbn_patch.stop() super(TestConfig, self).tearDown() def test_default_config(self): """ Test various ways of defaulting config. """ files = [ "felix_missing.cfg", # does not exist "felix_empty.cfg", # empty file "felix_empty_section.cfg", # file with empty section "felix_extra.cfg", # extra config is just logged ] for filename in files: with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/%s" % filename) host_dict = { "InterfacePrefix": "blah", "MetadataPort": 123 } global_dict = { "InterfacePrefix": "overridden", "MetadataAddr": "1.2.3.4" } with mock.patch('calico.common.complete_logging'): config.report_etcd_config(host_dict, global_dict) # Test defaulting. self.assertEqual(config.ETCD_ADDR, "localhost:4001") self.assertEqual(config.HOSTNAME, socket.gethostname()) self.assertEqual(config.IFACE_PREFIX, "blah") self.assertEqual(config.METADATA_PORT, 123) self.assertEqual(config.METADATA_IP, "1.2.3.4") def test_invalid_port(self): data = { "felix_invalid_port.cfg": "Invalid port in field", "felix_invalid_addr.cfg": "Invalid or unresolvable", "felix_invalid_both.cfg": "Invalid or unresolvable", "felix_invalid_format.cfg": "Invalid format for field" } for filename in data: log.debug("Test filename : %s", filename) with self.assertRaisesRegexp(ConfigException, data[filename]): config = Config("calico/felix/test/data/%s" % filename) def test_no_logfile(self): # Logging to file can be excluded by explicitly saying "none" - # but if in etcd config the file is still created. with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "InterfacePrefix": "blah", "LogFilePath": "None" } with mock.patch('calico.common.complete_logging'): config.report_etcd_config({}, cfg_dict) self.assertEqual(config.LOGFILE, None) config = Config("calico/felix/test/data/felix_nolog.cfg") cfg_dict = { "InterfacePrefix": "blah"} config.report_etcd_config({}, cfg_dict) self.assertEqual(config.LOGFILE, None) def test_no_metadata(self): # Metadata can be excluded by explicitly saying "none" with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "InterfacePrefix": "blah", "MetadataAddr": "NoNe", "MetadataPort": 123 } with mock.patch('calico.common.complete_logging'): config.report_etcd_config({}, cfg_dict) # Test defaulting. self.assertEqual(config.METADATA_IP, None) self.assertEqual(config.METADATA_PORT, None) def test_metadata_port_not_int(self): with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "InterfacePrefix": "blah", "MetadataAddr": "127.0.0.1", "MetadataPort": "bloop" } with self.assertRaisesRegexp(ConfigException, "Field was not integer.*MetadataPort"): config.report_etcd_config({}, cfg_dict) def test_metadata_port_not_valid_1(self): for i in (0, -1, 99999): log.debug("Test invalid metadata port %d", i) with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "InterfacePrefix": "blah", "MetadataAddr": "127.0.0.1", "MetadataPort": i } with self.assertRaisesRegexp(ConfigException, "Invalid field value.*MetadataPort"): config.report_etcd_config({}, cfg_dict) def test_bad_metadata_addr(self): with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "InterfacePrefix": "blah", "MetadataAddr": "bloop", "MetadataPort": "123" } with self.assertRaisesRegexp(ConfigException, "Invalid or unresolvable.*MetadataAddr"): config.report_etcd_config({}, cfg_dict) self.m_gethostbyname.assert_has_calls([mock.call("bloop")]) def test_bad_log_level(self): for field in ("LogSeverityFile", "LogSeverityScreen", "LogSeveritySys"): with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "LogInterfacePrefix": "blah", field: "bloop" } with self.assertRaisesRegexp(ConfigException, "Invalid log level.*%s" % field): config.report_etcd_config({}, cfg_dict) def test_blank_metadata_addr(self): with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "InterfacePrefix": "blah", "MetadataAddr": "", "MetadataPort": "123" } with self.assertRaisesRegexp(ConfigException, "Blank value.*MetadataAddr"): config.report_etcd_config({}, cfg_dict) def test_no_iface_prefix(self): with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = {} with self.assertRaisesRegexp(ConfigException, "Missing undefaulted value.*InterfacePrefix"): config.report_etcd_config({}, cfg_dict) def test_file_sections(self): """ Test various ways of defaulting config. """ files = [ "felix_section.cfg", # lots of sections ] for filename in files: with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/%s" % filename) # Test that read ignoring sections. self.assertEqual(config.ETCD_ADDR, "localhost:4001") self.assertEqual(config.HOSTNAME, socket.gethostname()) self.assertEqual(config.LOGFILE, "/log/nowhere.log") self.assertEqual(config.IFACE_PREFIX, "whatever") self.assertEqual(config.METADATA_PORT, 246) self.assertEqual(config.METADATA_IP, "1.2.3.4") def test_env_var_override(self): """ Test environment variables override config options, """ with mock.patch.dict("os.environ", {"FELIX_ETCDADDR": "9.9.9.9:1234", "FELIX_METADATAPORT": "999"}): with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_section.cfg") host_dict = { "InterfacePrefix": "blah", "StartupCleanupDelay": "42", "MetadataAddr": "4.3.2.1", "MetadataPort": "123" } global_dict = { "InterfacePrefix": "blah", "StartupCleanupDelay": "99", "MetadataAddr": "5.4.3.2", "MetadataPort": "123" } with mock.patch('calico.common.complete_logging'): config.report_etcd_config(host_dict, global_dict) self.assertEqual(config.ETCD_ADDR, "9.9.9.9:1234") self.assertEqual(config.HOSTNAME, socket.gethostname()) self.assertEqual(config.LOGFILE, "/log/nowhere.log") self.assertEqual(config.IFACE_PREFIX, "whatever") self.assertEqual(config.METADATA_PORT, 999) self.assertEqual(config.METADATA_IP, "1.2.3.4") self.assertEqual(config.STARTUP_CLEANUP_DELAY, 42) def test_ip_in_ip_enabled(self): test_values = [ ("true", True), ("t", True), ("True", True), ("1", True), (1, True), ("yes", True), ("y", True), ("false", False), ("f", False), ("False", False), ("0", False), (0, False), ("no", False), ("n", False), ] for value, expected in test_values: with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "InterfacePrefix": "blah", "IpInIpEnabled": value } config.report_etcd_config({}, cfg_dict) self.assertEqual(config.IP_IN_IP_ENABLED, expected, "%r was mis-interpreted as %r" % (value, config.IP_IN_IP_ENABLED)) def test_ip_in_ip_enabled_bad(self): with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "InterfacePrefix": "blah", "IpInIpEnabled": "blah" } with self.assertRaisesRegexp(ConfigException, "Field was not a valid Boolean" ".*IpInIpEnabled"): config.report_etcd_config({}, cfg_dict)
calico/felix/test/test_config.py
from collections import namedtuple import logging import re import mock import socket import sys from calico.felix.config import Config, ConfigException if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest # Logger log = logging.getLogger(__name__) class TestConfig(unittest.TestCase): def setUp(self): super(TestConfig, self).setUp() self.ghbn_patch = mock.patch("socket.gethostbyname", autospec=True) self.m_gethostbyname = self.ghbn_patch.start() self.m_gethostbyname.side_effect = self.dummy_gethostbyname def dummy_gethostbyname(self, host): if host in ("localhost", "127.0.0.1"): return "127.0.0.1" elif re.match(r"\d+\.\d+\.\d+\.\d+", host): return host else: raise socket.gaierror("Dummy test error") def tearDown(self): self.ghbn_patch.stop() super(TestConfig, self).tearDown() def test_default_config(self): """ Test various ways of defaulting config. """ files = [ "felix_missing.cfg", # does not exist "felix_empty.cfg", # empty file "felix_empty_section.cfg", # file with empty section "felix_extra.cfg", # extra config is just logged ] for filename in files: with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/%s" % filename) host_dict = { "InterfacePrefix": "blah", "MetadataPort": 123 } global_dict = { "InterfacePrefix": "overridden", "MetadataAddr": "1.2.3.4" } with mock.patch('calico.common.complete_logging'): config.report_etcd_config(host_dict, global_dict) # Test defaulting. self.assertEqual(config.ETCD_ADDR, "localhost:4001") self.assertEqual(config.HOSTNAME, socket.gethostname()) self.assertEqual(config.IFACE_PREFIX, "blah") self.assertEqual(config.METADATA_PORT, 123) self.assertEqual(config.METADATA_IP, "1.2.3.4") def test_invalid_port(self): data = { "felix_invalid_port.cfg": "Invalid port in field", "felix_invalid_addr.cfg": "Invalid or unresolvable", "felix_invalid_both.cfg": "Invalid or unresolvable", "felix_invalid_format.cfg": "Invalid format for field" } for filename in data: log.debug("Test filename : %s", filename) with self.assertRaisesRegexp(ConfigException, data[filename]): config = Config("calico/felix/test/data/%s" % filename) def test_no_logfile(self): # Logging to file can be excluded by explicitly saying "none" - # but if in etcd config the file is still created. with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "InterfacePrefix": "blah", "LogFilePath": "None" } with mock.patch('calico.common.complete_logging'): config.report_etcd_config({}, cfg_dict) self.assertEqual(config.LOGFILE, None) config = Config("calico/felix/test/data/felix_nolog.cfg") cfg_dict = { "InterfacePrefix": "blah"} config.report_etcd_config({}, cfg_dict) self.assertEqual(config.LOGFILE, None) def test_no_metadata(self): # Metadata can be excluded by explicitly saying "none" with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "InterfacePrefix": "blah", "MetadataAddr": "NoNe", "MetadataPort": 123 } with mock.patch('calico.common.complete_logging'): config.report_etcd_config({}, cfg_dict) # Test defaulting. self.assertEqual(config.METADATA_IP, None) self.assertEqual(config.METADATA_PORT, None) def test_metadata_port_not_int(self): with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "InterfacePrefix": "blah", "MetadataAddr": "127.0.0.1", "MetadataPort": "bloop" } with self.assertRaisesRegexp(ConfigException, "Field was not integer.*MetadataPort"): config.report_etcd_config({}, cfg_dict) def test_metadata_port_not_valid_1(self): for i in (0, -1, 99999): log.debug("Test invalid metadata port %d", i) with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "InterfacePrefix": "blah", "MetadataAddr": "127.0.0.1", "MetadataPort": i } with self.assertRaisesRegexp(ConfigException, "Invalid field value.*MetadataPort"): config.report_etcd_config({}, cfg_dict) def test_bad_metadata_addr(self): with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "InterfacePrefix": "blah", "MetadataAddr": "bloop", "MetadataPort": "123" } with self.assertRaisesRegexp(ConfigException, "Invalid or unresolvable.*MetadataAddr"): config.report_etcd_config({}, cfg_dict) self.m_gethostbyname.assert_has_calls([mock.call("bloop")]) def test_bad_log_level(self): for field in ("LogSeverityFile", "LogSeverityScreen", "LogSeveritySys"): with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "LogInterfacePrefix": "blah", field: "bloop" } with self.assertRaisesRegexp(ConfigException, "Invalid log level.*%s" % field): config.report_etcd_config({}, cfg_dict) def test_blank_metadata_addr(self): with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "InterfacePrefix": "blah", "MetadataAddr": "", "MetadataPort": "123" } with self.assertRaisesRegexp(ConfigException, "Blank value.*MetadataAddr"): config.report_etcd_config({}, cfg_dict) def test_no_iface_prefix(self): with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = {} with self.assertRaisesRegexp(ConfigException, "Missing undefaulted value.*InterfacePrefix"): config.report_etcd_config({}, cfg_dict) def test_file_sections(self): """ Test various ways of defaulting config. """ files = [ "felix_section.cfg", # lots of sections ] for filename in files: with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/%s" % filename) # Test that read ignoring sections. self.assertEqual(config.ETCD_ADDR, "localhost:4001") self.assertEqual(config.HOSTNAME, socket.gethostname()) self.assertEqual(config.LOGFILE, "/log/nowhere.log") self.assertEqual(config.IFACE_PREFIX, "whatever") self.assertEqual(config.METADATA_PORT, 246) self.assertEqual(config.METADATA_IP, "1.2.3.4") def test_env_var_override(self): """ Test environment variables override config options, """ with mock.patch.dict("os.environ", {"FELIX_ETCDADDR": "9.9.9.9:1234", "FELIX_METADATAPORT": "999"}): with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_section.cfg") host_dict = { "InterfacePrefix": "blah", "StartupCleanupDelay": "42", "MetadataAddr": "4.3.2.1", "MetadataPort": "123" } global_dict = { "InterfacePrefix": "blah", "StartupCleanupDelay": "99", "MetadataAddr": "5.4.3.2", "MetadataPort": "123" } with mock.patch('calico.common.complete_logging'): config.report_etcd_config(host_dict, global_dict) self.assertEqual(config.ETCD_ADDR, "9.9.9.9:1234") self.assertEqual(config.HOSTNAME, socket.gethostname()) self.assertEqual(config.LOGFILE, "/log/nowhere.log") self.assertEqual(config.IFACE_PREFIX, "whatever") self.assertEqual(config.METADATA_PORT, 999) self.assertEqual(config.METADATA_IP, "1.2.3.4") self.assertEqual(config.STARTUP_CLEANUP_DELAY, 42) def test_ip_in_ip_enabled(self): test_values = [ ("true", True), ("t", True), ("True", True), ("1", True), (1, True), ("yes", True), ("y", True), ("false", False), ("f", False), ("False", False), ("0", False), (0, False), ("no", False), ("n", False), ] for value, expected in test_values: with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "InterfacePrefix": "blah", "IpInIpEnabled": value } config.report_etcd_config({}, cfg_dict) self.assertEqual(config.IP_IN_IP_ENABLED, expected, "%r was mis-interpreted as %r" % (value, config.IP_IN_IP_ENABLED)) def test_ip_in_ip_enabled_bad(self): with mock.patch('calico.common.complete_logging'): config = Config("calico/felix/test/data/felix_missing.cfg") cfg_dict = { "InterfacePrefix": "blah", "IpInIpEnabled": "blah" } with self.assertRaisesRegexp(ConfigException, "Field was not a valid Boolean" ".*IpInIpEnabled"): config.report_etcd_config({}, cfg_dict)
0.445288
0.179315
from ovim.log import logger from urllib import request import json import tarfile import tempfile import os class UbuntuRunner: homedir = os.path.abspath(os.getenv('HOME')) local_bin = os.path.join(homedir, '.local', 'bin') @classmethod def check_env(cls): if os.system("curl --version"): raise RuntimeError('curl is not exist.') @classmethod def install_fzf(cls): with os.popen("uname -sm") as f: arch = f.read() arch = arch.strip() logger.info(arch) if arch.endswith("64"): arch = "linux_amd64" elif "armv5" in arch: arch = "linux_armv5" elif "armv6" in arch: arch = "linux_armv6" elif "armv7" in arch: arch = "linux_amdv7" elif "armv8" in arch: arch = "linux_amd64" elif "aarch64" in arch: arch = "linux_amd64" fzf_release_url = "https://api.github.com/repos/junegunn/fzf/releases/latest" resp = request.urlopen(fzf_release_url) j = resp.read().decode() j = json.loads(j) latest_tag_name = j['tag_name'] file_url = "https://github.com/junegunn/fzf/releases/download/{}/fzf-{}-{}.tar.gz".format( latest_tag_name, latest_tag_name, arch) logger.info("download fzf...") resp = request.urlopen(file_url) temp_file = tempfile.TemporaryFile() temp_file.write(resp.read()) resp.close() temp_file.seek(0) tfile = tarfile.open(fileobj=temp_file, mode='r') os.makedirs(cls.local_bin, exist_ok=True) tfile.extract('fzf', cls.local_bin) logger.info("fzf extract to {}".format(cls.local_bin)) tfile.close() temp_file.close() @classmethod def install_ctags(cls): with os.popen("apt list --installed universal-ctags") as f: r = f.read() logger.info(r) if "universal-ctags" not in r: os.system("apt-get install universal-ctags -y") @classmethod def run(cls): try: logger.info("ubuntu runner start.") cls.install_ctags() cls.install_fzf() except Exception as e: logger.error("UbuntuRunner occured error {}".format(e))
ovim/python3/ovim/platform/ubuntu.py
from ovim.log import logger from urllib import request import json import tarfile import tempfile import os class UbuntuRunner: homedir = os.path.abspath(os.getenv('HOME')) local_bin = os.path.join(homedir, '.local', 'bin') @classmethod def check_env(cls): if os.system("curl --version"): raise RuntimeError('curl is not exist.') @classmethod def install_fzf(cls): with os.popen("uname -sm") as f: arch = f.read() arch = arch.strip() logger.info(arch) if arch.endswith("64"): arch = "linux_amd64" elif "armv5" in arch: arch = "linux_armv5" elif "armv6" in arch: arch = "linux_armv6" elif "armv7" in arch: arch = "linux_amdv7" elif "armv8" in arch: arch = "linux_amd64" elif "aarch64" in arch: arch = "linux_amd64" fzf_release_url = "https://api.github.com/repos/junegunn/fzf/releases/latest" resp = request.urlopen(fzf_release_url) j = resp.read().decode() j = json.loads(j) latest_tag_name = j['tag_name'] file_url = "https://github.com/junegunn/fzf/releases/download/{}/fzf-{}-{}.tar.gz".format( latest_tag_name, latest_tag_name, arch) logger.info("download fzf...") resp = request.urlopen(file_url) temp_file = tempfile.TemporaryFile() temp_file.write(resp.read()) resp.close() temp_file.seek(0) tfile = tarfile.open(fileobj=temp_file, mode='r') os.makedirs(cls.local_bin, exist_ok=True) tfile.extract('fzf', cls.local_bin) logger.info("fzf extract to {}".format(cls.local_bin)) tfile.close() temp_file.close() @classmethod def install_ctags(cls): with os.popen("apt list --installed universal-ctags") as f: r = f.read() logger.info(r) if "universal-ctags" not in r: os.system("apt-get install universal-ctags -y") @classmethod def run(cls): try: logger.info("ubuntu runner start.") cls.install_ctags() cls.install_fzf() except Exception as e: logger.error("UbuntuRunner occured error {}".format(e))
0.30054
0.04807
import numpy as np import os import subprocess import shutil import multiprocessing import sys import copy from collections import OrderedDict from pyfoamsetup.coreLibrary import * import pyfoamsetup.coreLibrary.CaseSetup as CaseSetup class PropellerSimulation(CaseSetup.CaseSetup): def __init__(self, runName, c, D, Re, J, fluid='air', rotationAxis='right', pushPull='push'): # Default environment settings if fluid == 'air': rho = 1.226 nu = 1.45e-05 elif fluid == 'water': rho = 1000 nu = 1.19e-6 self.D = D self.r = D/2 self.J = J self.n = Re*nu/(np.sqrt((J*D)**2 + (0.7*self.r*2*np.pi)**2)*c) self.omega = 2*np.pi*self.n self.U_r = 0.7*(D/2)*self.omega U = self.J*self.n*self.D A = np.pi*(D/2)**2 self.rotationAxis = rotationAxis patchList = ['propeller'] # Call init from base class self.homePath = os.path.dirname(os.path.realpath(__file__)) super().__init__(runName, patchList, c, U, A, nu, rho, 'PropellerSimulation') # Reset reynolds number from input self.Re = Re # Time step settings self.maxDegreesPrTimeStep = 2 self.numberOfRevolutions = 4 self.baseSize = 1 self.domainWake = 6 self.domainFront = 4 self.domainWidth = 4 self.rotatingCylinderRadius = 0.75 self.rotatingCylinderLength = 1 self.setMeshSettings() self.nrLayers = 0 self.setSolver('pimpleDyMFoam') self.adjustTimeStep = False def setDefaultCellLengths(self): super().setDefaultCellLengths() self.maxBaseSize = 0.1*self.D # Ensure that the geometry is captured! self.maxSmallestSize = 0.01*self.L self.viscousLength = 0.02*self.D def writeBlockMesh(self): blockMesh = BlockMesh.Dict() # Calculate minimum values for domain size xBack = self.domainWake*self.D xFront = -self.domainFront*self.D yRight = self.domainWidth*self.D yLeft = -self.domainWidth*self.D zHeight = self.domainWidth*self.D zDepth = -self.domainWidth*self.D # Calculate number of cells in each direction x_nrCells = np.ceil((xBack - xFront)/self.baseSize) y_nrCells = np.ceil((yRight - yLeft)/self.baseSize) z_nrCells = np.ceil((zHeight - zDepth)/self.baseSize) # Readjust domain size to fit nr cells xLength = self.baseSize*x_nrCells yLength = self.baseSize*y_nrCells zLength = self.baseSize*z_nrCells wakeFraction = (self.domainWake/(self.domainWake + self.domainFront)) frontFraction = (self.domainFront/(self.domainWake + self.domainFront)) xFront = -xLength*frontFraction xBack = xLength*wakeFraction yRight = yLength/2 yLeft = -yLength/2 # Add data to blockmesh and write blockMesh.addVertex([xFront, yLeft, zDepth]) blockMesh.addVertex([xBack, yLeft, zDepth]) blockMesh.addVertex([xBack, yRight, zDepth]) blockMesh.addVertex([xFront, yRight, zDepth]) blockMesh.addVertex([xFront, yLeft, zHeight]) blockMesh.addVertex([xBack, yLeft, zHeight]) blockMesh.addVertex([xBack, yRight, zHeight]) blockMesh.addVertex([xFront, yRight, zHeight]) blockMesh.addBlock([x_nrCells, y_nrCells, z_nrCells]) blockMesh.addBoundary('inlet', 'patch', [[0, 4, 7, 3],[3, 2, 6, 7], [4, 5, 6, 7], [0, 1, 5, 4], [0, 3, 2, 1]]) blockMesh.addBoundary('outlet', 'patch', [[2, 6, 5, 1]]) blockMesh.write(self.systemFolder) def writeMesh(self): self.calculateBaseSize() self.writeBlockMesh() # Add geometry self.snappyDict.addGeometry('propeller.obj', 'triSurfaceMesh', {'name':'propeller'}) self.snappyDict.addRefinementSurface('propeller', self.maxRefinementLevel-1, self.maxRefinementLevel, self.nrLayers) self.snappyDict.addFeature('propeller.eMesh', self.maxRefinementLevel) self.snappyDict.addGeometry('propellerStem.obj', 'triSurfaceMesh', {'name':'propellerStem'}) self.snappyDict.addRefinementSurface('propellerStem', self.maxRefinementLevel-3, self.maxRefinementLevel-3, 0) # Add cylinders name = 'rotatingCylinder' length = self.rotatingCylinderLength*self.D radius = self.rotatingCylinderRadius*self.D x0 = 0 level = self.maxRefinementLevel-2 point1String = '({:.6f} {:.6f} {:.6f})'.format(x0, 0, 0) point2String = '({:.6f} {:.6f} {:.6f})'.format(x0+length, 0, 0) radiusString = '{:.6f}'.format(radius) extraArgumentDict = OrderedDict() extraArgumentDict['faceType'] = 'boundary' extraArgumentDict['cellZone'] = name extraArgumentDict['faceZone'] = name extraArgumentDict['cellZoneInside'] = 'inside' self.snappyDict.addGeometry(name, 'searchableCylinder', {'point1':point1String, 'point2':point2String, 'radius':radiusString}) self.snappyDict.addRefinementSurface(name, level, level, 0, extraArgumentDict=extraArgumentDict) self.snappyDict.addRefinementRegion(name, 'inside', np.array([1, level])) # Set up layer settings self.snappyDict.addLayersControls['relativeSizes'] = 'false' self.snappyDict.addLayersControls['finalLayerThickness'] = self.t_final self.snappyDict.addLayersControls['minThickness'] = 0.5*self.t_final self.snappyDict.addLayersControls['expansionRatio'] = self.layerExpansion self.snappyDict.castellatedMeshControls['locationInMesh'] = '({:.3f} {:.3f} {:.3f})'.format(-1.03*self.D, 1.04*self.D, 1.3*self.D) self.snappyDict.castellatedMeshControls['nCellsBetweenLevels'] = int(self.nCellsBetweenLevels) self.snappyDict.write(self.systemFolder) self.snappyDict.writeSurfaceFeatureExtractDict(self.systemFolder, 'propeller.obj') def writeCaseFiles(self): # Recalculate time stepping self.deltaT = np.round(self.maxDegreesPrTimeStep/(self.n*360), decimals=8) self.maxDeltaT = np.round(self.maxDegreesPrTimeStep/(self.n*360), decimals=8) self.endTime = np.round(self.numberOfRevolutions/self.n, decimals=8) self.writeInterval = np.round(self.endTime/10, decimals = 8) super().writeCaseFiles() FileHandling.changeLine(self.constantFolder+'dynamicMeshDict', 'omega', '\t\tomega {:.6f};'.format(self.omega)) if self.rotationAxis == 'left': FileHandling.changeLine(self.constantFolder+'dynamicMeshDict', 'axis', '\t\taxis (-1 0 0);') self.writePropInfo() createPatchDict = createPatch.Dict() createPatchDict.addPatch('AMI1', 'rotatingCylinder', 'AMI2') createPatchDict.addPatch('AMI2', 'rotatingCylinder_slave', 'AMI1') createPatchDict.write(self.systemFolder) def writeScripts(self): # ------ Mesh -------------------- f = open(self.runFolder+'/mesh.sh', 'w') f.write('#!/bin/bash\n\n') if self.snappyDict.snapControls['explicitFeatureSnap'] == 'true': f.write('surfaceFeatureExtract\n') f.write('blockMesh\n') f.write('mv system/decomposeParDict system/decomposeParDict.sim\n') f.write('mv system/decomposeParDict.mesh system/decomposeParDict\n') f.write('decomposePar\n') f.write('mpirun -np {:.0f} snappyHexMesh -overwrite -parallel\n'.format(self.nCPUs_mesh)) f.write('reconstructParMesh -constant\n') f.write('rm -fr processor*\n') f.write('createPatch -overwrite\n') f.write('mv system/decomposeParDict system/decomposeParDict.mesh\n') f.write('mv system/decomposeParDict.sim system/decomposeParDict\n') f.write('renumberMesh -overwrite\n') if len(self.topoSetList) > 0: f.write('topoSet\n') f.close() # ------- Simulation --------------------- f = open(self.runFolder + '/runSim.sh', 'w') f.write('#!/bin/bash\n\n') f.write('decomposePar\n') if self.vilje: f.write('mpiexec ' + self.solver + ' -parallel\n') else: f.write('mpirun -np {:.0f} '.format(self.nCPUs) + self.solver + ' -parallel\n') f.write('reconstructPar\n') f.write('rm -fr processor*\n') f.close() def addViscousWake(self, x0, y0, z0, lengthFactor = 4, radiusFactor = 1.0, expansion = 2): # Ensure that mesh size is calculated self.turbulence = Turbulence.Properties(self.U, self.L, self.nu, self.turbulenceModel, self.turbulenceType) self.turbulence.calculateInitialValues() self.calculateBaseSize() maxLevel = int(np.floor(np.log(self.baseSize/self.viscousLength)/np.log(2))) print(maxLevel) radius0 = radiusFactor*self.D length0 = lengthFactor*self.D level = maxLevel for i in range(maxLevel): cellLength = self.baseSize/(2**level+1) name = 'viscWake{:.0f}'.format(i+1) length = length0*expansion**(i) radius = radius0*expansion**(i) point1String = '({:.6f} {:.6f} {:.6f})'.format(x0, y0, z0) point2String = '({:.6f} {:.6f} {:.6f})'.format(x0+length, y0, z0) radiusString = '{:.6f}'.format(radius) self.snappyDict.addGeometry(name, 'searchableCylinder', {'point1':point1String, 'point2':point2String, 'radius':radiusString}) self.snappyDict.addRefinementRegion(name, 'inside', np.array([1, level])) level -= 1 def writePropInfo(self): f = open(self.runFolder + 'propInfo.txt', 'w') f.write('D {:.6f}\n'.format(self.D)) f.write('c {:.6f}\n'.format(self.L)) f.write('Re {:.6f}\n'.format(self.Re)) f.write('J {:.6f}\n'.format(self.J)) f.write('n {:.6f}\n'.format(self.n)) f.write('omega {:.6f}\n'.format(self.omega)) f.write('rho {:.6f}\n'.format(self.rho)) f.write('U {:.6f}\n'.format(self.U)) f.write('U_R {:.6f}\n'.format(self.U_r)) f.close() class ActuatorDisk(CaseSetup): def __init__(self, runName, U, D, CT, CQ=0.0, rh_factor=0.1, alpha=0, fluid='air', meshSetting='medium', vilje=False): # Default environment settings if fluid == 'air': rho = 1.226 nu = 1.45e-05 elif fluid == 'water': rho = 1000 nu = 1.19e-6 self.D = D self.r = D/2 self.r_h = rh_factor*self.r self.CT = CT self.CQ = CQ self.alpha = alpha A = np.pi*self.r**2 patchList = [] # Call init from base class super().__init__(runName, patchList, 0.5*self.r, U, A, nu, rho, vilje) self.Thrust = 0.5*self.A*self.CT*self.U**2 self.Torque = 0.5*self.A*self.CQ*self.U**2*self.D # Essential folder paths self.foamPath = os.environ['FOAM_RUN'] self.mainRunFolder = self.foamPath + '/PropellerSimulation' self.homePath = os.path.dirname(os.path.realpath(__file__)) self.setFolderPaths() self.maxBaseSize = 0.5*self.D self.maxSmallestSize = 0.01*self.D self.actuatorDiskLength = 0.05*self.D self.viscousLength = 0.02*self.D # Default mesh settings if meshSetting == 'fine': self.maxBaseSize /= np.sqrt(2) self.maxSmallestSize /= np.sqrt(2) self.viscousLength /= np.sqrt(2) elif meshSetting == 'veryFine': self.maxBaseSize /= 2 self.maxSmallestSize /= 2 self.viscousLength /= 2 elif meshSetting == 'coarse': self.maxBaseSize *= np.sqrt(2) self.maxSmallestSize *= np.sqrt(2) self.viscousLength *= np.sqrt(2) elif meshSetting == 'veryCoarse': self.maxBaseSize *= 2 self.maxSmallestSize *= 2 self.viscousLength *= 2 self.baseSize = 1 self.domainWake = 10 self.domainFront = 5 self.domainWidth = 5 self.setMeshSettings() self.setSolver('simpleFoam') def calculateBaseSize(self): self.smallestSize = self.maxSmallestSize self.baseSize = self.smallestSize*2**(self.maxRefinementLevel) while self.baseSize > self.maxBaseSize and self.maxRefinementLevel > self.minRefinementLevel: self.maxRefinementLevel -= 1 self.baseSize = self.smallestSize*2**(self.maxRefinementLevel) def writeBlockMesh(self): blockMesh = BlockMesh.Dict() # Calculate minimum values for domain size xBack = self.domainWake*self.D xFront = -self.domainFront*self.D yRight = self.domainWidth*self.D yLeft = -self.domainWidth*self.D zHeight = self.domainWidth*self.D zDepth = -self.domainWidth*self.D # Calculate number of cells in each direction x_nrCells = np.ceil((xBack - xFront)/self.baseSize) y_nrCells = np.ceil((yRight - yLeft)/self.baseSize) z_nrCells = np.ceil((zHeight - zDepth)/self.baseSize) # Readjust domain size to fit nr cells xLength = self.baseSize*x_nrCells yLength = self.baseSize*y_nrCells zLength = self.baseSize*z_nrCells wakeFraction = (self.domainWake/(self.domainWake + self.domainFront)) frontFraction = (self.domainFront/(self.domainWake + self.domainFront)) xFront = -xLength*frontFraction xBack = xLength*wakeFraction yRight = yLength/2 yLeft = -yLength/2 # Add data to blockmesh and write blockMesh.addVertex([xFront, yLeft, zDepth]) blockMesh.addVertex([xBack, yLeft, zDepth]) blockMesh.addVertex([xBack, yRight, zDepth]) blockMesh.addVertex([xFront, yRight, zDepth]) blockMesh.addVertex([xFront, yLeft, zHeight]) blockMesh.addVertex([xBack, yLeft, zHeight]) blockMesh.addVertex([xBack, yRight, zHeight]) blockMesh.addVertex([xFront, yRight, zHeight]) blockMesh.addBlock([x_nrCells, y_nrCells, z_nrCells]) blockMesh.addBoundary('inlet', 'patch', [[0, 4, 7, 3],[3, 2, 6, 7], [4, 5, 6, 7], [0, 1, 5, 4], [0, 3, 2, 1]]) blockMesh.addBoundary('outlet', 'patch', [[2, 6, 5, 1]]) blockMesh.write(self.systemFolder) def writeMesh(self): self.calculateBaseSize() self.writeBlockMesh() name = 'actuatorDisk' p1 = np.array([0, 0, 0]) r = self.r diskDir = np.array([np.cos(self.alpha), -np.sin(self.alpha), 0]) diskThickness = self.actuatorDiskLength self.addPropellerActuatorDisk(name, p1, r, diskDir, diskThickness, self.Thrust, self.Torque, self.smallestSize) self.snappyDict.write(self.systemFolder) def writeCaseFiles(self): super().writeCaseFiles() def addViscousWake(self, x0, y0, z0, lengthFactor = 4, radiusFactor = 1.0, expansion = 2): # Ensure that mesh size is calculated self.calculateBaseSize() maxLevel = int(np.floor(np.log(self.baseSize/self.viscousLength)/np.log(2))) radius0 = radiusFactor*self.D length0 = lengthFactor*self.D level = maxLevel for i in range(maxLevel): cellLength = self.baseSize/(2**level+1) name = 'viscWake{:.0f}'.format(i+1) length = length0*expansion**(i) radius = radius0*expansion**(i) point1String = '({:.6f} {:.6f} {:.6f})'.format(x0, y0, z0) point2String = '({:.6f} {:.6f} {:.6f})'.format(x0+length, y0, z0) radiusString = '{:.6f}'.format(radius) self.snappyDict.addGeometry(name, 'searchableCylinder', {'point1':point1String, 'point2':point2String, 'radius':radiusString}) self.snappyDict.addRefinementRegion(name, 'inside', np.array([1, level])) level -= 1 def writeScripts(self): # ------ Mesh -------------------- f = open(self.runFolder+'/mesh.sh', 'w') f.write('#!/bin/bash\n\n') f.write('blockMesh\n') f.write('mv system/decomposeParDict system/decomposeParDict.sim\n') f.write('mv system/decomposeParDict.mesh system/decomposeParDict\n') f.write('decomposePar\n') f.write('mpirun -np {:.0f} snappyHexMesh -overwrite -parallel\n'.format(self.nCPUs_mesh)) f.write('reconstructParMesh -constant\n') f.write('rm -fr processor*\n') f.write('mv system/decomposeParDict system/decomposeParDict.mesh\n') f.write('mv system/decomposeParDict.sim system/decomposeParDict\n') f.write('createPatch -overwrite\n') if len(self.topoSetList) > 0: f.write('topoSet\n') f.close() # ------- Simulation --------------------- f = open(self.runFolder + '/runSim.sh', 'w') f.write('#!/bin/bash\n\n') f.write('decomposePar\n') if self.vilje: f.write('mpiexec ' + self.solver + ' -parallel\n') else: f.write('mpirun -np {:.0f} '.format(self.nCPUs) + self.solver + ' -parallel\n') f.write('reconstructPar\n') f.write('rm -fr processor*\n') f.close() def writeRunScripts(caseNameList, propSim, folderName=''): # Write run script f = open('run.sh', 'w') f.write('#!/bin/bash\n\n') f.write('cd $FOAM_RUN/PropellerSimulation\n\n') for i in range(len(caseNameList)): f.write('cd {0}\n'.format(caseNameList[i])) f.write('bash mesh.sh\n') f.write('bash runSim.sh\n') f.write('cd $FOAM_RUN/TowingTank\n\n') f.close()
pyfoamsetup/PropellerSimulation/PropellerSimulation.py
import numpy as np import os import subprocess import shutil import multiprocessing import sys import copy from collections import OrderedDict from pyfoamsetup.coreLibrary import * import pyfoamsetup.coreLibrary.CaseSetup as CaseSetup class PropellerSimulation(CaseSetup.CaseSetup): def __init__(self, runName, c, D, Re, J, fluid='air', rotationAxis='right', pushPull='push'): # Default environment settings if fluid == 'air': rho = 1.226 nu = 1.45e-05 elif fluid == 'water': rho = 1000 nu = 1.19e-6 self.D = D self.r = D/2 self.J = J self.n = Re*nu/(np.sqrt((J*D)**2 + (0.7*self.r*2*np.pi)**2)*c) self.omega = 2*np.pi*self.n self.U_r = 0.7*(D/2)*self.omega U = self.J*self.n*self.D A = np.pi*(D/2)**2 self.rotationAxis = rotationAxis patchList = ['propeller'] # Call init from base class self.homePath = os.path.dirname(os.path.realpath(__file__)) super().__init__(runName, patchList, c, U, A, nu, rho, 'PropellerSimulation') # Reset reynolds number from input self.Re = Re # Time step settings self.maxDegreesPrTimeStep = 2 self.numberOfRevolutions = 4 self.baseSize = 1 self.domainWake = 6 self.domainFront = 4 self.domainWidth = 4 self.rotatingCylinderRadius = 0.75 self.rotatingCylinderLength = 1 self.setMeshSettings() self.nrLayers = 0 self.setSolver('pimpleDyMFoam') self.adjustTimeStep = False def setDefaultCellLengths(self): super().setDefaultCellLengths() self.maxBaseSize = 0.1*self.D # Ensure that the geometry is captured! self.maxSmallestSize = 0.01*self.L self.viscousLength = 0.02*self.D def writeBlockMesh(self): blockMesh = BlockMesh.Dict() # Calculate minimum values for domain size xBack = self.domainWake*self.D xFront = -self.domainFront*self.D yRight = self.domainWidth*self.D yLeft = -self.domainWidth*self.D zHeight = self.domainWidth*self.D zDepth = -self.domainWidth*self.D # Calculate number of cells in each direction x_nrCells = np.ceil((xBack - xFront)/self.baseSize) y_nrCells = np.ceil((yRight - yLeft)/self.baseSize) z_nrCells = np.ceil((zHeight - zDepth)/self.baseSize) # Readjust domain size to fit nr cells xLength = self.baseSize*x_nrCells yLength = self.baseSize*y_nrCells zLength = self.baseSize*z_nrCells wakeFraction = (self.domainWake/(self.domainWake + self.domainFront)) frontFraction = (self.domainFront/(self.domainWake + self.domainFront)) xFront = -xLength*frontFraction xBack = xLength*wakeFraction yRight = yLength/2 yLeft = -yLength/2 # Add data to blockmesh and write blockMesh.addVertex([xFront, yLeft, zDepth]) blockMesh.addVertex([xBack, yLeft, zDepth]) blockMesh.addVertex([xBack, yRight, zDepth]) blockMesh.addVertex([xFront, yRight, zDepth]) blockMesh.addVertex([xFront, yLeft, zHeight]) blockMesh.addVertex([xBack, yLeft, zHeight]) blockMesh.addVertex([xBack, yRight, zHeight]) blockMesh.addVertex([xFront, yRight, zHeight]) blockMesh.addBlock([x_nrCells, y_nrCells, z_nrCells]) blockMesh.addBoundary('inlet', 'patch', [[0, 4, 7, 3],[3, 2, 6, 7], [4, 5, 6, 7], [0, 1, 5, 4], [0, 3, 2, 1]]) blockMesh.addBoundary('outlet', 'patch', [[2, 6, 5, 1]]) blockMesh.write(self.systemFolder) def writeMesh(self): self.calculateBaseSize() self.writeBlockMesh() # Add geometry self.snappyDict.addGeometry('propeller.obj', 'triSurfaceMesh', {'name':'propeller'}) self.snappyDict.addRefinementSurface('propeller', self.maxRefinementLevel-1, self.maxRefinementLevel, self.nrLayers) self.snappyDict.addFeature('propeller.eMesh', self.maxRefinementLevel) self.snappyDict.addGeometry('propellerStem.obj', 'triSurfaceMesh', {'name':'propellerStem'}) self.snappyDict.addRefinementSurface('propellerStem', self.maxRefinementLevel-3, self.maxRefinementLevel-3, 0) # Add cylinders name = 'rotatingCylinder' length = self.rotatingCylinderLength*self.D radius = self.rotatingCylinderRadius*self.D x0 = 0 level = self.maxRefinementLevel-2 point1String = '({:.6f} {:.6f} {:.6f})'.format(x0, 0, 0) point2String = '({:.6f} {:.6f} {:.6f})'.format(x0+length, 0, 0) radiusString = '{:.6f}'.format(radius) extraArgumentDict = OrderedDict() extraArgumentDict['faceType'] = 'boundary' extraArgumentDict['cellZone'] = name extraArgumentDict['faceZone'] = name extraArgumentDict['cellZoneInside'] = 'inside' self.snappyDict.addGeometry(name, 'searchableCylinder', {'point1':point1String, 'point2':point2String, 'radius':radiusString}) self.snappyDict.addRefinementSurface(name, level, level, 0, extraArgumentDict=extraArgumentDict) self.snappyDict.addRefinementRegion(name, 'inside', np.array([1, level])) # Set up layer settings self.snappyDict.addLayersControls['relativeSizes'] = 'false' self.snappyDict.addLayersControls['finalLayerThickness'] = self.t_final self.snappyDict.addLayersControls['minThickness'] = 0.5*self.t_final self.snappyDict.addLayersControls['expansionRatio'] = self.layerExpansion self.snappyDict.castellatedMeshControls['locationInMesh'] = '({:.3f} {:.3f} {:.3f})'.format(-1.03*self.D, 1.04*self.D, 1.3*self.D) self.snappyDict.castellatedMeshControls['nCellsBetweenLevels'] = int(self.nCellsBetweenLevels) self.snappyDict.write(self.systemFolder) self.snappyDict.writeSurfaceFeatureExtractDict(self.systemFolder, 'propeller.obj') def writeCaseFiles(self): # Recalculate time stepping self.deltaT = np.round(self.maxDegreesPrTimeStep/(self.n*360), decimals=8) self.maxDeltaT = np.round(self.maxDegreesPrTimeStep/(self.n*360), decimals=8) self.endTime = np.round(self.numberOfRevolutions/self.n, decimals=8) self.writeInterval = np.round(self.endTime/10, decimals = 8) super().writeCaseFiles() FileHandling.changeLine(self.constantFolder+'dynamicMeshDict', 'omega', '\t\tomega {:.6f};'.format(self.omega)) if self.rotationAxis == 'left': FileHandling.changeLine(self.constantFolder+'dynamicMeshDict', 'axis', '\t\taxis (-1 0 0);') self.writePropInfo() createPatchDict = createPatch.Dict() createPatchDict.addPatch('AMI1', 'rotatingCylinder', 'AMI2') createPatchDict.addPatch('AMI2', 'rotatingCylinder_slave', 'AMI1') createPatchDict.write(self.systemFolder) def writeScripts(self): # ------ Mesh -------------------- f = open(self.runFolder+'/mesh.sh', 'w') f.write('#!/bin/bash\n\n') if self.snappyDict.snapControls['explicitFeatureSnap'] == 'true': f.write('surfaceFeatureExtract\n') f.write('blockMesh\n') f.write('mv system/decomposeParDict system/decomposeParDict.sim\n') f.write('mv system/decomposeParDict.mesh system/decomposeParDict\n') f.write('decomposePar\n') f.write('mpirun -np {:.0f} snappyHexMesh -overwrite -parallel\n'.format(self.nCPUs_mesh)) f.write('reconstructParMesh -constant\n') f.write('rm -fr processor*\n') f.write('createPatch -overwrite\n') f.write('mv system/decomposeParDict system/decomposeParDict.mesh\n') f.write('mv system/decomposeParDict.sim system/decomposeParDict\n') f.write('renumberMesh -overwrite\n') if len(self.topoSetList) > 0: f.write('topoSet\n') f.close() # ------- Simulation --------------------- f = open(self.runFolder + '/runSim.sh', 'w') f.write('#!/bin/bash\n\n') f.write('decomposePar\n') if self.vilje: f.write('mpiexec ' + self.solver + ' -parallel\n') else: f.write('mpirun -np {:.0f} '.format(self.nCPUs) + self.solver + ' -parallel\n') f.write('reconstructPar\n') f.write('rm -fr processor*\n') f.close() def addViscousWake(self, x0, y0, z0, lengthFactor = 4, radiusFactor = 1.0, expansion = 2): # Ensure that mesh size is calculated self.turbulence = Turbulence.Properties(self.U, self.L, self.nu, self.turbulenceModel, self.turbulenceType) self.turbulence.calculateInitialValues() self.calculateBaseSize() maxLevel = int(np.floor(np.log(self.baseSize/self.viscousLength)/np.log(2))) print(maxLevel) radius0 = radiusFactor*self.D length0 = lengthFactor*self.D level = maxLevel for i in range(maxLevel): cellLength = self.baseSize/(2**level+1) name = 'viscWake{:.0f}'.format(i+1) length = length0*expansion**(i) radius = radius0*expansion**(i) point1String = '({:.6f} {:.6f} {:.6f})'.format(x0, y0, z0) point2String = '({:.6f} {:.6f} {:.6f})'.format(x0+length, y0, z0) radiusString = '{:.6f}'.format(radius) self.snappyDict.addGeometry(name, 'searchableCylinder', {'point1':point1String, 'point2':point2String, 'radius':radiusString}) self.snappyDict.addRefinementRegion(name, 'inside', np.array([1, level])) level -= 1 def writePropInfo(self): f = open(self.runFolder + 'propInfo.txt', 'w') f.write('D {:.6f}\n'.format(self.D)) f.write('c {:.6f}\n'.format(self.L)) f.write('Re {:.6f}\n'.format(self.Re)) f.write('J {:.6f}\n'.format(self.J)) f.write('n {:.6f}\n'.format(self.n)) f.write('omega {:.6f}\n'.format(self.omega)) f.write('rho {:.6f}\n'.format(self.rho)) f.write('U {:.6f}\n'.format(self.U)) f.write('U_R {:.6f}\n'.format(self.U_r)) f.close() class ActuatorDisk(CaseSetup): def __init__(self, runName, U, D, CT, CQ=0.0, rh_factor=0.1, alpha=0, fluid='air', meshSetting='medium', vilje=False): # Default environment settings if fluid == 'air': rho = 1.226 nu = 1.45e-05 elif fluid == 'water': rho = 1000 nu = 1.19e-6 self.D = D self.r = D/2 self.r_h = rh_factor*self.r self.CT = CT self.CQ = CQ self.alpha = alpha A = np.pi*self.r**2 patchList = [] # Call init from base class super().__init__(runName, patchList, 0.5*self.r, U, A, nu, rho, vilje) self.Thrust = 0.5*self.A*self.CT*self.U**2 self.Torque = 0.5*self.A*self.CQ*self.U**2*self.D # Essential folder paths self.foamPath = os.environ['FOAM_RUN'] self.mainRunFolder = self.foamPath + '/PropellerSimulation' self.homePath = os.path.dirname(os.path.realpath(__file__)) self.setFolderPaths() self.maxBaseSize = 0.5*self.D self.maxSmallestSize = 0.01*self.D self.actuatorDiskLength = 0.05*self.D self.viscousLength = 0.02*self.D # Default mesh settings if meshSetting == 'fine': self.maxBaseSize /= np.sqrt(2) self.maxSmallestSize /= np.sqrt(2) self.viscousLength /= np.sqrt(2) elif meshSetting == 'veryFine': self.maxBaseSize /= 2 self.maxSmallestSize /= 2 self.viscousLength /= 2 elif meshSetting == 'coarse': self.maxBaseSize *= np.sqrt(2) self.maxSmallestSize *= np.sqrt(2) self.viscousLength *= np.sqrt(2) elif meshSetting == 'veryCoarse': self.maxBaseSize *= 2 self.maxSmallestSize *= 2 self.viscousLength *= 2 self.baseSize = 1 self.domainWake = 10 self.domainFront = 5 self.domainWidth = 5 self.setMeshSettings() self.setSolver('simpleFoam') def calculateBaseSize(self): self.smallestSize = self.maxSmallestSize self.baseSize = self.smallestSize*2**(self.maxRefinementLevel) while self.baseSize > self.maxBaseSize and self.maxRefinementLevel > self.minRefinementLevel: self.maxRefinementLevel -= 1 self.baseSize = self.smallestSize*2**(self.maxRefinementLevel) def writeBlockMesh(self): blockMesh = BlockMesh.Dict() # Calculate minimum values for domain size xBack = self.domainWake*self.D xFront = -self.domainFront*self.D yRight = self.domainWidth*self.D yLeft = -self.domainWidth*self.D zHeight = self.domainWidth*self.D zDepth = -self.domainWidth*self.D # Calculate number of cells in each direction x_nrCells = np.ceil((xBack - xFront)/self.baseSize) y_nrCells = np.ceil((yRight - yLeft)/self.baseSize) z_nrCells = np.ceil((zHeight - zDepth)/self.baseSize) # Readjust domain size to fit nr cells xLength = self.baseSize*x_nrCells yLength = self.baseSize*y_nrCells zLength = self.baseSize*z_nrCells wakeFraction = (self.domainWake/(self.domainWake + self.domainFront)) frontFraction = (self.domainFront/(self.domainWake + self.domainFront)) xFront = -xLength*frontFraction xBack = xLength*wakeFraction yRight = yLength/2 yLeft = -yLength/2 # Add data to blockmesh and write blockMesh.addVertex([xFront, yLeft, zDepth]) blockMesh.addVertex([xBack, yLeft, zDepth]) blockMesh.addVertex([xBack, yRight, zDepth]) blockMesh.addVertex([xFront, yRight, zDepth]) blockMesh.addVertex([xFront, yLeft, zHeight]) blockMesh.addVertex([xBack, yLeft, zHeight]) blockMesh.addVertex([xBack, yRight, zHeight]) blockMesh.addVertex([xFront, yRight, zHeight]) blockMesh.addBlock([x_nrCells, y_nrCells, z_nrCells]) blockMesh.addBoundary('inlet', 'patch', [[0, 4, 7, 3],[3, 2, 6, 7], [4, 5, 6, 7], [0, 1, 5, 4], [0, 3, 2, 1]]) blockMesh.addBoundary('outlet', 'patch', [[2, 6, 5, 1]]) blockMesh.write(self.systemFolder) def writeMesh(self): self.calculateBaseSize() self.writeBlockMesh() name = 'actuatorDisk' p1 = np.array([0, 0, 0]) r = self.r diskDir = np.array([np.cos(self.alpha), -np.sin(self.alpha), 0]) diskThickness = self.actuatorDiskLength self.addPropellerActuatorDisk(name, p1, r, diskDir, diskThickness, self.Thrust, self.Torque, self.smallestSize) self.snappyDict.write(self.systemFolder) def writeCaseFiles(self): super().writeCaseFiles() def addViscousWake(self, x0, y0, z0, lengthFactor = 4, radiusFactor = 1.0, expansion = 2): # Ensure that mesh size is calculated self.calculateBaseSize() maxLevel = int(np.floor(np.log(self.baseSize/self.viscousLength)/np.log(2))) radius0 = radiusFactor*self.D length0 = lengthFactor*self.D level = maxLevel for i in range(maxLevel): cellLength = self.baseSize/(2**level+1) name = 'viscWake{:.0f}'.format(i+1) length = length0*expansion**(i) radius = radius0*expansion**(i) point1String = '({:.6f} {:.6f} {:.6f})'.format(x0, y0, z0) point2String = '({:.6f} {:.6f} {:.6f})'.format(x0+length, y0, z0) radiusString = '{:.6f}'.format(radius) self.snappyDict.addGeometry(name, 'searchableCylinder', {'point1':point1String, 'point2':point2String, 'radius':radiusString}) self.snappyDict.addRefinementRegion(name, 'inside', np.array([1, level])) level -= 1 def writeScripts(self): # ------ Mesh -------------------- f = open(self.runFolder+'/mesh.sh', 'w') f.write('#!/bin/bash\n\n') f.write('blockMesh\n') f.write('mv system/decomposeParDict system/decomposeParDict.sim\n') f.write('mv system/decomposeParDict.mesh system/decomposeParDict\n') f.write('decomposePar\n') f.write('mpirun -np {:.0f} snappyHexMesh -overwrite -parallel\n'.format(self.nCPUs_mesh)) f.write('reconstructParMesh -constant\n') f.write('rm -fr processor*\n') f.write('mv system/decomposeParDict system/decomposeParDict.mesh\n') f.write('mv system/decomposeParDict.sim system/decomposeParDict\n') f.write('createPatch -overwrite\n') if len(self.topoSetList) > 0: f.write('topoSet\n') f.close() # ------- Simulation --------------------- f = open(self.runFolder + '/runSim.sh', 'w') f.write('#!/bin/bash\n\n') f.write('decomposePar\n') if self.vilje: f.write('mpiexec ' + self.solver + ' -parallel\n') else: f.write('mpirun -np {:.0f} '.format(self.nCPUs) + self.solver + ' -parallel\n') f.write('reconstructPar\n') f.write('rm -fr processor*\n') f.close() def writeRunScripts(caseNameList, propSim, folderName=''): # Write run script f = open('run.sh', 'w') f.write('#!/bin/bash\n\n') f.write('cd $FOAM_RUN/PropellerSimulation\n\n') for i in range(len(caseNameList)): f.write('cd {0}\n'.format(caseNameList[i])) f.write('bash mesh.sh\n') f.write('bash runSim.sh\n') f.write('cd $FOAM_RUN/TowingTank\n\n') f.close()
0.356111
0.241042
from numpy.linalg import norm from numpy import savetxt from .FDGradient import FDGradient class FDValidGrad(object): """ Finite differences gradient calculation and validation. """ def __init__(self, scheme_order, f_pointer, df_pointer, fd_step=1e-6, bounds=None): """ Constructor Args: scheme_order : order of the numerical scheme : 1, 1j, 2, f_pointer : pointer to the function to be derived df_pointer : pointer to the function gradient to be checked fd_step : finite differences step """ self.__fpointer = f_pointer self.__df_pointer = df_pointer self.__fd_grad = FDGradient( scheme_order, f_pointer, fd_step=fd_step, bounds=bounds) self.__multi_proc = False self.set_multi_proc(False) def set_bounds(self, bounds): self.__fd_grad.set_bounds(bounds) def set_multi_proc(self, multi): self.__multi_proc = multi self.__fd_grad.set_multi_proc(multi) def compute_fd_grad(self, x, args=None): """ Computes the gradient by finite differences Args : x : variables where the function is derived Returns: The gradient vector """ if args is not None: return self.__fd_grad.grad_f(x, args) return self.__fd_grad.grad_f(x) def compare(self, x, treshold=1e-4, args=None, force_print=False, split_out=False, iprint=True, return_all=False, write_to_files=False, grad_files_prefix=""): """ Comparison of provided gradient and finite differences gradient. Args : x : variables where the function is derived treshold : tolerance between analytical and finite differences gradient args : function additional args force_print : if True, error is printed file names of the exported gradient values split_out: split checking of vectorial outputs iprint : allows printing of messages return_all : instead of returning status only, returns status, finite differences gradient and analytical gradients write_to_files: write gradients into files grad_files_prefix : if write_to_files and gradient is written to disc, Returns: ok : True if gradient is valid df_fd : optional finite differences gradient output df: optional analytical gradient output """ df_fd = self.compute_fd_grad(x, args) if args is None: df = self.__df_pointer(x) else: df = self.__df_pointer(x, args) ok, msg = self.__compute_error_and_check( df_fd, df, treshold, split_out=split_out) if (not ok or force_print) and iprint: print(msg) if write_to_files: for i in range(len(x)): savetxt(grad_files_prefix + 'df_analytic_' + str(i) + '.txt', df[:, :, i].T) savetxt(grad_files_prefix + 'df_FD_' + str(i) + '.txt', df_fd[:, :, i].T) if return_all: return ok, df_fd, df else: return ok def __compute_error_and_check(self, df_fd, df, treshold, split_out=False): """ Computes the relative error between finite differences gradient and analytical gradient. Args : df_fd : the gradient obtained by finite differences df : the analytical gradient treshold : the numerical tolerance for the comparison split_out : option to check each output from a vectorial output Returns: ok : the status msg : message about the error """ if len(df.shape) == 1 or not split_out: nfd = norm(df_fd) if nfd < treshold: # In case df = 0 err = norm(df_fd - df) else: err = norm(df_fd - df) / nfd if err < treshold: ok = True msg = 'Gradients are valid.' else: ok = False msg = 'Gradient not in bounds, error = ' + str(err) + '\n' msg += 'df =\n' + str(df) + '\n' msg += 'df finite diff =\n' + str(df_fd) + '\n' msg += 'df-df_fd =\n' + str(df - df_fd) + '\n' else: ok = True err = 0. dim_out = df.shape[0] err_msg = 'Gradients are not valid due to an error in the output vector\n' for n in range(dim_out): ndv = len(df_fd[n, :]) nfd = norm(df_fd[n, :]) / ndv if nfd < treshold: # In case df = 0 lerr = norm(df_fd[n, :] - df[n, :]) else: lerr = norm(df_fd[n, :] - df[n, :]) / nfd err += lerr if lerr > treshold: ok = False err_msg += 'Error may come from output ' + \ str(n) + ' error = ' + str(lerr) + '\n' if ok: msg = 'Gradients are valid.' else: msg = err_msg err = err / dim_out return ok, msg
sos_trades_core/tools/grad_solvers/validgrad/FDValidGrad.py
from numpy.linalg import norm from numpy import savetxt from .FDGradient import FDGradient class FDValidGrad(object): """ Finite differences gradient calculation and validation. """ def __init__(self, scheme_order, f_pointer, df_pointer, fd_step=1e-6, bounds=None): """ Constructor Args: scheme_order : order of the numerical scheme : 1, 1j, 2, f_pointer : pointer to the function to be derived df_pointer : pointer to the function gradient to be checked fd_step : finite differences step """ self.__fpointer = f_pointer self.__df_pointer = df_pointer self.__fd_grad = FDGradient( scheme_order, f_pointer, fd_step=fd_step, bounds=bounds) self.__multi_proc = False self.set_multi_proc(False) def set_bounds(self, bounds): self.__fd_grad.set_bounds(bounds) def set_multi_proc(self, multi): self.__multi_proc = multi self.__fd_grad.set_multi_proc(multi) def compute_fd_grad(self, x, args=None): """ Computes the gradient by finite differences Args : x : variables where the function is derived Returns: The gradient vector """ if args is not None: return self.__fd_grad.grad_f(x, args) return self.__fd_grad.grad_f(x) def compare(self, x, treshold=1e-4, args=None, force_print=False, split_out=False, iprint=True, return_all=False, write_to_files=False, grad_files_prefix=""): """ Comparison of provided gradient and finite differences gradient. Args : x : variables where the function is derived treshold : tolerance between analytical and finite differences gradient args : function additional args force_print : if True, error is printed file names of the exported gradient values split_out: split checking of vectorial outputs iprint : allows printing of messages return_all : instead of returning status only, returns status, finite differences gradient and analytical gradients write_to_files: write gradients into files grad_files_prefix : if write_to_files and gradient is written to disc, Returns: ok : True if gradient is valid df_fd : optional finite differences gradient output df: optional analytical gradient output """ df_fd = self.compute_fd_grad(x, args) if args is None: df = self.__df_pointer(x) else: df = self.__df_pointer(x, args) ok, msg = self.__compute_error_and_check( df_fd, df, treshold, split_out=split_out) if (not ok or force_print) and iprint: print(msg) if write_to_files: for i in range(len(x)): savetxt(grad_files_prefix + 'df_analytic_' + str(i) + '.txt', df[:, :, i].T) savetxt(grad_files_prefix + 'df_FD_' + str(i) + '.txt', df_fd[:, :, i].T) if return_all: return ok, df_fd, df else: return ok def __compute_error_and_check(self, df_fd, df, treshold, split_out=False): """ Computes the relative error between finite differences gradient and analytical gradient. Args : df_fd : the gradient obtained by finite differences df : the analytical gradient treshold : the numerical tolerance for the comparison split_out : option to check each output from a vectorial output Returns: ok : the status msg : message about the error """ if len(df.shape) == 1 or not split_out: nfd = norm(df_fd) if nfd < treshold: # In case df = 0 err = norm(df_fd - df) else: err = norm(df_fd - df) / nfd if err < treshold: ok = True msg = 'Gradients are valid.' else: ok = False msg = 'Gradient not in bounds, error = ' + str(err) + '\n' msg += 'df =\n' + str(df) + '\n' msg += 'df finite diff =\n' + str(df_fd) + '\n' msg += 'df-df_fd =\n' + str(df - df_fd) + '\n' else: ok = True err = 0. dim_out = df.shape[0] err_msg = 'Gradients are not valid due to an error in the output vector\n' for n in range(dim_out): ndv = len(df_fd[n, :]) nfd = norm(df_fd[n, :]) / ndv if nfd < treshold: # In case df = 0 lerr = norm(df_fd[n, :] - df[n, :]) else: lerr = norm(df_fd[n, :] - df[n, :]) / nfd err += lerr if lerr > treshold: ok = False err_msg += 'Error may come from output ' + \ str(n) + ' error = ' + str(lerr) + '\n' if ok: msg = 'Gradients are valid.' else: msg = err_msg err = err / dim_out return ok, msg
0.830972
0.476519
import curses import logging import os from vindauga.constants.command_codes import cmPaste from vindauga.constants.event_codes import evMouseUp, evKeyDown, evMouseDown, evCommand from vindauga.constants.option_flags import ofSelectable from vindauga.constants.keys import * from vindauga.events.event import Event from vindauga.misc.clipboard import Clipboard from vindauga.types.collections.collection import Collection from vindauga.types.draw_buffer import DrawBuffer from vindauga.types.point import Point from vindauga.types.view import View from .terminal import Terminal, STATE_CURSOR_INVIS, STATE_TITLE_CHANGED, STATE_MOUSE logger = logging.getLogger(__name__) class TerminalView(View): ActiveTerminals = Collection() def __init__(self, bounds, parent, command=None, *commandArgs): super().__init__(bounds) self.window = parent self.__clipboard = Clipboard() self.eventMask |= evMouseUp self.options |= ofSelectable self.terminal = Terminal(self.size.x, self.size.y, 0, command, *commandArgs) self.terminal.setColors(curses.COLOR_WHITE, curses.COLOR_BLACK) def draw(self): minY = min(self.size.y, self.terminal.rows) minX = min(self.size.x, self.terminal.cols) for y in range(minY): buffer = DrawBuffer(True) for x in range(minX): cell = self.terminal.cells[y][x] attr = cell.attr c = cell.color if attr & curses.A_REVERSE: c = self.reverseColor(c) buffer.putAttribute(x, c) buffer.putChar(x, chr(cell.char)) self.writeLine(0, y, minX, 1, buffer) self.setCursor(self.terminal.currCol, self.terminal.currRow) if self.terminal.state & STATE_CURSOR_INVIS: self.hideCursor() else: self.showCursor() if self.terminal.state & STATE_TITLE_CHANGED: self.window.setTitle(self.terminal.title) self.terminal.state &= ~STATE_TITLE_CHANGED def handleEvent(self, event: Event): super().handleEvent(event) ch = [0, 0] if event.what == evKeyDown: ch[0] = event.keyDown.charScan.charCode if ord(ch[0]) in {-1, 0}: ch = self.decodeKey(event.keyDown.keyCode) if ch[0] != -1: self.terminal.write(ch[0]) if ch[1]: self.terminal.write(ch[1]) self.clearEvent(event) elif event.what in {evMouseDown, evMouseUp}: if self.terminal.state & STATE_MOUSE: self.sendMouseEvent(event) if not self.terminal.state & STATE_MOUSE: self.tryPaste(event, 1) self.clearEvent(event) elif event.what == evCommand: if event.message.command == cmPaste: self.tryPaste(event, 0) self.clearEvent(event) def sendMouseEvent(self, event: Event): local = self.makeLocal(event.mouse.where) b = chr(32) mb = event.mouse.buttons if mb & 1: b = chr(32) elif mb & 2: b = chr(33) elif mb & 4: b = chr(34) elif mb & 8: b = chr(96) elif mb & 16: b = chr(97) elif not (mb & 7): b = chr(35) bx = chr(local.x + 33) by = chr(local.y + 33) buffer = bytes('\033[M{b}{bx}{by}'.format(b=b, bx=bx, by=by)) os.write(self.terminal.ptyFd, buffer) def tryPaste(self, event: Event, clip: int): if clip and not event.mouse.buttons & 2: return buffer = self.__clipboard.receiveFromClipboard() if buffer: os.write(self.terminal.ptyFd, buffer) def changeSize(self, s: Point): self.terminal.resize(s.x - 2, s.y - 2) self.growTo(s.x - 2, s.y - 2) self.drawView() @staticmethod def decodeKey(k): ESC = '\x1B' keyMap = { kbEnter: (10, 0), kbEsc: (ESC, 0), kbDown: (curses.KEY_DOWN, 0), kbUp: (curses.KEY_UP, 0), kbLeft: (curses.KEY_LEFT, 0), kbRight: (curses.KEY_RIGHT, 0), kbBackSpace: (curses.KEY_BACKSPACE, 0), kbTab: (9, 0), kbPgDn: (curses.KEY_NPAGE, 0), kbPgUp: (curses.KEY_PPAGE, 0), kbHome: (curses.KEY_HOME, 0), kbEnd: (curses.KEY_END, 0), kbIns: (curses.KEY_IC, 0), kbDel: (curses.KEY_DC, 0), kbF1: (curses.KEY_F1, 0), kbF2: (curses.KEY_F2, 0), kbF3: (curses.KEY_F3, 0), kbF4: (curses.KEY_F4, 0), kbF5: (curses.KEY_F5, 0), kbF6: (curses.KEY_F6, 0), kbF7: (curses.KEY_F7, 0), kbF8: (curses.KEY_F8, 0), kbF9: (curses.KEY_F9, 0), kbF10: (curses.KEY_F10, 0), kbAltA: (ESC, 'A'), kbAltB: (ESC, 'B'), kbAltC: (ESC, 'C'), kbAltD: (ESC, 'D'), kbAltE: (ESC, 'E'), kbAltF: (ESC, 'F'), kbAltG: (ESC, 'G'), kbAltH: (ESC, 'H'), kbAltI: (ESC, 'I'), kbAltJ: (ESC, 'J'), kbAltK: (ESC, 'K'), kbAltL: (ESC, 'L'), kbAltM: (ESC, 'M'), kbAltN: (ESC, 'N'), kbAltO: (ESC, 'O'), kbAltP: (ESC, 'P'), kbAltQ: (ESC, 'Q'), kbAltR: (ESC, 'R'), kbAltS: (ESC, 'S'), kbAltT: (ESC, 'T'), kbAltU: (ESC, 'U'), kbAltV: (ESC, 'V'), kbAltW: (ESC, 'W'), kbAltX: (ESC, 'X'), kbAltY: (ESC, 'Y'), kbAltZ: (ESC, 'Z'), } if k in keyMap: return keyMap[k] return -1, 0 @staticmethod def reverseColor(color): a = color & 0x0F b = color & 0xF0 return (a << 4) | (b >> 4) @staticmethod def handleTerminal(window, *args): bytesRead = window.terminal.readPipe() if bytesRead > 0: window.drawView() elif bytesRead == -1: window.window.close() @staticmethod def updateTerminals(): """ Call me on idle; `TerminalView.updateTerminals()` """ TerminalView.ActiveTerminals.forEach(TerminalView.handleTerminal)
vindauga/terminal/terminal_view.py
import curses import logging import os from vindauga.constants.command_codes import cmPaste from vindauga.constants.event_codes import evMouseUp, evKeyDown, evMouseDown, evCommand from vindauga.constants.option_flags import ofSelectable from vindauga.constants.keys import * from vindauga.events.event import Event from vindauga.misc.clipboard import Clipboard from vindauga.types.collections.collection import Collection from vindauga.types.draw_buffer import DrawBuffer from vindauga.types.point import Point from vindauga.types.view import View from .terminal import Terminal, STATE_CURSOR_INVIS, STATE_TITLE_CHANGED, STATE_MOUSE logger = logging.getLogger(__name__) class TerminalView(View): ActiveTerminals = Collection() def __init__(self, bounds, parent, command=None, *commandArgs): super().__init__(bounds) self.window = parent self.__clipboard = Clipboard() self.eventMask |= evMouseUp self.options |= ofSelectable self.terminal = Terminal(self.size.x, self.size.y, 0, command, *commandArgs) self.terminal.setColors(curses.COLOR_WHITE, curses.COLOR_BLACK) def draw(self): minY = min(self.size.y, self.terminal.rows) minX = min(self.size.x, self.terminal.cols) for y in range(minY): buffer = DrawBuffer(True) for x in range(minX): cell = self.terminal.cells[y][x] attr = cell.attr c = cell.color if attr & curses.A_REVERSE: c = self.reverseColor(c) buffer.putAttribute(x, c) buffer.putChar(x, chr(cell.char)) self.writeLine(0, y, minX, 1, buffer) self.setCursor(self.terminal.currCol, self.terminal.currRow) if self.terminal.state & STATE_CURSOR_INVIS: self.hideCursor() else: self.showCursor() if self.terminal.state & STATE_TITLE_CHANGED: self.window.setTitle(self.terminal.title) self.terminal.state &= ~STATE_TITLE_CHANGED def handleEvent(self, event: Event): super().handleEvent(event) ch = [0, 0] if event.what == evKeyDown: ch[0] = event.keyDown.charScan.charCode if ord(ch[0]) in {-1, 0}: ch = self.decodeKey(event.keyDown.keyCode) if ch[0] != -1: self.terminal.write(ch[0]) if ch[1]: self.terminal.write(ch[1]) self.clearEvent(event) elif event.what in {evMouseDown, evMouseUp}: if self.terminal.state & STATE_MOUSE: self.sendMouseEvent(event) if not self.terminal.state & STATE_MOUSE: self.tryPaste(event, 1) self.clearEvent(event) elif event.what == evCommand: if event.message.command == cmPaste: self.tryPaste(event, 0) self.clearEvent(event) def sendMouseEvent(self, event: Event): local = self.makeLocal(event.mouse.where) b = chr(32) mb = event.mouse.buttons if mb & 1: b = chr(32) elif mb & 2: b = chr(33) elif mb & 4: b = chr(34) elif mb & 8: b = chr(96) elif mb & 16: b = chr(97) elif not (mb & 7): b = chr(35) bx = chr(local.x + 33) by = chr(local.y + 33) buffer = bytes('\033[M{b}{bx}{by}'.format(b=b, bx=bx, by=by)) os.write(self.terminal.ptyFd, buffer) def tryPaste(self, event: Event, clip: int): if clip and not event.mouse.buttons & 2: return buffer = self.__clipboard.receiveFromClipboard() if buffer: os.write(self.terminal.ptyFd, buffer) def changeSize(self, s: Point): self.terminal.resize(s.x - 2, s.y - 2) self.growTo(s.x - 2, s.y - 2) self.drawView() @staticmethod def decodeKey(k): ESC = '\x1B' keyMap = { kbEnter: (10, 0), kbEsc: (ESC, 0), kbDown: (curses.KEY_DOWN, 0), kbUp: (curses.KEY_UP, 0), kbLeft: (curses.KEY_LEFT, 0), kbRight: (curses.KEY_RIGHT, 0), kbBackSpace: (curses.KEY_BACKSPACE, 0), kbTab: (9, 0), kbPgDn: (curses.KEY_NPAGE, 0), kbPgUp: (curses.KEY_PPAGE, 0), kbHome: (curses.KEY_HOME, 0), kbEnd: (curses.KEY_END, 0), kbIns: (curses.KEY_IC, 0), kbDel: (curses.KEY_DC, 0), kbF1: (curses.KEY_F1, 0), kbF2: (curses.KEY_F2, 0), kbF3: (curses.KEY_F3, 0), kbF4: (curses.KEY_F4, 0), kbF5: (curses.KEY_F5, 0), kbF6: (curses.KEY_F6, 0), kbF7: (curses.KEY_F7, 0), kbF8: (curses.KEY_F8, 0), kbF9: (curses.KEY_F9, 0), kbF10: (curses.KEY_F10, 0), kbAltA: (ESC, 'A'), kbAltB: (ESC, 'B'), kbAltC: (ESC, 'C'), kbAltD: (ESC, 'D'), kbAltE: (ESC, 'E'), kbAltF: (ESC, 'F'), kbAltG: (ESC, 'G'), kbAltH: (ESC, 'H'), kbAltI: (ESC, 'I'), kbAltJ: (ESC, 'J'), kbAltK: (ESC, 'K'), kbAltL: (ESC, 'L'), kbAltM: (ESC, 'M'), kbAltN: (ESC, 'N'), kbAltO: (ESC, 'O'), kbAltP: (ESC, 'P'), kbAltQ: (ESC, 'Q'), kbAltR: (ESC, 'R'), kbAltS: (ESC, 'S'), kbAltT: (ESC, 'T'), kbAltU: (ESC, 'U'), kbAltV: (ESC, 'V'), kbAltW: (ESC, 'W'), kbAltX: (ESC, 'X'), kbAltY: (ESC, 'Y'), kbAltZ: (ESC, 'Z'), } if k in keyMap: return keyMap[k] return -1, 0 @staticmethod def reverseColor(color): a = color & 0x0F b = color & 0xF0 return (a << 4) | (b >> 4) @staticmethod def handleTerminal(window, *args): bytesRead = window.terminal.readPipe() if bytesRead > 0: window.drawView() elif bytesRead == -1: window.window.close() @staticmethod def updateTerminals(): """ Call me on idle; `TerminalView.updateTerminals()` """ TerminalView.ActiveTerminals.forEach(TerminalView.handleTerminal)
0.40157
0.095265
from random import random from math import log import numpy as np def intervalq(point, bounds): '''find which interval a point lies in given interval bounds input: point - number to identify bucket for bounds - list of increasing bucket bounds including ends output: index such that bounds[index - 1] <= point < bounds[index] ''' right = len(bounds) - 1 left = 0 assert(right > 0) # check that bounds contains at least two elements # deal with points outside bounds range if point >= bounds[right]: return right if point <= bounds[left]: return 1 # binary search for interval while left < right - 1: assert(bounds[left] < bounds[right]) # check that bounds are sorted mid = (left + right)/2 if point >= bounds[mid]: left = mid else: right = mid return right def rlaplace(scale, location=0): '''genrate a random deviate from Laplace(location, scale)''' assert(scale > 0) r = random() signr = 1 if r >= 0.5 else -1 rr = r if r < 0.5 else 1 - r return location - signr * scale * log(2 * rr) def noisyh(h, epsilon=1.0, tau=0.5): '''make a histogram ina numpy array differentially private. Expected maximal noise added is O(lon(n)/epsilon) where n are the number of times noise is added, i.e., size of histogram. Using this, we set entries that are smaller than tau * log(n)/epsilon 0.''' hp = map(lambda x: rlaplace(scale=2/epsilon, location=x), h.flatten()) threshold = tau * log(len(hp))/epsilon hpt = map(lambda y: 0 if y < threshold else y, hp) return np.reshape(hpt, h.shape) def p2m(points, xbounds, ybounds): '''convert a list of points to histogram. xbounds and ybounds contain grid axis points into which points are discretized.''' xb = sorted(xbounds) # make sure boundaries are sorted yb = sorted(ybounds) # make sure boundaries are sorted nxb = len(xb) - 1 # number of x intervals nyb = len(yb) - 1 # number of y intervals h = np.zeros((nxb, nyb)) for x, y in points: i = intervalq(x, xb) - 1 j = intervalq(y, yb) - 1 h[i, j] += 1 return h def m2p(h, xbounds, ybounds): '''transform histogram into points xbounds and ybounds give grid axis points, meaning that h[i,j] is translated into a point (x,y) such that x is uniformly distributed in [xbounds[i], xbounds[i + 1]), and similarly for y.''' xb = sorted(xbounds) # make sure boundaries are sorted yb = sorted(ybounds) # make sure boundaries are sorted nxb = len(xb) - 1 # number of x intervals nyb = len(yb) - 1 # number of y intervals assert(h.shape == (nxb, nyb)) points = [] for i in range(nxb): ax = xb[i] bx = xb[i + 1] xwidth = bx - ax for j in range(nyb): ay = yb[j] by = yb[j + 1] ywidth = by - ay pnts = map(lambda _: (ax + random() * xwidth, ay + random() * ywidth), range(int(h[i, j]))) points = pnts + points return points def privatize(points, xbounds, ybounds, epsilon=1.0, tau=1.5): '''create differentially private version of list of points using a grid the grid is defined by axis points in xbounds and ybounds. epsilon is the differential privacy level. tau is a filtering parameter, see noisyh(). ''' dph = np.array( noisyh( p2m(points, xbounds, ybounds), epsilon, tau).round(), int) return m2p(dph, xbounds, ybounds)
keep_backend/privacy/map.py
from random import random from math import log import numpy as np def intervalq(point, bounds): '''find which interval a point lies in given interval bounds input: point - number to identify bucket for bounds - list of increasing bucket bounds including ends output: index such that bounds[index - 1] <= point < bounds[index] ''' right = len(bounds) - 1 left = 0 assert(right > 0) # check that bounds contains at least two elements # deal with points outside bounds range if point >= bounds[right]: return right if point <= bounds[left]: return 1 # binary search for interval while left < right - 1: assert(bounds[left] < bounds[right]) # check that bounds are sorted mid = (left + right)/2 if point >= bounds[mid]: left = mid else: right = mid return right def rlaplace(scale, location=0): '''genrate a random deviate from Laplace(location, scale)''' assert(scale > 0) r = random() signr = 1 if r >= 0.5 else -1 rr = r if r < 0.5 else 1 - r return location - signr * scale * log(2 * rr) def noisyh(h, epsilon=1.0, tau=0.5): '''make a histogram ina numpy array differentially private. Expected maximal noise added is O(lon(n)/epsilon) where n are the number of times noise is added, i.e., size of histogram. Using this, we set entries that are smaller than tau * log(n)/epsilon 0.''' hp = map(lambda x: rlaplace(scale=2/epsilon, location=x), h.flatten()) threshold = tau * log(len(hp))/epsilon hpt = map(lambda y: 0 if y < threshold else y, hp) return np.reshape(hpt, h.shape) def p2m(points, xbounds, ybounds): '''convert a list of points to histogram. xbounds and ybounds contain grid axis points into which points are discretized.''' xb = sorted(xbounds) # make sure boundaries are sorted yb = sorted(ybounds) # make sure boundaries are sorted nxb = len(xb) - 1 # number of x intervals nyb = len(yb) - 1 # number of y intervals h = np.zeros((nxb, nyb)) for x, y in points: i = intervalq(x, xb) - 1 j = intervalq(y, yb) - 1 h[i, j] += 1 return h def m2p(h, xbounds, ybounds): '''transform histogram into points xbounds and ybounds give grid axis points, meaning that h[i,j] is translated into a point (x,y) such that x is uniformly distributed in [xbounds[i], xbounds[i + 1]), and similarly for y.''' xb = sorted(xbounds) # make sure boundaries are sorted yb = sorted(ybounds) # make sure boundaries are sorted nxb = len(xb) - 1 # number of x intervals nyb = len(yb) - 1 # number of y intervals assert(h.shape == (nxb, nyb)) points = [] for i in range(nxb): ax = xb[i] bx = xb[i + 1] xwidth = bx - ax for j in range(nyb): ay = yb[j] by = yb[j + 1] ywidth = by - ay pnts = map(lambda _: (ax + random() * xwidth, ay + random() * ywidth), range(int(h[i, j]))) points = pnts + points return points def privatize(points, xbounds, ybounds, epsilon=1.0, tau=1.5): '''create differentially private version of list of points using a grid the grid is defined by axis points in xbounds and ybounds. epsilon is the differential privacy level. tau is a filtering parameter, see noisyh(). ''' dph = np.array( noisyh( p2m(points, xbounds, ybounds), epsilon, tau).round(), int) return m2p(dph, xbounds, ybounds)
0.866881
0.760428
from constants import * import sys import cv2 if sys.version_info[0] == 2: # Workaround for https://github.com/PythonCharmers/python-future/issues/262 from Tkinter import * else: from tkinter import * from PIL import ImageTk from PIL import Image import matplotlib, sys import matplotlib.pyplot as plt matplotlib.use('TkAgg') import numpy as np from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure video_width = 432 video_height = 240 DISPLAY_WIDTH = WIDTH DISPLAY_HEIGHT = 432 + video_height class Display(object): def __init__(self): plt.ion() #turn matplot interactive on self.root = Tk() self.root.wm_title("GVF Knowledge") #Data 1 self.tAFigure = Figure(figsize=(4.3,2), dpi=100) #self.a = self.tAFigure.add_subplot(111) self.taPlot = self.tAFigure.add_subplot(111) self.taPlot.set_ylim(-0.05, 1.05) timeStepValues = np.arange(-50, 0, 1) #The last 50 self.taPredictions = [0.0] * 50 self.taPredictionLine, = self.taPlot.plot(timeStepValues, self.taPredictions, 'g', label = "TA(predict)") self.taActualValues = [0.0] * 50 self.taActualLine, = self.taPlot.plot(timeStepValues, self.taActualValues, 'b', label="TA(actual)") self.taPlot.legend() self.taCanvas = FigureCanvasTkAgg(self.tAFigure, master=self.root) #canvas.get_tk_widget().grid(row=1,column=4,columnspan=3,rowspan=20) self.taCanvas.draw() self.taCanvas.get_tk_widget().pack(side = "top", anchor = "w") self.canvas = Canvas(self.root, borderwidth=0, highlightthickness=0, width=WIDTH, height=HEIGHT, bg="black") #self.canvas.config(width=WIDTH, height=HEIGHT) self.canvas.pack(padx=0, pady=0) #self.root_frame.pack() #Did touch display self.didTouch = StringVar() self.didTouchLabel = Label(self.root, textvariable = self.didTouch, font = 'Helvetica 18 bold') self.didTouchLabel.pack() #Touch prediction self.touchPrediction = StringVar() self.touchPredictionLabel = Label(self.root, textvariable = self.touchPrediction) self.touchPredictionLabel.pack(side = "top", anchor = "w") #Turn left and touch prediction self.turnLeftAndTouchPrediction = StringVar() self.turnLeftAndTouchPredictionLabel = Label(self.root, textvariable = self.turnLeftAndTouchPrediction) self.turnLeftAndTouchPredictionLabel.pack(side = "top", anchor = "w") #Turn right and touch prediction self.turnRightAndTouchPrediction = StringVar() self.turnRightAndTouchPredictionLabel = Label(self.root, textvariable = self.turnRightAndTouchPrediction) self.turnRightAndTouchPredictionLabel.pack(side = "top", anchor = "w") #Touch behind prediction self.touchBehindPrediction = StringVar() self.touchBehindPredictionLabel = Label(self.root, textvariable = self.touchBehindPrediction) self.touchBehindPredictionLabel.pack(side = "top", anchor = "w") #Wall Adjacent prediction self.isWallAdjacentPrediction = StringVar() self.isWallAdjacentPredictionLabel = Label(self.root, textvariable = self.isWallAdjacentPrediction) self.isWallAdjacentPredictionLabel.pack(side = "top", anchor = "w") #Distance to adjacent prediction self.distanceToAdjacent = StringVar() self.distanceToAdjacentLabel = Label(self.root, textvariable = self.distanceToAdjacent) self.distanceToAdjacentLabel.pack(side = "top", anchor = "w") #Number of Steps Left self.numberOfStepsLeft = StringVar() self.numberOfStepsLeftLabel = Label(self.root, textvariable=self.numberOfStepsLeft) self.numberOfStepsLeftLabel.pack(side="top", anchor="w") #Number of Steps Right self.numberOfStepsRight = StringVar() self.numberOfStepsRightLabel = Label(self.root, textvariable=self.numberOfStepsRight) self.numberOfStepsRightLabel.pack(side="top", anchor="w") #Number of Steps Back self.numberOfStepsBack = StringVar() self.numberOfStepsBackLabel = Label(self.root, textvariable=self.numberOfStepsBack) self.numberOfStepsBackLabel.pack(side="top", anchor="w") #Number of steps self.numberOfSteps = StringVar() self.numberOfStepsLabel = Label(self.root, textvariable = self.numberOfSteps) self.numberOfStepsLabel.pack(side = "top", anchor = "w") self.reset() def reset(self): self.canvas.delete("all") self.image = Image.new('RGB', (WIDTH, HEIGHT)) self.photoImage = None self.image_handle = None self.current_frame = 0 def update(self, image, numberOfSteps, currentTouchPrediction, didTouch, turnLeftAndTouchPrediction, wallInFront, wallOnLeft, turnRightAndTouchPrediction, wallOnRight, touchBehindPrediction, wallBehind, touchAdjacentPrediction, distanceToAdjacent, distanceToAdjacentPrediction, distanceToLeft, distanceToLeftPrediction, distanceToRight, distanceToRightPrediction, distanceBack, distanceBackPrediction, wallAdjacent): #Update labels self.touchPrediction.set("T: " + str(currentTouchPrediction)) if wallInFront: self.touchPredictionLabel.config(fg = 'blue') else: self.touchPredictionLabel.config(fg = 'red') self.turnLeftAndTouchPrediction.set("TL: " + str(turnLeftAndTouchPrediction)) if wallOnLeft: self.turnLeftAndTouchPredictionLabel.config(fg='blue') else: self.turnLeftAndTouchPredictionLabel.config(fg = 'red') self.turnRightAndTouchPrediction.set("TR: " + str(turnRightAndTouchPrediction)) if wallOnRight: self.turnRightAndTouchPredictionLabel.config(fg='blue') else: self.turnRightAndTouchPredictionLabel.config(fg='red') self.touchBehindPrediction.set("TB: " + str(touchBehindPrediction)) if wallBehind: self.touchBehindPredictionLabel.config(fg='blue') else: self.touchBehindPredictionLabel.config(fg='red') self.isWallAdjacentPrediction.set("TA: " + str(touchAdjacentPrediction)) if wallAdjacent: self.isWallAdjacentPredictionLabel.config(fg = 'blue') else: self.isWallAdjacentPredictionLabel.config(fg = 'red') self.distanceToAdjacent.set("DTA: " + str(round(distanceToAdjacentPrediction, 1)) + " (" + str(distanceToAdjacent) + ")") self.numberOfStepsLeft.set("DTL: " + str(round(distanceToLeftPrediction, 1)) + " (" + str(distanceToLeft) + ")") self.numberOfStepsRight.set("DTR: " + str(round(distanceToRightPrediction, 1)) + " (" + str(distanceToRight) + ")") self.numberOfStepsBack.set("DTB: " + str(round(distanceBackPrediction)) + " (" + str(distanceBack) + ")") self.numberOfSteps.set("Step: " + str(numberOfSteps)) if didTouch: self.didTouch.set("TOUCHED") else: self.didTouch.set("") #Update image #change from BGR to RGB l = len(image) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # convert the cv2 images to PIL format... self.image = Image.fromarray(image) # ...and then to ImageTk format self.photoImage = ImageTk.PhotoImage(self.image) # And update/create the canvas image: if self.image_handle is None: self.image_handle = self.canvas.create_image(WIDTH/2,HEIGHT/2, image=self.photoImage) else: self.canvas.itemconfig(self.image_handle, image=self.photoImage) self.taPredictions.pop(0) self.taPredictions.append(currentTouchPrediction) self.taActualValues.pop(0) if (wallInFront): touchActual = 1.0 else: touchActual = 0.0 self.taActualValues.append(touchActual) self.taPredictionLine.set_ydata(self.taPredictions) self.taActualLine.set_ydata(self.taActualValues) self.taCanvas.draw() self.root.update()
python/display.py
from constants import * import sys import cv2 if sys.version_info[0] == 2: # Workaround for https://github.com/PythonCharmers/python-future/issues/262 from Tkinter import * else: from tkinter import * from PIL import ImageTk from PIL import Image import matplotlib, sys import matplotlib.pyplot as plt matplotlib.use('TkAgg') import numpy as np from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure video_width = 432 video_height = 240 DISPLAY_WIDTH = WIDTH DISPLAY_HEIGHT = 432 + video_height class Display(object): def __init__(self): plt.ion() #turn matplot interactive on self.root = Tk() self.root.wm_title("GVF Knowledge") #Data 1 self.tAFigure = Figure(figsize=(4.3,2), dpi=100) #self.a = self.tAFigure.add_subplot(111) self.taPlot = self.tAFigure.add_subplot(111) self.taPlot.set_ylim(-0.05, 1.05) timeStepValues = np.arange(-50, 0, 1) #The last 50 self.taPredictions = [0.0] * 50 self.taPredictionLine, = self.taPlot.plot(timeStepValues, self.taPredictions, 'g', label = "TA(predict)") self.taActualValues = [0.0] * 50 self.taActualLine, = self.taPlot.plot(timeStepValues, self.taActualValues, 'b', label="TA(actual)") self.taPlot.legend() self.taCanvas = FigureCanvasTkAgg(self.tAFigure, master=self.root) #canvas.get_tk_widget().grid(row=1,column=4,columnspan=3,rowspan=20) self.taCanvas.draw() self.taCanvas.get_tk_widget().pack(side = "top", anchor = "w") self.canvas = Canvas(self.root, borderwidth=0, highlightthickness=0, width=WIDTH, height=HEIGHT, bg="black") #self.canvas.config(width=WIDTH, height=HEIGHT) self.canvas.pack(padx=0, pady=0) #self.root_frame.pack() #Did touch display self.didTouch = StringVar() self.didTouchLabel = Label(self.root, textvariable = self.didTouch, font = 'Helvetica 18 bold') self.didTouchLabel.pack() #Touch prediction self.touchPrediction = StringVar() self.touchPredictionLabel = Label(self.root, textvariable = self.touchPrediction) self.touchPredictionLabel.pack(side = "top", anchor = "w") #Turn left and touch prediction self.turnLeftAndTouchPrediction = StringVar() self.turnLeftAndTouchPredictionLabel = Label(self.root, textvariable = self.turnLeftAndTouchPrediction) self.turnLeftAndTouchPredictionLabel.pack(side = "top", anchor = "w") #Turn right and touch prediction self.turnRightAndTouchPrediction = StringVar() self.turnRightAndTouchPredictionLabel = Label(self.root, textvariable = self.turnRightAndTouchPrediction) self.turnRightAndTouchPredictionLabel.pack(side = "top", anchor = "w") #Touch behind prediction self.touchBehindPrediction = StringVar() self.touchBehindPredictionLabel = Label(self.root, textvariable = self.touchBehindPrediction) self.touchBehindPredictionLabel.pack(side = "top", anchor = "w") #Wall Adjacent prediction self.isWallAdjacentPrediction = StringVar() self.isWallAdjacentPredictionLabel = Label(self.root, textvariable = self.isWallAdjacentPrediction) self.isWallAdjacentPredictionLabel.pack(side = "top", anchor = "w") #Distance to adjacent prediction self.distanceToAdjacent = StringVar() self.distanceToAdjacentLabel = Label(self.root, textvariable = self.distanceToAdjacent) self.distanceToAdjacentLabel.pack(side = "top", anchor = "w") #Number of Steps Left self.numberOfStepsLeft = StringVar() self.numberOfStepsLeftLabel = Label(self.root, textvariable=self.numberOfStepsLeft) self.numberOfStepsLeftLabel.pack(side="top", anchor="w") #Number of Steps Right self.numberOfStepsRight = StringVar() self.numberOfStepsRightLabel = Label(self.root, textvariable=self.numberOfStepsRight) self.numberOfStepsRightLabel.pack(side="top", anchor="w") #Number of Steps Back self.numberOfStepsBack = StringVar() self.numberOfStepsBackLabel = Label(self.root, textvariable=self.numberOfStepsBack) self.numberOfStepsBackLabel.pack(side="top", anchor="w") #Number of steps self.numberOfSteps = StringVar() self.numberOfStepsLabel = Label(self.root, textvariable = self.numberOfSteps) self.numberOfStepsLabel.pack(side = "top", anchor = "w") self.reset() def reset(self): self.canvas.delete("all") self.image = Image.new('RGB', (WIDTH, HEIGHT)) self.photoImage = None self.image_handle = None self.current_frame = 0 def update(self, image, numberOfSteps, currentTouchPrediction, didTouch, turnLeftAndTouchPrediction, wallInFront, wallOnLeft, turnRightAndTouchPrediction, wallOnRight, touchBehindPrediction, wallBehind, touchAdjacentPrediction, distanceToAdjacent, distanceToAdjacentPrediction, distanceToLeft, distanceToLeftPrediction, distanceToRight, distanceToRightPrediction, distanceBack, distanceBackPrediction, wallAdjacent): #Update labels self.touchPrediction.set("T: " + str(currentTouchPrediction)) if wallInFront: self.touchPredictionLabel.config(fg = 'blue') else: self.touchPredictionLabel.config(fg = 'red') self.turnLeftAndTouchPrediction.set("TL: " + str(turnLeftAndTouchPrediction)) if wallOnLeft: self.turnLeftAndTouchPredictionLabel.config(fg='blue') else: self.turnLeftAndTouchPredictionLabel.config(fg = 'red') self.turnRightAndTouchPrediction.set("TR: " + str(turnRightAndTouchPrediction)) if wallOnRight: self.turnRightAndTouchPredictionLabel.config(fg='blue') else: self.turnRightAndTouchPredictionLabel.config(fg='red') self.touchBehindPrediction.set("TB: " + str(touchBehindPrediction)) if wallBehind: self.touchBehindPredictionLabel.config(fg='blue') else: self.touchBehindPredictionLabel.config(fg='red') self.isWallAdjacentPrediction.set("TA: " + str(touchAdjacentPrediction)) if wallAdjacent: self.isWallAdjacentPredictionLabel.config(fg = 'blue') else: self.isWallAdjacentPredictionLabel.config(fg = 'red') self.distanceToAdjacent.set("DTA: " + str(round(distanceToAdjacentPrediction, 1)) + " (" + str(distanceToAdjacent) + ")") self.numberOfStepsLeft.set("DTL: " + str(round(distanceToLeftPrediction, 1)) + " (" + str(distanceToLeft) + ")") self.numberOfStepsRight.set("DTR: " + str(round(distanceToRightPrediction, 1)) + " (" + str(distanceToRight) + ")") self.numberOfStepsBack.set("DTB: " + str(round(distanceBackPrediction)) + " (" + str(distanceBack) + ")") self.numberOfSteps.set("Step: " + str(numberOfSteps)) if didTouch: self.didTouch.set("TOUCHED") else: self.didTouch.set("") #Update image #change from BGR to RGB l = len(image) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # convert the cv2 images to PIL format... self.image = Image.fromarray(image) # ...and then to ImageTk format self.photoImage = ImageTk.PhotoImage(self.image) # And update/create the canvas image: if self.image_handle is None: self.image_handle = self.canvas.create_image(WIDTH/2,HEIGHT/2, image=self.photoImage) else: self.canvas.itemconfig(self.image_handle, image=self.photoImage) self.taPredictions.pop(0) self.taPredictions.append(currentTouchPrediction) self.taActualValues.pop(0) if (wallInFront): touchActual = 1.0 else: touchActual = 0.0 self.taActualValues.append(touchActual) self.taPredictionLine.set_ydata(self.taPredictions) self.taActualLine.set_ydata(self.taActualValues) self.taCanvas.draw() self.root.update()
0.322846
0.25393
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs import * __all__ = ['DomainArgs', 'Domain'] @pulumi.input_type class DomainArgs: def __init__(__self__, *, server_side_encryption_configuration: pulumi.Input['DomainServerSideEncryptionConfigurationArgs'], description: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Sequence[pulumi.Input['DomainTagArgs']]]] = None): """ The set of arguments for constructing a Domain resource. """ pulumi.set(__self__, "server_side_encryption_configuration", server_side_encryption_configuration) if description is not None: pulumi.set(__self__, "description", description) if name is not None: pulumi.set(__self__, "name", name) if tags is not None: pulumi.set(__self__, "tags", tags) @property @pulumi.getter(name="serverSideEncryptionConfiguration") def server_side_encryption_configuration(self) -> pulumi.Input['DomainServerSideEncryptionConfigurationArgs']: return pulumi.get(self, "server_side_encryption_configuration") @server_side_encryption_configuration.setter def server_side_encryption_configuration(self, value: pulumi.Input['DomainServerSideEncryptionConfigurationArgs']): pulumi.set(self, "server_side_encryption_configuration", value) @property @pulumi.getter def description(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "description") @description.setter def description(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "description", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['DomainTagArgs']]]]: return pulumi.get(self, "tags") @tags.setter def tags(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['DomainTagArgs']]]]): pulumi.set(self, "tags", value) class Domain(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, description: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, server_side_encryption_configuration: Optional[pulumi.Input[pulumi.InputType['DomainServerSideEncryptionConfigurationArgs']]] = None, tags: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DomainTagArgs']]]]] = None, __props__=None): """ The AWS::VoiceID::Domain resource specifies an Amazon VoiceID Domain. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. """ ... @overload def __init__(__self__, resource_name: str, args: DomainArgs, opts: Optional[pulumi.ResourceOptions] = None): """ The AWS::VoiceID::Domain resource specifies an Amazon VoiceID Domain. :param str resource_name: The name of the resource. :param DomainArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(DomainArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, description: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, server_side_encryption_configuration: Optional[pulumi.Input[pulumi.InputType['DomainServerSideEncryptionConfigurationArgs']]] = None, tags: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DomainTagArgs']]]]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = DomainArgs.__new__(DomainArgs) __props__.__dict__["description"] = description __props__.__dict__["name"] = name if server_side_encryption_configuration is None and not opts.urn: raise TypeError("Missing required property 'server_side_encryption_configuration'") __props__.__dict__["server_side_encryption_configuration"] = server_side_encryption_configuration __props__.__dict__["tags"] = tags __props__.__dict__["domain_id"] = None super(Domain, __self__).__init__( 'aws-native:voiceid:Domain', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'Domain': """ Get an existing Domain resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = DomainArgs.__new__(DomainArgs) __props__.__dict__["description"] = None __props__.__dict__["domain_id"] = None __props__.__dict__["name"] = None __props__.__dict__["server_side_encryption_configuration"] = None __props__.__dict__["tags"] = None return Domain(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter def description(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "description") @property @pulumi.getter(name="domainId") def domain_id(self) -> pulumi.Output[str]: return pulumi.get(self, "domain_id") @property @pulumi.getter def name(self) -> pulumi.Output[str]: return pulumi.get(self, "name") @property @pulumi.getter(name="serverSideEncryptionConfiguration") def server_side_encryption_configuration(self) -> pulumi.Output['outputs.DomainServerSideEncryptionConfiguration']: return pulumi.get(self, "server_side_encryption_configuration") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Sequence['outputs.DomainTag']]]: return pulumi.get(self, "tags")
sdk/python/pulumi_aws_native/voiceid/domain.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs import * __all__ = ['DomainArgs', 'Domain'] @pulumi.input_type class DomainArgs: def __init__(__self__, *, server_side_encryption_configuration: pulumi.Input['DomainServerSideEncryptionConfigurationArgs'], description: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Sequence[pulumi.Input['DomainTagArgs']]]] = None): """ The set of arguments for constructing a Domain resource. """ pulumi.set(__self__, "server_side_encryption_configuration", server_side_encryption_configuration) if description is not None: pulumi.set(__self__, "description", description) if name is not None: pulumi.set(__self__, "name", name) if tags is not None: pulumi.set(__self__, "tags", tags) @property @pulumi.getter(name="serverSideEncryptionConfiguration") def server_side_encryption_configuration(self) -> pulumi.Input['DomainServerSideEncryptionConfigurationArgs']: return pulumi.get(self, "server_side_encryption_configuration") @server_side_encryption_configuration.setter def server_side_encryption_configuration(self, value: pulumi.Input['DomainServerSideEncryptionConfigurationArgs']): pulumi.set(self, "server_side_encryption_configuration", value) @property @pulumi.getter def description(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "description") @description.setter def description(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "description", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['DomainTagArgs']]]]: return pulumi.get(self, "tags") @tags.setter def tags(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['DomainTagArgs']]]]): pulumi.set(self, "tags", value) class Domain(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, description: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, server_side_encryption_configuration: Optional[pulumi.Input[pulumi.InputType['DomainServerSideEncryptionConfigurationArgs']]] = None, tags: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DomainTagArgs']]]]] = None, __props__=None): """ The AWS::VoiceID::Domain resource specifies an Amazon VoiceID Domain. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. """ ... @overload def __init__(__self__, resource_name: str, args: DomainArgs, opts: Optional[pulumi.ResourceOptions] = None): """ The AWS::VoiceID::Domain resource specifies an Amazon VoiceID Domain. :param str resource_name: The name of the resource. :param DomainArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(DomainArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, description: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, server_side_encryption_configuration: Optional[pulumi.Input[pulumi.InputType['DomainServerSideEncryptionConfigurationArgs']]] = None, tags: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DomainTagArgs']]]]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = DomainArgs.__new__(DomainArgs) __props__.__dict__["description"] = description __props__.__dict__["name"] = name if server_side_encryption_configuration is None and not opts.urn: raise TypeError("Missing required property 'server_side_encryption_configuration'") __props__.__dict__["server_side_encryption_configuration"] = server_side_encryption_configuration __props__.__dict__["tags"] = tags __props__.__dict__["domain_id"] = None super(Domain, __self__).__init__( 'aws-native:voiceid:Domain', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'Domain': """ Get an existing Domain resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = DomainArgs.__new__(DomainArgs) __props__.__dict__["description"] = None __props__.__dict__["domain_id"] = None __props__.__dict__["name"] = None __props__.__dict__["server_side_encryption_configuration"] = None __props__.__dict__["tags"] = None return Domain(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter def description(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "description") @property @pulumi.getter(name="domainId") def domain_id(self) -> pulumi.Output[str]: return pulumi.get(self, "domain_id") @property @pulumi.getter def name(self) -> pulumi.Output[str]: return pulumi.get(self, "name") @property @pulumi.getter(name="serverSideEncryptionConfiguration") def server_side_encryption_configuration(self) -> pulumi.Output['outputs.DomainServerSideEncryptionConfiguration']: return pulumi.get(self, "server_side_encryption_configuration") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Sequence['outputs.DomainTag']]]: return pulumi.get(self, "tags")
0.861684
0.0584
import pygame as pg import numpy as np import pickle import time import itertools from multiprocessing import Pipe, Process from importlib import reload import user_settings as cng from states import state_config as state_cng from instances import instance_config as game_cng from states import state from states import game_state from classes import spaceship from classes import projectile from classes import maps from images import images as imgs from instances import game_instances as game_i from instances import ui_instances as ui_i from server import network as net FRAME_TIME = 1/cng.fps COLORS = pg.colordict.THECOLORS def handshake(bridge, ship): ''' Initialize handshake with server This function returns the client_id (int) ''' out_data = pickle.dumps(ship) bridge.send(out_data) client_id = pickle.loads(bridge.recv(state_cng.recv_size)) return client_id def server_comm_protocol(bridge, pipe, ship, bullets): ''' Stands for server communication protocoll. This function handles the client-server communication, and is meant to be run by a parallell process to reduce in-game stuttering. ''' # TODO: Contemplate buffersize, should at least be 16kb recv_size = 1024*32 bridge.client_socket.settimeout(5.0) while True: try: kill_signal, ship, bullets = pipe.recv() if(kill_signal): pipe.close() return data_to_send = pickle.dumps([ship, bullets]) bridge.send(data_to_send) try: all_ships, all_bullets, planets, asteroids = pickle.loads(bridge.recv(state_cng.recv_size)) except: pass all_bullets = list(itertools.chain.from_iterable(all_bullets)) pipe.send([all_ships, all_bullets, planets, asteroids]) except: print("Client comm process terminated") pipe.send([0,0,0,0]) pipe.close() return class mayhem(game_state.mayhem): ''' Multiplayer (LAN) mayhem class, inherits the single-player mayhem class and is meant to be a part of a state machine. ''' def __init__(self, MANAGER, WINDOW): super().__init__(MANAGER, WINDOW) def init_attributes(self): '''Helper method for initializing attributes, used for soft-reloading''' self.planets = [] self.asteroids = [] self.all_ships = [] self.bullets = [] self.ship = game_i.ship self.camera = np.array([self.w_shape[0], self.w_shape[1]])/2 - self.ship.pos self.show_refuel = False self.show_loading_ammo = False def update_graphics(self): ''' Blits and flips The objects does not contain any surface objects to be blitted and therefore needs to be given which image to blit. This is because the the objects should be lightweight (and you can't pickle surfaces anyways) in order to be sent to a server during an online session. ''' self.WINDOW.fill(self.bg_color) self.WINDOW.blit( imgs.bg_img, self.camera ) self.planets[0].draw(self.WINDOW, self.camera, imgs.earth_img) self.planets[1].draw(self.WINDOW, self.camera, imgs.venus_img) game_i.sun.draw(self.WINDOW, self.camera, imgs.sun_img) for ship in self.all_ships: ship.draw(self.WINDOW, self.camera, imgs.enemyship_img) for asteroid, img in zip(self.asteroids, imgs.asteroid_imgs): asteroid.draw(self.WINDOW, self.camera, img) for bullet in self.all_bullets: bullet.draw(self.WINDOW, self.camera, imgs.bullet_img) self.ship.draw( self.WINDOW, self.camera, imgs.ship_img ) self.minimap.draw( WINDOW=self.WINDOW, colors=game_i.minimap_colors_online, sizes=game_i.minimap_sizes_online, bullets=self.all_bullets, sun=[game_i.sun], celestials=self.planets, asteroids=self.asteroids, others=self.all_ships, ) self.minimap.draw_player( self.WINDOW, game_i.ship, 2 ) for text in ui_i.indicators: text.draw(self.WINDOW) pg.display.update() def logic(self): ''' Method for handling logic ''' self.ship.update(self) for bullet in self.bullets: bullet.update(self) bullet.interact_ship(self.all_ships, self.bullets) def parallell_comm_protocol(self, pipe): ''' Stands for parallell communication protocoll, and is the function that is meant to be called from the main process to communicate with the parallell process via a pipe. ''' self.all_ships, self.all_bullets, self.planets, self.asteroids = pipe.recv() if self.all_ships == 0: return 0 del(self.all_ships[self.client_id]) self.all_ships = list(self.all_ships.values()) return 1 def run(self): ''' The "main" loop ''' self.socket = net.Network() # If socket fails to connect to server if not self.socket.connect(): self._active = False return self.MANAGER.get_state('main_menu') state_pipe, comm_pipe = Pipe() self.client_id = handshake(self.socket, self.ship) print(f"Client id = {self.client_id}") # Run server communication protocol in separate process p = Process(target=server_comm_protocol, args=(self.socket, comm_pipe, self.ship, self.bullets)) p.start() while(self._active): state_pipe.send((0, self.ship, self.bullets)) if not self.parallell_comm_protocol(state_pipe): self._active = False self.next_state = self.MANAGER.get_state('main_menu') break self.dt = self.clock.tick(cng.fps) # TODO: Check if this works properly for high fps self.lag_correction = self.dt/self.target_timestep self.update_graphics() self.update_user_input() self.logic() # This needs to be below update graphics for some reason self.animations() # Terminate parallell process by telling it to kill itself state_pipe.send((1, None, None)) self.socket.client_socket.close() p.join() # p.close happens automatically during garbage collection, and using p.close raises attribute error for some computers # p.close() return self.next_state
states/game_state_online.py
import pygame as pg import numpy as np import pickle import time import itertools from multiprocessing import Pipe, Process from importlib import reload import user_settings as cng from states import state_config as state_cng from instances import instance_config as game_cng from states import state from states import game_state from classes import spaceship from classes import projectile from classes import maps from images import images as imgs from instances import game_instances as game_i from instances import ui_instances as ui_i from server import network as net FRAME_TIME = 1/cng.fps COLORS = pg.colordict.THECOLORS def handshake(bridge, ship): ''' Initialize handshake with server This function returns the client_id (int) ''' out_data = pickle.dumps(ship) bridge.send(out_data) client_id = pickle.loads(bridge.recv(state_cng.recv_size)) return client_id def server_comm_protocol(bridge, pipe, ship, bullets): ''' Stands for server communication protocoll. This function handles the client-server communication, and is meant to be run by a parallell process to reduce in-game stuttering. ''' # TODO: Contemplate buffersize, should at least be 16kb recv_size = 1024*32 bridge.client_socket.settimeout(5.0) while True: try: kill_signal, ship, bullets = pipe.recv() if(kill_signal): pipe.close() return data_to_send = pickle.dumps([ship, bullets]) bridge.send(data_to_send) try: all_ships, all_bullets, planets, asteroids = pickle.loads(bridge.recv(state_cng.recv_size)) except: pass all_bullets = list(itertools.chain.from_iterable(all_bullets)) pipe.send([all_ships, all_bullets, planets, asteroids]) except: print("Client comm process terminated") pipe.send([0,0,0,0]) pipe.close() return class mayhem(game_state.mayhem): ''' Multiplayer (LAN) mayhem class, inherits the single-player mayhem class and is meant to be a part of a state machine. ''' def __init__(self, MANAGER, WINDOW): super().__init__(MANAGER, WINDOW) def init_attributes(self): '''Helper method for initializing attributes, used for soft-reloading''' self.planets = [] self.asteroids = [] self.all_ships = [] self.bullets = [] self.ship = game_i.ship self.camera = np.array([self.w_shape[0], self.w_shape[1]])/2 - self.ship.pos self.show_refuel = False self.show_loading_ammo = False def update_graphics(self): ''' Blits and flips The objects does not contain any surface objects to be blitted and therefore needs to be given which image to blit. This is because the the objects should be lightweight (and you can't pickle surfaces anyways) in order to be sent to a server during an online session. ''' self.WINDOW.fill(self.bg_color) self.WINDOW.blit( imgs.bg_img, self.camera ) self.planets[0].draw(self.WINDOW, self.camera, imgs.earth_img) self.planets[1].draw(self.WINDOW, self.camera, imgs.venus_img) game_i.sun.draw(self.WINDOW, self.camera, imgs.sun_img) for ship in self.all_ships: ship.draw(self.WINDOW, self.camera, imgs.enemyship_img) for asteroid, img in zip(self.asteroids, imgs.asteroid_imgs): asteroid.draw(self.WINDOW, self.camera, img) for bullet in self.all_bullets: bullet.draw(self.WINDOW, self.camera, imgs.bullet_img) self.ship.draw( self.WINDOW, self.camera, imgs.ship_img ) self.minimap.draw( WINDOW=self.WINDOW, colors=game_i.minimap_colors_online, sizes=game_i.minimap_sizes_online, bullets=self.all_bullets, sun=[game_i.sun], celestials=self.planets, asteroids=self.asteroids, others=self.all_ships, ) self.minimap.draw_player( self.WINDOW, game_i.ship, 2 ) for text in ui_i.indicators: text.draw(self.WINDOW) pg.display.update() def logic(self): ''' Method for handling logic ''' self.ship.update(self) for bullet in self.bullets: bullet.update(self) bullet.interact_ship(self.all_ships, self.bullets) def parallell_comm_protocol(self, pipe): ''' Stands for parallell communication protocoll, and is the function that is meant to be called from the main process to communicate with the parallell process via a pipe. ''' self.all_ships, self.all_bullets, self.planets, self.asteroids = pipe.recv() if self.all_ships == 0: return 0 del(self.all_ships[self.client_id]) self.all_ships = list(self.all_ships.values()) return 1 def run(self): ''' The "main" loop ''' self.socket = net.Network() # If socket fails to connect to server if not self.socket.connect(): self._active = False return self.MANAGER.get_state('main_menu') state_pipe, comm_pipe = Pipe() self.client_id = handshake(self.socket, self.ship) print(f"Client id = {self.client_id}") # Run server communication protocol in separate process p = Process(target=server_comm_protocol, args=(self.socket, comm_pipe, self.ship, self.bullets)) p.start() while(self._active): state_pipe.send((0, self.ship, self.bullets)) if not self.parallell_comm_protocol(state_pipe): self._active = False self.next_state = self.MANAGER.get_state('main_menu') break self.dt = self.clock.tick(cng.fps) # TODO: Check if this works properly for high fps self.lag_correction = self.dt/self.target_timestep self.update_graphics() self.update_user_input() self.logic() # This needs to be below update graphics for some reason self.animations() # Terminate parallell process by telling it to kill itself state_pipe.send((1, None, None)) self.socket.client_socket.close() p.join() # p.close happens automatically during garbage collection, and using p.close raises attribute error for some computers # p.close() return self.next_state
0.169922
0.106412
import os import re try: from maya import mel from maya import cmds isMaya = True except ImportError: isMaya = False def onMayaDroppedPythonFile(*args, **kwargs): pass def _onMayaDropped(): if isMaya: main() def getNamePathLang(dir): dirItemList = os.listdir(dir) namePathLang = [] for dirItem in dirItemList: if dirItem.endswith(".py"): namePathLang.append([dirItem.split(".")[0], os.path.join(dir, dirItem), "python"]) if dirItem.endswith(".mel"): namePathLang.append([dirItem.split(".")[0], os.path.join(dir, dirItem), "mel"]) return namePathLang def getCommand(scriptPath): with open(scriptPath, "r") as f: data = f.read() return data def getCurrentDir(): currentDir = os.path.dirname(__file__) return currentDir def getRunTimeCommandDir(): runTimeCommandDir = os.path.join(getCurrentDir(), "scripts", "runTimeCommand") return runTimeCommandDir def getShelfDir(): shelfDir = os.path.join(getCurrentDir(), "scripts", "shelf") return shelfDir def createUpdateRunTimeCommand(): runTimeCommandNamePathLangs = getNamePathLang(getRunTimeCommandDir()) runTimeCommandNamePathLangs.sort() updatedMsg = "\nUpdated...\n\n" createdMsg = "\nCreated...\n\n" for runTimeCommandNamePathLang in runTimeCommandNamePathLangs: name, path, commandLanguage = runTimeCommandNamePathLang if cmds.runTimeCommand(name, q=True, exists=True): cmds.runTimeCommand(name, e=True, delete=True) cmds.runTimeCommand(name, category="Custom Scripts", commandLanguage=commandLanguage, command=getCommand(path)) updatedMsg += "'{}' runtime command\n".format(name) else: cmds.runTimeCommand(name, category="Custom Scripts", commandLanguage=commandLanguage, command=getCommand(path)) cmds.nameCommand(name+"NameCommand", annotation=name+"NameCommand", sourceType="mel", command=name) createdMsg += "'{}' runtime command.\n".format(name) cmds.confirmDialog(title="Run Time Command Results",message="{0}\n-----------------------\n{1}".format(updatedMsg, createdMsg)) def camel_case_split(str): """ e.g. str = "mayaMatchmoveTools" >> ['maya', 'Matchmove', 'Tools'] e.g. str = "MayaMatchmoveTools" >> ['Maya', 'Matchmove', 'Tools'] """ return re.findall(r'[a-zA-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))', str) def labelfy(name): strings = camel_case_split(name) labelName = '\n\n' + '\n'.join(strings) return labelName def _null(*args): pass class _shelf(): '''A simple class to build shelves in maya. Since the build method is empty, it should be extended by the derived class to build the necessary shelf elements. By default it creates an empty shelf called "customShelf".''' def __init__(self, name="hkTools", iconPath=""): self.name = name self.iconPath = iconPath self.labelBackground = (.1, .1, .1, 1) self.labelColour = (.9, .9, .9) self._cleanOldShelf() cmds.setParent(self.name) self.build() def build(self): '''This method should be overwritten in derived classes to actually build the shelf elements. Otherwise, nothing is added to the shelf.''' pass def addButon(self, label, icon="commandButton.png", command=_null, doubleCommand=_null, sourceType=_null, olb=(.1, .1, .1, 1) ,olc=(.9, .9, .9)): '''Adds a shelf button with the specified label, command, double click command and image.''' cmds.setParent(self.name) if icon: icon = self.iconPath + icon cmds.shelfButton(image=icon, l=label, command=command, dcc=doubleCommand, imageOverlayLabel=label, olb=olb, olc=olc, stp=sourceType, noDefaultPopup=True) def addSeparator(self): cmds.separator(enable=True, width=24, height=31, manage=True, visible=True, style="shelf", horizontal=False) def addMenuItem(self, parent, label, command=_null, icon=""): '''Adds a shelf button with the specified label, command, double click command and image.''' if icon: icon = self.iconPath + icon return cmds.menuItem(p=parent, l=label, c=command, i="") def addSubMenu(self, parent, label, icon=None): '''Adds a sub menu item with the specified label and icon to the specified parent popup menu.''' if icon: icon = self.iconPath + icon return cmds.menuItem(p=parent, l=label, i=icon, subMenu=1) def _cleanOldShelf(self): '''Checks if the shelf exists and empties it if it does or creates it if it does not.''' if cmds.shelfLayout(self.name, ex=1): if cmds.shelfLayout(self.name, q=1, ca=1): for each in cmds.shelfLayout(self.name, q=1, ca=1): cmds.deleteUI(each) else: cmds.shelfLayout(self.name, p="ShelfLayout") class customShelf(_shelf): def build(self): self.shelfNamePathLangs = getNamePathLang(getShelfDir()) self.shelfNamePathLangs.sort() for shelfNamePathLang in self.shelfNamePathLangs: name, path, commandLanguage = shelfNamePathLang labelName = labelfy(name).upper() if self.shelfNamePathLangs.index(shelfNamePathLang) % 2 == 0: self.addButon(label=labelName, sourceType=commandLanguage, command=getCommand(path), olb=(.1, .1, .1, 1), olc=(.9, .9, .9)) else: self.addButon(label=labelName, sourceType=commandLanguage, command=getCommand(path), olb=(.9, .9, .9, 1), olc=(.1, .1, .1)) # Add shelf buttons manually from this point... self.addSeparator() # Add separator self.addButon(label="", icon="parentConstraint.png", sourceType="mel", command="ParentConstraintOptions") self.addButon(label="", icon="posConstraint.png", sourceType="mel", command="PointConstraintOptions") self.addButon(label="", icon="orientConstraint.png", sourceType="mel", command="OrientConstraintOptions") self.addSeparator() self.addButon(label="", icon="motionTrail.png", sourceType="mel", command="CreateMotionTrailOptions") self.addButon(label="", icon="bakeAnimation.png", sourceType="mel", command="BakeSimulationOptions") self.addSeparator() self.addButon(label="", icon="locator.png", sourceType="mel", command="CreateLocator") self.addButon(label="", icon="cluster.png", sourceType="mel", command="CreateClusterOptions") def createUpdateShelf(): customShelf() def createUpdateHotkey(): # Returns all available hotkey sets in Maya hotkeySetList = cmds.hotkeySet( q=True, hotkeySetArray=True ) # Delete old hkTools hotkey set if "hkTools" in hotkeySetList: cmds.hotkeySet( "hkTools", edit=True, delete=True ) # Import hkTools hotkey set hkTools_mhk_filepath = os.path.join(getCurrentDir(), "hkTools.mhk") cmds.hotkeySet( e=True, ip=hkTools_mhk_filepath ) def main(): createUpdateRunTimeCommand() createUpdateShelf() createUpdateHotkey()
hkTools.py
import os import re try: from maya import mel from maya import cmds isMaya = True except ImportError: isMaya = False def onMayaDroppedPythonFile(*args, **kwargs): pass def _onMayaDropped(): if isMaya: main() def getNamePathLang(dir): dirItemList = os.listdir(dir) namePathLang = [] for dirItem in dirItemList: if dirItem.endswith(".py"): namePathLang.append([dirItem.split(".")[0], os.path.join(dir, dirItem), "python"]) if dirItem.endswith(".mel"): namePathLang.append([dirItem.split(".")[0], os.path.join(dir, dirItem), "mel"]) return namePathLang def getCommand(scriptPath): with open(scriptPath, "r") as f: data = f.read() return data def getCurrentDir(): currentDir = os.path.dirname(__file__) return currentDir def getRunTimeCommandDir(): runTimeCommandDir = os.path.join(getCurrentDir(), "scripts", "runTimeCommand") return runTimeCommandDir def getShelfDir(): shelfDir = os.path.join(getCurrentDir(), "scripts", "shelf") return shelfDir def createUpdateRunTimeCommand(): runTimeCommandNamePathLangs = getNamePathLang(getRunTimeCommandDir()) runTimeCommandNamePathLangs.sort() updatedMsg = "\nUpdated...\n\n" createdMsg = "\nCreated...\n\n" for runTimeCommandNamePathLang in runTimeCommandNamePathLangs: name, path, commandLanguage = runTimeCommandNamePathLang if cmds.runTimeCommand(name, q=True, exists=True): cmds.runTimeCommand(name, e=True, delete=True) cmds.runTimeCommand(name, category="Custom Scripts", commandLanguage=commandLanguage, command=getCommand(path)) updatedMsg += "'{}' runtime command\n".format(name) else: cmds.runTimeCommand(name, category="Custom Scripts", commandLanguage=commandLanguage, command=getCommand(path)) cmds.nameCommand(name+"NameCommand", annotation=name+"NameCommand", sourceType="mel", command=name) createdMsg += "'{}' runtime command.\n".format(name) cmds.confirmDialog(title="Run Time Command Results",message="{0}\n-----------------------\n{1}".format(updatedMsg, createdMsg)) def camel_case_split(str): """ e.g. str = "mayaMatchmoveTools" >> ['maya', 'Matchmove', 'Tools'] e.g. str = "MayaMatchmoveTools" >> ['Maya', 'Matchmove', 'Tools'] """ return re.findall(r'[a-zA-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))', str) def labelfy(name): strings = camel_case_split(name) labelName = '\n\n' + '\n'.join(strings) return labelName def _null(*args): pass class _shelf(): '''A simple class to build shelves in maya. Since the build method is empty, it should be extended by the derived class to build the necessary shelf elements. By default it creates an empty shelf called "customShelf".''' def __init__(self, name="hkTools", iconPath=""): self.name = name self.iconPath = iconPath self.labelBackground = (.1, .1, .1, 1) self.labelColour = (.9, .9, .9) self._cleanOldShelf() cmds.setParent(self.name) self.build() def build(self): '''This method should be overwritten in derived classes to actually build the shelf elements. Otherwise, nothing is added to the shelf.''' pass def addButon(self, label, icon="commandButton.png", command=_null, doubleCommand=_null, sourceType=_null, olb=(.1, .1, .1, 1) ,olc=(.9, .9, .9)): '''Adds a shelf button with the specified label, command, double click command and image.''' cmds.setParent(self.name) if icon: icon = self.iconPath + icon cmds.shelfButton(image=icon, l=label, command=command, dcc=doubleCommand, imageOverlayLabel=label, olb=olb, olc=olc, stp=sourceType, noDefaultPopup=True) def addSeparator(self): cmds.separator(enable=True, width=24, height=31, manage=True, visible=True, style="shelf", horizontal=False) def addMenuItem(self, parent, label, command=_null, icon=""): '''Adds a shelf button with the specified label, command, double click command and image.''' if icon: icon = self.iconPath + icon return cmds.menuItem(p=parent, l=label, c=command, i="") def addSubMenu(self, parent, label, icon=None): '''Adds a sub menu item with the specified label and icon to the specified parent popup menu.''' if icon: icon = self.iconPath + icon return cmds.menuItem(p=parent, l=label, i=icon, subMenu=1) def _cleanOldShelf(self): '''Checks if the shelf exists and empties it if it does or creates it if it does not.''' if cmds.shelfLayout(self.name, ex=1): if cmds.shelfLayout(self.name, q=1, ca=1): for each in cmds.shelfLayout(self.name, q=1, ca=1): cmds.deleteUI(each) else: cmds.shelfLayout(self.name, p="ShelfLayout") class customShelf(_shelf): def build(self): self.shelfNamePathLangs = getNamePathLang(getShelfDir()) self.shelfNamePathLangs.sort() for shelfNamePathLang in self.shelfNamePathLangs: name, path, commandLanguage = shelfNamePathLang labelName = labelfy(name).upper() if self.shelfNamePathLangs.index(shelfNamePathLang) % 2 == 0: self.addButon(label=labelName, sourceType=commandLanguage, command=getCommand(path), olb=(.1, .1, .1, 1), olc=(.9, .9, .9)) else: self.addButon(label=labelName, sourceType=commandLanguage, command=getCommand(path), olb=(.9, .9, .9, 1), olc=(.1, .1, .1)) # Add shelf buttons manually from this point... self.addSeparator() # Add separator self.addButon(label="", icon="parentConstraint.png", sourceType="mel", command="ParentConstraintOptions") self.addButon(label="", icon="posConstraint.png", sourceType="mel", command="PointConstraintOptions") self.addButon(label="", icon="orientConstraint.png", sourceType="mel", command="OrientConstraintOptions") self.addSeparator() self.addButon(label="", icon="motionTrail.png", sourceType="mel", command="CreateMotionTrailOptions") self.addButon(label="", icon="bakeAnimation.png", sourceType="mel", command="BakeSimulationOptions") self.addSeparator() self.addButon(label="", icon="locator.png", sourceType="mel", command="CreateLocator") self.addButon(label="", icon="cluster.png", sourceType="mel", command="CreateClusterOptions") def createUpdateShelf(): customShelf() def createUpdateHotkey(): # Returns all available hotkey sets in Maya hotkeySetList = cmds.hotkeySet( q=True, hotkeySetArray=True ) # Delete old hkTools hotkey set if "hkTools" in hotkeySetList: cmds.hotkeySet( "hkTools", edit=True, delete=True ) # Import hkTools hotkey set hkTools_mhk_filepath = os.path.join(getCurrentDir(), "hkTools.mhk") cmds.hotkeySet( e=True, ip=hkTools_mhk_filepath ) def main(): createUpdateRunTimeCommand() createUpdateShelf() createUpdateHotkey()
0.477067
0.096153
import cv2, math, string, numpy image = cv2.imread('test_resize.png', -1) image = numpy.array(image).tolist() digits = string.digits + string.ascii_letters #generic helper functions def dictToArr(dictionary): arr = [None]*len(dictionary) for d in dictionary: arr[dictionary[d]-1] = d return arr def pixelsPerChar(base): if base == 2: return 8 if base < 13: return 4 if base < 180: return 2 return 1 def getHex(color): r = str(hex(color[2]).split('x')[-1]) if len(r) == 1: r = '0'+r g = str(hex(color[1]).split('x')[-1]) if len(g) == 1: g = '0'+g b = str(hex(color[0]).split('x')[-1]) if len(b) == 1: b = '0'+b return r+g+b def isTransparent(color): if len(color) == 3: return False if len(color) == 4 and color[3] == 255: return False return True def fillImage(image, tile_size=8): rows = len(image) cols = len(image[0]) rows_needed = rows//tile_size cols_needed = cols//tile_size #fill columns for row in image: for col in range(cols_needed): row.append([0,0,0,0]) #fill rows empty_row = [] for col in range(cols+cols_needed): empty_row.append([0,0,0,0]) for row in range(rows_needed): image.append(empty_row) def convertImageToHex(image): hex_image = list() for row in image: hex_row = list() for col in row: if isTransparent(col): hex_row.append(0) else: hex_row.append(getHex(col)) hex_image.append(hex_row) return hex_image #worker helper functions def createColorDict(image): color_dict = dict() counter = 1 for row in image: for col in row: if col != 0 and col not in color_dict: color_dict[col] = counter counter += 1 return color_dict def createTileRow(image_row, colors, tile_size): tiles = [] for t in range(len(image_row[0])//tile_size): tiles.append([]) for i, row in enumerate(image_row): tile_row = list() for col_num, col in enumerate(row): color_index = 0 if col == 0 else colors[col] tile_row.append(color_index) if len(tile_row) == tile_size: index = col_num // tile_size tiles[index].append(tile_row) tile_row = [] return tiles def compressTile(tile, base): pixels_per_char = pixelsPerChar(base) compressed_tile = '' for row in tile: for i in range(0, 8, pixels_per_char): group = row[i:i+pixels_per_char] string = '' for el in group: string += str(el) compressed_tile += chr(int(string, base)+42) return compressed_tile def compressTiles(tiled_image, colors): base = len(colors)+1 tiles = list() for row in tiled_image: tile_row = list() for tile in row: compressed_tile = compressTile(tile, base) tile_row.append(compressed_tile) tiles.append(tile_row) return tiles def convertToTiles(image, colors, tile_size): converted = [] for row_num in range(0, len(image), tile_size): tile = createTileRow(image[row_num:row_num+tile_size], colors, tile_size) converted.append(tile) return converted #worker functions def createTileset(compressed_tiles, tile_size, compressed_factor): tiledict = dict() counter = 1 for row in compressed_tiles: for tile in row: if tile == '*'*(tile_size**2//4): continue if tile not in tiledict: tiledict[tile] = counter counter += 1 return tiledict def createBitmap(tiled_image, tiledict, base): bitmap = list() for tile_row in tiled_image: bit_row = list() for tile in tile_row: tile = compressTile(tile, base) if tile in tiledict: bit_row.append(tiledict[tile]) else: bit_row.append(0) bitmap.append(bit_row) return bitmap def convert(image, tile_size=8): fillImage(image) image = convertImageToHex(image) colors = createColorDict(image) compressed_factor = pixelsPerChar(len(colors)+1) tiled_image = convertToTiles(image, colors, tile_size) compressed_tiles = compressTiles(tiled_image, colors) tiledict = createTileset(compressed_tiles, tile_size, compressed_factor) tileset = dictToArr(tiledict) bitmap = createBitmap(tiled_image, tiledict, compressed_factor) image = { 'bitmap': bitmap, 'tileset': tileset, 'compressed_factor': compressed_factor, 'colors': colors } return image #run function newimage = convert(image, 8) for m in newimage: print(m, newimage[m])
pictobit.py
import cv2, math, string, numpy image = cv2.imread('test_resize.png', -1) image = numpy.array(image).tolist() digits = string.digits + string.ascii_letters #generic helper functions def dictToArr(dictionary): arr = [None]*len(dictionary) for d in dictionary: arr[dictionary[d]-1] = d return arr def pixelsPerChar(base): if base == 2: return 8 if base < 13: return 4 if base < 180: return 2 return 1 def getHex(color): r = str(hex(color[2]).split('x')[-1]) if len(r) == 1: r = '0'+r g = str(hex(color[1]).split('x')[-1]) if len(g) == 1: g = '0'+g b = str(hex(color[0]).split('x')[-1]) if len(b) == 1: b = '0'+b return r+g+b def isTransparent(color): if len(color) == 3: return False if len(color) == 4 and color[3] == 255: return False return True def fillImage(image, tile_size=8): rows = len(image) cols = len(image[0]) rows_needed = rows//tile_size cols_needed = cols//tile_size #fill columns for row in image: for col in range(cols_needed): row.append([0,0,0,0]) #fill rows empty_row = [] for col in range(cols+cols_needed): empty_row.append([0,0,0,0]) for row in range(rows_needed): image.append(empty_row) def convertImageToHex(image): hex_image = list() for row in image: hex_row = list() for col in row: if isTransparent(col): hex_row.append(0) else: hex_row.append(getHex(col)) hex_image.append(hex_row) return hex_image #worker helper functions def createColorDict(image): color_dict = dict() counter = 1 for row in image: for col in row: if col != 0 and col not in color_dict: color_dict[col] = counter counter += 1 return color_dict def createTileRow(image_row, colors, tile_size): tiles = [] for t in range(len(image_row[0])//tile_size): tiles.append([]) for i, row in enumerate(image_row): tile_row = list() for col_num, col in enumerate(row): color_index = 0 if col == 0 else colors[col] tile_row.append(color_index) if len(tile_row) == tile_size: index = col_num // tile_size tiles[index].append(tile_row) tile_row = [] return tiles def compressTile(tile, base): pixels_per_char = pixelsPerChar(base) compressed_tile = '' for row in tile: for i in range(0, 8, pixels_per_char): group = row[i:i+pixels_per_char] string = '' for el in group: string += str(el) compressed_tile += chr(int(string, base)+42) return compressed_tile def compressTiles(tiled_image, colors): base = len(colors)+1 tiles = list() for row in tiled_image: tile_row = list() for tile in row: compressed_tile = compressTile(tile, base) tile_row.append(compressed_tile) tiles.append(tile_row) return tiles def convertToTiles(image, colors, tile_size): converted = [] for row_num in range(0, len(image), tile_size): tile = createTileRow(image[row_num:row_num+tile_size], colors, tile_size) converted.append(tile) return converted #worker functions def createTileset(compressed_tiles, tile_size, compressed_factor): tiledict = dict() counter = 1 for row in compressed_tiles: for tile in row: if tile == '*'*(tile_size**2//4): continue if tile not in tiledict: tiledict[tile] = counter counter += 1 return tiledict def createBitmap(tiled_image, tiledict, base): bitmap = list() for tile_row in tiled_image: bit_row = list() for tile in tile_row: tile = compressTile(tile, base) if tile in tiledict: bit_row.append(tiledict[tile]) else: bit_row.append(0) bitmap.append(bit_row) return bitmap def convert(image, tile_size=8): fillImage(image) image = convertImageToHex(image) colors = createColorDict(image) compressed_factor = pixelsPerChar(len(colors)+1) tiled_image = convertToTiles(image, colors, tile_size) compressed_tiles = compressTiles(tiled_image, colors) tiledict = createTileset(compressed_tiles, tile_size, compressed_factor) tileset = dictToArr(tiledict) bitmap = createBitmap(tiled_image, tiledict, compressed_factor) image = { 'bitmap': bitmap, 'tileset': tileset, 'compressed_factor': compressed_factor, 'colors': colors } return image #run function newimage = convert(image, 8) for m in newimage: print(m, newimage[m])
0.227298
0.482917
from flask import Flask, request, redirect, session, url_for from fhirclient import client from fhirclient.models.medicationorder import MedicationOrder settings = { 'app_id': 'my_web_app' } application = app = Flask('wsgi') app.debug = True app.secret_key = 'khsathdnsthjre' # CHANGE ME def _save_state(state): session['state'] = state def _get_smart(): state = session.get('state') if state: return client.FHIRClient(state=state, save_func=_save_state) else: return client.FHIRClient(settings=settings, save_func=_save_state) def _get_prescriptions(smart): return MedicationOrder.where({'patient': smart.patient_id}).perform(smart.server).entry def _med_name(med): if med.text: return med.text if med.coding and med.coding[0].display: return med.coding[0].display return "Unnamed Medication(TM)" @app.route('/fhir-app/launch.html') def launch(): session.clear() iss = request.args.get('iss', '') if iss: settings.update({ 'api_base': iss, 'auth_type': 'oauth2', 'launch_token': request.args.get('launch', ''), 'redirect_uri': request.url.split('/fhir-app')[0] + url_for('authorize') }) smart = _get_smart() auth_url = smart.authorize_url return redirect(auth_url) fhirServiceUrl = request.args.get('fhirServiceUrl', '') if fhirServiceUrl: settings['api_base'] = fhirServiceUrl settings['patient_id'] = request.args.get('patientId', '') settings['auth_type'] = 'none' smart = _get_smart() redirect_url = request.url.split('/fhir-app')[0] + url_for('index') return redirect(redirect_url) # Heuston, we have a problem raise Exception("Launch sequence aborted") @app.route('/fhir-app/authorize.html') def authorize(): smart = _get_smart() smart.handle_callback(request.url) return redirect(url_for('index')) @app.route('/fhir-app/') def index(): smart = _get_smart() if smart.ready and smart.patient is not None: out = """<!DOCTYPE html> <html> <head><title>Sample REST App</title></head> <body> """ name = smart.human_name(smart.patient.name[0] if smart.patient.name and len(smart.patient.name) > 0 else 'Unknown') out += "<h1>Medications for <span id='name'>%s</span></h1>\n" % name out += "<ul id='med_list'>\n" prescriptions = _get_prescriptions(smart) for pres in prescriptions: med = pres.resource.medicationCodeableConcept out += '<li>%s</li>\n' % _med_name(med) out += """ </ul> </body> </html>""" return out if __name__ == '__main__': app.run(port=8000)
rest-app/app.py
from flask import Flask, request, redirect, session, url_for from fhirclient import client from fhirclient.models.medicationorder import MedicationOrder settings = { 'app_id': 'my_web_app' } application = app = Flask('wsgi') app.debug = True app.secret_key = 'khsathdnsthjre' # CHANGE ME def _save_state(state): session['state'] = state def _get_smart(): state = session.get('state') if state: return client.FHIRClient(state=state, save_func=_save_state) else: return client.FHIRClient(settings=settings, save_func=_save_state) def _get_prescriptions(smart): return MedicationOrder.where({'patient': smart.patient_id}).perform(smart.server).entry def _med_name(med): if med.text: return med.text if med.coding and med.coding[0].display: return med.coding[0].display return "Unnamed Medication(TM)" @app.route('/fhir-app/launch.html') def launch(): session.clear() iss = request.args.get('iss', '') if iss: settings.update({ 'api_base': iss, 'auth_type': 'oauth2', 'launch_token': request.args.get('launch', ''), 'redirect_uri': request.url.split('/fhir-app')[0] + url_for('authorize') }) smart = _get_smart() auth_url = smart.authorize_url return redirect(auth_url) fhirServiceUrl = request.args.get('fhirServiceUrl', '') if fhirServiceUrl: settings['api_base'] = fhirServiceUrl settings['patient_id'] = request.args.get('patientId', '') settings['auth_type'] = 'none' smart = _get_smart() redirect_url = request.url.split('/fhir-app')[0] + url_for('index') return redirect(redirect_url) # Heuston, we have a problem raise Exception("Launch sequence aborted") @app.route('/fhir-app/authorize.html') def authorize(): smart = _get_smart() smart.handle_callback(request.url) return redirect(url_for('index')) @app.route('/fhir-app/') def index(): smart = _get_smart() if smart.ready and smart.patient is not None: out = """<!DOCTYPE html> <html> <head><title>Sample REST App</title></head> <body> """ name = smart.human_name(smart.patient.name[0] if smart.patient.name and len(smart.patient.name) > 0 else 'Unknown') out += "<h1>Medications for <span id='name'>%s</span></h1>\n" % name out += "<ul id='med_list'>\n" prescriptions = _get_prescriptions(smart) for pres in prescriptions: med = pres.resource.medicationCodeableConcept out += '<li>%s</li>\n' % _med_name(med) out += """ </ul> </body> </html>""" return out if __name__ == '__main__': app.run(port=8000)
0.349533
0.050168
import numpy as np def relu(x): return np.maximum(0, x) def drelu(x): return 1 * (x > 0) def output_layer_activation(x): return x def output_layer_activation_derivative(x): return 1 class NeuralNet(): def __init__(self, X_train, y_train, hidden_layer, lr, epochs): self.W1 = np.random.randint(10, size = (hidden_layer, X_train.shape[1])) self.W2 = np.ones((hidden_layer, 3)) self.b = np.zeros(hidden_layer) self.learning_rate = lr self.epochs = epochs self.training_points = X_train self.ypoints = y_train def train(self, X, y): f1 = np.vectorize(relu) df1 = np.vectorize(drelu) # Forward propagation z1 = self.W1 @ X + self.b a1 = f1(z1) z2 = a1 @ self.W2 output = output_layer_activation(z2) # Backpropagation output_layer_error = (output - y) * output_layer_activation_derivative(z2) hidden_layer_error = np.multiply(self.W2 * output_layer_error, df1(z1)) # Gradients b_grad = hidden_layer_error W2_grad = (a1 * output_layer_error).T W1_grad = np.outer(hidden_layer_error, X) # Update the parameters self.b = self.b - self.learning_rate * b_grad self.W1 = self.W1 - self.learning_rate * W1_grad self.W2 = self.W2 - self.learning_rate * W2_grad def predict(self, X): f1 = np.vectorize(relu) z1 = self.W1 @ X + self.b a1 = f1(z1) z2 = self.W2 @ a1 activated_output = output_layer_activation(z2) return activated_output.item() def train_neural_network(self): for epoch in range(self.epochs): for x, y in zip(self.training_points, self.ypoints): self.train(x, y) def test_neural_network(self, X_test, y_test): y_pred = [] for point in X_test: y_pred.append(self.predict(point)) return np.mean(y_pred == y_test)
irisneuralnet.py
import numpy as np def relu(x): return np.maximum(0, x) def drelu(x): return 1 * (x > 0) def output_layer_activation(x): return x def output_layer_activation_derivative(x): return 1 class NeuralNet(): def __init__(self, X_train, y_train, hidden_layer, lr, epochs): self.W1 = np.random.randint(10, size = (hidden_layer, X_train.shape[1])) self.W2 = np.ones((hidden_layer, 3)) self.b = np.zeros(hidden_layer) self.learning_rate = lr self.epochs = epochs self.training_points = X_train self.ypoints = y_train def train(self, X, y): f1 = np.vectorize(relu) df1 = np.vectorize(drelu) # Forward propagation z1 = self.W1 @ X + self.b a1 = f1(z1) z2 = a1 @ self.W2 output = output_layer_activation(z2) # Backpropagation output_layer_error = (output - y) * output_layer_activation_derivative(z2) hidden_layer_error = np.multiply(self.W2 * output_layer_error, df1(z1)) # Gradients b_grad = hidden_layer_error W2_grad = (a1 * output_layer_error).T W1_grad = np.outer(hidden_layer_error, X) # Update the parameters self.b = self.b - self.learning_rate * b_grad self.W1 = self.W1 - self.learning_rate * W1_grad self.W2 = self.W2 - self.learning_rate * W2_grad def predict(self, X): f1 = np.vectorize(relu) z1 = self.W1 @ X + self.b a1 = f1(z1) z2 = self.W2 @ a1 activated_output = output_layer_activation(z2) return activated_output.item() def train_neural_network(self): for epoch in range(self.epochs): for x, y in zip(self.training_points, self.ypoints): self.train(x, y) def test_neural_network(self, X_test, y_test): y_pred = [] for point in X_test: y_pred.append(self.predict(point)) return np.mean(y_pred == y_test)
0.813498
0.354126
import json import logging import pathlib import shutil from django.core.mail import send_mail import environ import requests from admin_extension.models import Files from app_market.models import Catalog, Category, Good, MediaFiles, Seller from transliterate import translit from market_place_proj.celery import app logger = logging.getLogger('about_import') ROOT = environ.Path(__file__) - 2 IMPORT_NICE_DIRECTORY = ROOT + 'media/imports/nice/' IMPORT_PROBLEM_DIRECTORY = ROOT + 'media/imports/problem/' def moving_files(file, name_file, file_name, json_file, status): if status == 'nice': path = f'imports/nice/{name_file}' directory = IMPORT_NICE_DIRECTORY else: path = f'imports/problem/{name_file}' directory = IMPORT_PROBLEM_DIRECTORY Files.objects.filter(file_start=file.file_start).update( file_start=None, file_nice=path) pathlib.Path(directory).mkdir(parents=True, exist_ok=True) shutil.move(ROOT + file_name, directory + (json_file[0]['seller']['title_ru'] + name_file)) def open_images(urls): for url in urls: try: file_open = url.split('/')[-1] directory = ROOT + 'media/catalog/images/' pathlib.Path(directory).mkdir(parents=True, exist_ok=True) path = directory + file_open image = f'catalog/images/{file_open}' with open(path, 'wb') as file: try: file.write(requests.get(url).content) except BaseException as exc: logger.warning(msg=f'картинку {url} не удалось скачать, ошибка {exc}') return image except BaseException as exc: logger.warning(msg=f'картинка {url} не импортирована, ошибка {exc}') return None def create_good(goods, category, list_json_file): for good in goods: new_good = Catalog.objects.create( good=Good.objects.create( title=good['title'], title_ru=good['title'], title_en=translit(good['title'], language_code='ru', reversed=True), description=json.dumps(good['description'], ensure_ascii=False), description_ru=json.dumps(good['description'], ensure_ascii=False), description_en=json.dumps(translit(good['description'], language_code='ru', reversed=True), ensure_ascii=False), category=Category.objects.get_or_create(title=category['title'])[0], image=MediaFiles.objects.get_or_create( file=open_images(urls=[good['image']]))[0] ), seller=Seller.objects.get_or_create( title=list_json_file[0]['seller']['title_ru'], title_ru=list_json_file[0]['seller']['title_ru'], title_en=list_json_file[0]['seller']['title_en'], )[0], price=good['price'], count=good['count'], ) for image in good['files']: if image is not None: url = MediaFiles.objects.get_or_create(file=open_images(urls=[image]))[0] new_good.good.files.add(url) logger.log(msg=f'товар {good["title"]} импортирован') logger.log(msg=f'категория {category["title"]} импортирована') return True @app.task def import_file(email): for file in Files.objects.filter(file_start__isnull=False): file_name = f'media/{file.file_start}' name_file = file_name.split('/')[-1] if file_name.endswith('.json') is True: try: with open(file_name, 'r') as json_file: list_json_file = json.load(json_file) for _, categories in list_json_file[1].items(): for category in categories: if Category.objects.filter(title=category['title']).exists(): goods = category['goods'] create_good(goods, category, list_json_file) else: logger.error(msg=f'не стандартная категория {category["title"]} импорт не удался') moving_files(file=file, name_file=name_file, file_name=file_name, json_file=list_json_file, status='nice') logger.log(f'файл {name_file} импортирован') except BaseException as exc: logger.error(msg=f'при импорте файла {name_file} произошла ошибка {exc}') moving_files(file=file, name_file=name_file, file_name=file_name, json_file=list_json_file, status='problem') else: logger.error(msg=f'файл {name_file} должен быть в формате json, импорт не произведён') moving_files(file=file, name_file=name_file, file_name=file_name, json_file=list_json_file, status='problem') if email: send_mail( 'Импорт произведён', '<EMAIL>', [email], fail_silently=False, )
market_place_proj/admin_extension/tasks.py
import json import logging import pathlib import shutil from django.core.mail import send_mail import environ import requests from admin_extension.models import Files from app_market.models import Catalog, Category, Good, MediaFiles, Seller from transliterate import translit from market_place_proj.celery import app logger = logging.getLogger('about_import') ROOT = environ.Path(__file__) - 2 IMPORT_NICE_DIRECTORY = ROOT + 'media/imports/nice/' IMPORT_PROBLEM_DIRECTORY = ROOT + 'media/imports/problem/' def moving_files(file, name_file, file_name, json_file, status): if status == 'nice': path = f'imports/nice/{name_file}' directory = IMPORT_NICE_DIRECTORY else: path = f'imports/problem/{name_file}' directory = IMPORT_PROBLEM_DIRECTORY Files.objects.filter(file_start=file.file_start).update( file_start=None, file_nice=path) pathlib.Path(directory).mkdir(parents=True, exist_ok=True) shutil.move(ROOT + file_name, directory + (json_file[0]['seller']['title_ru'] + name_file)) def open_images(urls): for url in urls: try: file_open = url.split('/')[-1] directory = ROOT + 'media/catalog/images/' pathlib.Path(directory).mkdir(parents=True, exist_ok=True) path = directory + file_open image = f'catalog/images/{file_open}' with open(path, 'wb') as file: try: file.write(requests.get(url).content) except BaseException as exc: logger.warning(msg=f'картинку {url} не удалось скачать, ошибка {exc}') return image except BaseException as exc: logger.warning(msg=f'картинка {url} не импортирована, ошибка {exc}') return None def create_good(goods, category, list_json_file): for good in goods: new_good = Catalog.objects.create( good=Good.objects.create( title=good['title'], title_ru=good['title'], title_en=translit(good['title'], language_code='ru', reversed=True), description=json.dumps(good['description'], ensure_ascii=False), description_ru=json.dumps(good['description'], ensure_ascii=False), description_en=json.dumps(translit(good['description'], language_code='ru', reversed=True), ensure_ascii=False), category=Category.objects.get_or_create(title=category['title'])[0], image=MediaFiles.objects.get_or_create( file=open_images(urls=[good['image']]))[0] ), seller=Seller.objects.get_or_create( title=list_json_file[0]['seller']['title_ru'], title_ru=list_json_file[0]['seller']['title_ru'], title_en=list_json_file[0]['seller']['title_en'], )[0], price=good['price'], count=good['count'], ) for image in good['files']: if image is not None: url = MediaFiles.objects.get_or_create(file=open_images(urls=[image]))[0] new_good.good.files.add(url) logger.log(msg=f'товар {good["title"]} импортирован') logger.log(msg=f'категория {category["title"]} импортирована') return True @app.task def import_file(email): for file in Files.objects.filter(file_start__isnull=False): file_name = f'media/{file.file_start}' name_file = file_name.split('/')[-1] if file_name.endswith('.json') is True: try: with open(file_name, 'r') as json_file: list_json_file = json.load(json_file) for _, categories in list_json_file[1].items(): for category in categories: if Category.objects.filter(title=category['title']).exists(): goods = category['goods'] create_good(goods, category, list_json_file) else: logger.error(msg=f'не стандартная категория {category["title"]} импорт не удался') moving_files(file=file, name_file=name_file, file_name=file_name, json_file=list_json_file, status='nice') logger.log(f'файл {name_file} импортирован') except BaseException as exc: logger.error(msg=f'при импорте файла {name_file} произошла ошибка {exc}') moving_files(file=file, name_file=name_file, file_name=file_name, json_file=list_json_file, status='problem') else: logger.error(msg=f'файл {name_file} должен быть в формате json, импорт не произведён') moving_files(file=file, name_file=name_file, file_name=file_name, json_file=list_json_file, status='problem') if email: send_mail( 'Импорт произведён', '<EMAIL>', [email], fail_silently=False, )
0.17441
0.074534
import botocore from click.testing import CliRunner from s3_credentials.cli import cli import json import pytest from unittest.mock import call, Mock def test_whoami(mocker): boto3 = mocker.patch("boto3.client") boto3().get_user.return_value = {"User": {"username": "name"}} runner = CliRunner() with runner.isolated_filesystem(): result = runner.invoke(cli, ["whoami"]) assert result.exit_code == 0 assert json.loads(result.output) == {"username": "name"} @pytest.mark.parametrize( "option,expected", ( ("", '{\n "name": "one"\n}\n{\n "name": "two"\n}\n'), ( "--array", '[\n {\n "name": "one"\n },\n' ' {\n "name": "two"\n }\n]\n', ), ("--nl", '{"name": "one"}\n{"name": "two"}\n'), ), ) def test_list_users(mocker, option, expected): boto3 = mocker.patch("boto3.client") boto3().get_paginator().paginate.return_value = [ {"Users": [{"name": "one"}, {"name": "two"}]} ] runner = CliRunner() with runner.isolated_filesystem(): result = runner.invoke(cli, ["list-users"] + ([option] if option else [])) assert result.exit_code == 0 assert result.output == expected @pytest.mark.parametrize( "option,expected", ( ("", '{\n "name": "one"\n}\n{\n "name": "two"\n}\n'), ( "--array", '[\n {\n "name": "one"\n },\n' ' {\n "name": "two"\n }\n]\n', ), ("--nl", '{"name": "one"}\n{"name": "two"}\n'), ), ) def test_list_buckets(mocker, option, expected): boto3 = mocker.patch("boto3.client") boto3().list_buckets.return_value = {"Buckets": [{"name": "one"}, {"name": "two"}]} runner = CliRunner() with runner.isolated_filesystem(): result = runner.invoke(cli, ["list-buckets"] + ([option] if option else [])) assert result.exit_code == 0 assert result.output == expected CUSTOM_POLICY = '{"custom": "policy", "bucket": "$!BUCKET_NAME!$"}' READ_WRITE_POLICY = '{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": ["arn:aws:s3:::pytest-bucket-simonw-1"]}, {"Effect": "Allow", "Action": "s3:*Object", "Resource": ["arn:aws:s3:::pytest-bucket-simonw-1/*"]}]}' READ_ONLY_POLICY = '{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": ["arn:aws:s3:::pytest-bucket-simonw-1"]}, {"Effect": "Allow", "Action": "s3:GetObject*", "Resource": ["arn:aws:s3:::pytest-bucket-simonw-1/*"]}]}' WRITE_ONLY_POLICY = '{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": ["s3:PutObject"], "Resource": ["arn:aws:s3:::pytest-bucket-simonw-1/*"]}]}' @pytest.mark.parametrize( "options,use_policy_stdin,expected_policy,expected_name_fragment", ( ([], False, READ_WRITE_POLICY, "read-write"), (["--read-only"], False, READ_ONLY_POLICY, "read-only"), (["--write-only"], False, WRITE_ONLY_POLICY, "write-only"), (["--policy", "POLICYFILEPATH"], False, CUSTOM_POLICY, "custom"), (["--policy", "-"], True, CUSTOM_POLICY, "custom"), (["--policy", CUSTOM_POLICY], False, CUSTOM_POLICY, "custom"), ), ) def test_create( mocker, tmpdir, options, use_policy_stdin, expected_policy, expected_name_fragment ): boto3 = mocker.patch("boto3.client") boto3.return_value = Mock() boto3.return_value.create_access_key.return_value = { "AccessKey": { "AccessKeyId": "access", "SecretAccessKey": "secret", } } runner = CliRunner() with runner.isolated_filesystem(): filepath = str(tmpdir / "policy.json") open(filepath, "w").write(CUSTOM_POLICY) fixed_options = [ filepath if option == "POLICYFILEPATH" else option for option in options ] args = ["create", "pytest-bucket-simonw-1", "-c"] + fixed_options kwargs = {} if use_policy_stdin: kwargs["input"] = CUSTOM_POLICY result = runner.invoke(cli, args, **kwargs) assert result.exit_code == 0 assert result.output == ( "Attached policy s3.NAME_FRAGMENT.pytest-bucket-simonw-1 to user s3.NAME_FRAGMENT.pytest-bucket-simonw-1\n" "Created access key for user: s3.NAME_FRAGMENT.pytest-bucket-simonw-1\n" '{\n "AccessKeyId": "access",\n "SecretAccessKey": "secret"\n}\n' ).replace("NAME_FRAGMENT", expected_name_fragment) assert [str(c) for c in boto3.mock_calls] == [ "call('s3')", "call('iam')", "call().head_bucket(Bucket='pytest-bucket-simonw-1')", "call().get_user(UserName='s3.{}.pytest-bucket-simonw-1')".format( expected_name_fragment ), "call().put_user_policy(PolicyDocument='{}', PolicyName='s3.{}.pytest-bucket-simonw-1', UserName='s3.{}.pytest-bucket-simonw-1')".format( expected_policy.replace("$!BUCKET_NAME!$", "pytest-bucket-simonw-1"), expected_name_fragment, expected_name_fragment, ), "call().create_access_key(UserName='s3.{}.pytest-bucket-simonw-1')".format( expected_name_fragment ), ] def test_list_user_policies(mocker): boto3 = mocker.patch("boto3.client") boto3.return_value = Mock() boto3.return_value.get_user_policy.return_value = { "PolicyDocument": {"policy": "here"} } def get_paginator(type): m = Mock() if type == "list_users": m.paginate.return_value = [ {"Users": [{"UserName": "one"}, {"UserName": "two"}]} ] elif type == "list_user_policies": m.paginate.return_value = [{"PolicyNames": ["policy-one", "policy-two"]}] return m boto3().get_paginator.side_effect = get_paginator runner = CliRunner() with runner.isolated_filesystem(): result = runner.invoke(cli, ["list-user-policies"], catch_exceptions=False) assert result.exit_code == 0 assert result.output == ( "User: one\n" "PolicyName: policy-one\n" "{\n" ' "policy": "here"\n' "}\n" "PolicyName: policy-two\n" "{\n" ' "policy": "here"\n' "}\n" "User: two\n" "PolicyName: policy-one\n" "{\n" ' "policy": "here"\n' "}\n" "PolicyName: policy-two\n" "{\n" ' "policy": "here"\n' "}\n" ) assert boto3.mock_calls == [ call(), call("iam"), call().get_paginator("list_users"), call().get_paginator("list_user_policies"), call().get_user_policy(UserName="one", PolicyName="policy-one"), call().get_user_policy(UserName="one", PolicyName="policy-two"), call().get_user_policy(UserName="two", PolicyName="policy-one"), call().get_user_policy(UserName="two", PolicyName="policy-two"), ] def test_delete_user(mocker): boto3 = mocker.patch("boto3.client") boto3.return_value = Mock() boto3.return_value.get_user_policy.return_value = { "PolicyDocument": {"policy": "here"} } def get_paginator(type): m = Mock() if type == "list_access_keys": m.paginate.return_value = [ {"AccessKeyMetadata": [{"AccessKeyId": "one"}, {"AccessKeyId": "two"}]} ] elif type == "list_user_policies": m.paginate.return_value = [{"PolicyNames": ["policy-one"]}] return m boto3().get_paginator.side_effect = get_paginator runner = CliRunner() with runner.isolated_filesystem(): result = runner.invoke(cli, ["delete-user", "user-123"], catch_exceptions=False) assert result.exit_code == 0 assert result.output == ( "User: user-123\n" " Deleted policy: policy-one\n" " Deleted access key: one\n" " Deleted access key: two\n" " Deleted user\n" ) assert boto3.mock_calls == [ call(), call("iam"), call().get_paginator("list_user_policies"), call().get_paginator("list_access_keys"), call().delete_user_policy(UserName="user-123", PolicyName="policy-one"), call().delete_access_key(UserName="user-123", AccessKeyId="one"), call().delete_access_key(UserName="user-123", AccessKeyId="two"), call().delete_user(UserName="user-123"), ] @pytest.mark.parametrize( "strategy,expected_error", ( ("stdin", "Input contained invalid JSON"), ("filepath", "File contained invalid JSON"), ("string", "Invalid JSON string"), ), ) @pytest.mark.parametrize("use_valid_string", (True, False)) def test_verify_create_policy_option( tmpdir, mocker, strategy, expected_error, use_valid_string ): # Ensure "bucket does not exist" error to terminate after verification boto3 = mocker.patch("boto3.client") boto3.return_value.head_bucket.side_effect = botocore.exceptions.ClientError( error_response={}, operation_name="" ) if use_valid_string: content = '{"policy": "..."}' else: content = "{Invalid JSON" # Only used by strategy==filepath filepath = str(tmpdir / "policy.json") open(filepath, "w").write(content) runner = CliRunner() args = ["create", "my-bucket", "--policy"] kwargs = {} if strategy == "stdin": args.append("-") kwargs["input"] = content elif strategy == "filepath": args.append(filepath) elif strategy == "string": args.append(content) result = runner.invoke(cli, args, **kwargs) if use_valid_string: assert result.exit_code == 1 assert ( result.output == "Error: Bucket does not exist: my-bucket - try --create-bucket to create it\n" ) else: assert result.exit_code assert ( "Error: Invalid value for '--policy': {}".format(expected_error) in result.output )
tests/test_s3_credentials.py
import botocore from click.testing import CliRunner from s3_credentials.cli import cli import json import pytest from unittest.mock import call, Mock def test_whoami(mocker): boto3 = mocker.patch("boto3.client") boto3().get_user.return_value = {"User": {"username": "name"}} runner = CliRunner() with runner.isolated_filesystem(): result = runner.invoke(cli, ["whoami"]) assert result.exit_code == 0 assert json.loads(result.output) == {"username": "name"} @pytest.mark.parametrize( "option,expected", ( ("", '{\n "name": "one"\n}\n{\n "name": "two"\n}\n'), ( "--array", '[\n {\n "name": "one"\n },\n' ' {\n "name": "two"\n }\n]\n', ), ("--nl", '{"name": "one"}\n{"name": "two"}\n'), ), ) def test_list_users(mocker, option, expected): boto3 = mocker.patch("boto3.client") boto3().get_paginator().paginate.return_value = [ {"Users": [{"name": "one"}, {"name": "two"}]} ] runner = CliRunner() with runner.isolated_filesystem(): result = runner.invoke(cli, ["list-users"] + ([option] if option else [])) assert result.exit_code == 0 assert result.output == expected @pytest.mark.parametrize( "option,expected", ( ("", '{\n "name": "one"\n}\n{\n "name": "two"\n}\n'), ( "--array", '[\n {\n "name": "one"\n },\n' ' {\n "name": "two"\n }\n]\n', ), ("--nl", '{"name": "one"}\n{"name": "two"}\n'), ), ) def test_list_buckets(mocker, option, expected): boto3 = mocker.patch("boto3.client") boto3().list_buckets.return_value = {"Buckets": [{"name": "one"}, {"name": "two"}]} runner = CliRunner() with runner.isolated_filesystem(): result = runner.invoke(cli, ["list-buckets"] + ([option] if option else [])) assert result.exit_code == 0 assert result.output == expected CUSTOM_POLICY = '{"custom": "policy", "bucket": "$!BUCKET_NAME!$"}' READ_WRITE_POLICY = '{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": ["arn:aws:s3:::pytest-bucket-simonw-1"]}, {"Effect": "Allow", "Action": "s3:*Object", "Resource": ["arn:aws:s3:::pytest-bucket-simonw-1/*"]}]}' READ_ONLY_POLICY = '{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": ["arn:aws:s3:::pytest-bucket-simonw-1"]}, {"Effect": "Allow", "Action": "s3:GetObject*", "Resource": ["arn:aws:s3:::pytest-bucket-simonw-1/*"]}]}' WRITE_ONLY_POLICY = '{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": ["s3:PutObject"], "Resource": ["arn:aws:s3:::pytest-bucket-simonw-1/*"]}]}' @pytest.mark.parametrize( "options,use_policy_stdin,expected_policy,expected_name_fragment", ( ([], False, READ_WRITE_POLICY, "read-write"), (["--read-only"], False, READ_ONLY_POLICY, "read-only"), (["--write-only"], False, WRITE_ONLY_POLICY, "write-only"), (["--policy", "POLICYFILEPATH"], False, CUSTOM_POLICY, "custom"), (["--policy", "-"], True, CUSTOM_POLICY, "custom"), (["--policy", CUSTOM_POLICY], False, CUSTOM_POLICY, "custom"), ), ) def test_create( mocker, tmpdir, options, use_policy_stdin, expected_policy, expected_name_fragment ): boto3 = mocker.patch("boto3.client") boto3.return_value = Mock() boto3.return_value.create_access_key.return_value = { "AccessKey": { "AccessKeyId": "access", "SecretAccessKey": "secret", } } runner = CliRunner() with runner.isolated_filesystem(): filepath = str(tmpdir / "policy.json") open(filepath, "w").write(CUSTOM_POLICY) fixed_options = [ filepath if option == "POLICYFILEPATH" else option for option in options ] args = ["create", "pytest-bucket-simonw-1", "-c"] + fixed_options kwargs = {} if use_policy_stdin: kwargs["input"] = CUSTOM_POLICY result = runner.invoke(cli, args, **kwargs) assert result.exit_code == 0 assert result.output == ( "Attached policy s3.NAME_FRAGMENT.pytest-bucket-simonw-1 to user s3.NAME_FRAGMENT.pytest-bucket-simonw-1\n" "Created access key for user: s3.NAME_FRAGMENT.pytest-bucket-simonw-1\n" '{\n "AccessKeyId": "access",\n "SecretAccessKey": "secret"\n}\n' ).replace("NAME_FRAGMENT", expected_name_fragment) assert [str(c) for c in boto3.mock_calls] == [ "call('s3')", "call('iam')", "call().head_bucket(Bucket='pytest-bucket-simonw-1')", "call().get_user(UserName='s3.{}.pytest-bucket-simonw-1')".format( expected_name_fragment ), "call().put_user_policy(PolicyDocument='{}', PolicyName='s3.{}.pytest-bucket-simonw-1', UserName='s3.{}.pytest-bucket-simonw-1')".format( expected_policy.replace("$!BUCKET_NAME!$", "pytest-bucket-simonw-1"), expected_name_fragment, expected_name_fragment, ), "call().create_access_key(UserName='s3.{}.pytest-bucket-simonw-1')".format( expected_name_fragment ), ] def test_list_user_policies(mocker): boto3 = mocker.patch("boto3.client") boto3.return_value = Mock() boto3.return_value.get_user_policy.return_value = { "PolicyDocument": {"policy": "here"} } def get_paginator(type): m = Mock() if type == "list_users": m.paginate.return_value = [ {"Users": [{"UserName": "one"}, {"UserName": "two"}]} ] elif type == "list_user_policies": m.paginate.return_value = [{"PolicyNames": ["policy-one", "policy-two"]}] return m boto3().get_paginator.side_effect = get_paginator runner = CliRunner() with runner.isolated_filesystem(): result = runner.invoke(cli, ["list-user-policies"], catch_exceptions=False) assert result.exit_code == 0 assert result.output == ( "User: one\n" "PolicyName: policy-one\n" "{\n" ' "policy": "here"\n' "}\n" "PolicyName: policy-two\n" "{\n" ' "policy": "here"\n' "}\n" "User: two\n" "PolicyName: policy-one\n" "{\n" ' "policy": "here"\n' "}\n" "PolicyName: policy-two\n" "{\n" ' "policy": "here"\n' "}\n" ) assert boto3.mock_calls == [ call(), call("iam"), call().get_paginator("list_users"), call().get_paginator("list_user_policies"), call().get_user_policy(UserName="one", PolicyName="policy-one"), call().get_user_policy(UserName="one", PolicyName="policy-two"), call().get_user_policy(UserName="two", PolicyName="policy-one"), call().get_user_policy(UserName="two", PolicyName="policy-two"), ] def test_delete_user(mocker): boto3 = mocker.patch("boto3.client") boto3.return_value = Mock() boto3.return_value.get_user_policy.return_value = { "PolicyDocument": {"policy": "here"} } def get_paginator(type): m = Mock() if type == "list_access_keys": m.paginate.return_value = [ {"AccessKeyMetadata": [{"AccessKeyId": "one"}, {"AccessKeyId": "two"}]} ] elif type == "list_user_policies": m.paginate.return_value = [{"PolicyNames": ["policy-one"]}] return m boto3().get_paginator.side_effect = get_paginator runner = CliRunner() with runner.isolated_filesystem(): result = runner.invoke(cli, ["delete-user", "user-123"], catch_exceptions=False) assert result.exit_code == 0 assert result.output == ( "User: user-123\n" " Deleted policy: policy-one\n" " Deleted access key: one\n" " Deleted access key: two\n" " Deleted user\n" ) assert boto3.mock_calls == [ call(), call("iam"), call().get_paginator("list_user_policies"), call().get_paginator("list_access_keys"), call().delete_user_policy(UserName="user-123", PolicyName="policy-one"), call().delete_access_key(UserName="user-123", AccessKeyId="one"), call().delete_access_key(UserName="user-123", AccessKeyId="two"), call().delete_user(UserName="user-123"), ] @pytest.mark.parametrize( "strategy,expected_error", ( ("stdin", "Input contained invalid JSON"), ("filepath", "File contained invalid JSON"), ("string", "Invalid JSON string"), ), ) @pytest.mark.parametrize("use_valid_string", (True, False)) def test_verify_create_policy_option( tmpdir, mocker, strategy, expected_error, use_valid_string ): # Ensure "bucket does not exist" error to terminate after verification boto3 = mocker.patch("boto3.client") boto3.return_value.head_bucket.side_effect = botocore.exceptions.ClientError( error_response={}, operation_name="" ) if use_valid_string: content = '{"policy": "..."}' else: content = "{Invalid JSON" # Only used by strategy==filepath filepath = str(tmpdir / "policy.json") open(filepath, "w").write(content) runner = CliRunner() args = ["create", "my-bucket", "--policy"] kwargs = {} if strategy == "stdin": args.append("-") kwargs["input"] = content elif strategy == "filepath": args.append(filepath) elif strategy == "string": args.append(content) result = runner.invoke(cli, args, **kwargs) if use_valid_string: assert result.exit_code == 1 assert ( result.output == "Error: Bucket does not exist: my-bucket - try --create-bucket to create it\n" ) else: assert result.exit_code assert ( "Error: Invalid value for '--policy': {}".format(expected_error) in result.output )
0.416915
0.394726
# StatsTest must be imported first in order to get proper ndb monkeypatching. from stats.analysis import PatchsetReference from stats.trybot_stats import TrybotReference from stats.test.stats_test import StatsTest passed = 'JOB_SUCCEEDED' failed = 'JOB_FAILED' running = 'JOB_RUNNING' test_builder_ppp = { 'master': 'test_master_a', 'builder': 'test_builder_ppp', 'url': 'ppp', } test_builder_fff = { 'master': 'test_master_a', 'builder': 'test_builder_fff', 'url': 'fff', } test_builder_ffp = { 'master': 'test_master_b', 'builder': 'test_builder_ffp', 'url': 'ffp', } class TrybotStatsTest(StatsTest): # Keep this shorter than 24 records. Each record adds an hour of # virtual time, and the tests aggregate over a day. trybot_records = list(enumerate([ {'issue': 1, 'patchset': 1, 'action': 'patch_start'}, {'issue': 1, 'patchset': 1, 'action': 'verifier_jobs_update', 'jobs': { running: [test_builder_ppp, test_builder_fff, test_builder_ffp] }, }, {'issue': 1, 'patchset': 1, 'action': 'verifier_jobs_update', 'jobs': { passed: [test_builder_ppp], failed: [test_builder_fff, test_builder_ffp], }, }, {'issue': 1, 'patchset': 1, 'action': 'patch_stop'}, {'issue': 1, 'patchset': 1, 'action': 'patch_start'}, {'issue': 1, 'patchset': 1, 'action': 'verifier_jobs_update', 'jobs': { passed: [test_builder_ppp], failed: [test_builder_fff], }, }, {'issue': 1, 'patchset': 1, 'action': 'verifier_jobs_update', 'jobs': { failed: [test_builder_ffp, test_builder_fff], passed: [test_builder_ppp], }, }, {'issue': 1, 'patchset': 1, 'action': 'patch_stop'}, {'issue': 1, 'patchset': 1, 'action': 'patch_start'}, {'issue': 1, 'patchset': 1, 'action': 'verifier_jobs_update', 'jobs': { passed: [test_builder_ppp], failed: [test_builder_fff], passed: [test_builder_ffp], }, }, {'issue': 1, 'patchset': 1, 'action': 'patch_stop'}, ])) def test_trybot_false_reject_count(self): self.analyze_records(*self.trybot_records) self.assertEquals(self.create_count( name='trybot-test_builder_ppp-false-reject-count', description=('Number of false rejects by the test_builder_ppp trybot. ' 'This counts any failed runs that also had passing runs ' 'on the same patch.'), tally={PatchsetReference(1, 1): 0}, ), self.get_stats('trybot-test_builder_ppp-false-reject-count')) self.assertEquals(self.create_count( name='trybot-test_builder_fff-false-reject-count', description=('Number of false rejects by the test_builder_fff trybot. ' 'This counts any failed runs that also had passing runs ' 'on the same patch.'), tally={PatchsetReference(1, 1): 0}, ), self.get_stats('trybot-test_builder_fff-false-reject-count')) self.assertEquals(self.create_count( name='trybot-test_builder_ffp-false-reject-count', description=('Number of false rejects by the test_builder_ffp trybot. ' 'This counts any failed runs that also had passing runs ' 'on the same patch.'), tally={PatchsetReference(1, 1): 2}, ), self.get_stats('trybot-test_builder_ffp-false-reject-count')) self.assertEquals(self.create_count( name='trybot-false-reject-count', description=('Number of false rejects across all trybots. ' 'This counts any failed runs that also had passing runs ' 'on the same patch.'), tally={TrybotReference('test_master_b', 'test_builder_ffp'): 2}, ), self.get_stats('trybot-false-reject-count')) def test_trybot_failed_run_count(self): self.analyze_records(*self.trybot_records) self.assertEquals(self.create_count( name='trybot-test_builder_ppp-fail-count', description = 'Number of failing runs by the test_builder_ppp trybot.', tally={PatchsetReference(1, 1): 0}, ), self.get_stats('trybot-test_builder_ppp-fail-count')) self.assertEquals(self.create_count( name='trybot-test_builder_fff-fail-count', description = 'Number of failing runs by the test_builder_fff trybot.', tally={PatchsetReference(1, 1): 3}, ), self.get_stats('trybot-test_builder_fff-fail-count')) self.assertEquals(self.create_count( name='trybot-test_builder_ffp-fail-count', description = 'Number of failing runs by the test_builder_ffp trybot.', tally={PatchsetReference(1, 1): 2}, ), self.get_stats('trybot-test_builder_ffp-fail-count')) self.assertEquals(self.create_count( name='trybot-fail-count', description = 'Number of failing runs across all trybots.', tally={ TrybotReference('test_master_a', 'test_builder_ppp'): 0, TrybotReference('test_master_a', 'test_builder_fff'): 3, TrybotReference('test_master_b', 'test_builder_ffp'): 2, }, ), self.get_stats('trybot-fail-count')) def test_trybot_successful_run_count(self): self.analyze_records(*self.trybot_records) self.assertEquals(self.create_count( name='trybot-test_builder_ppp-pass-count', description = 'Number of passing runs by the test_builder_ppp trybot.', tally={PatchsetReference(1, 1): 1}, ), self.get_stats('trybot-test_builder_ppp-pass-count')) self.assertEquals(self.create_count( name='trybot-test_builder_fff-pass-count', description = 'Number of passing runs by the test_builder_fff trybot.', tally={PatchsetReference(1, 1): 0}, ), self.get_stats('trybot-test_builder_fff-pass-count')) self.assertEquals(self.create_count( name='trybot-test_builder_ffp-pass-count', description = 'Number of passing runs by the test_builder_ffp trybot.', tally={PatchsetReference(1, 1): 1}, ), self.get_stats('trybot-test_builder_ffp-pass-count')) self.assertEquals(self.create_count( name='trybot-pass-count', description = 'Number of passing runs across all trybots.', tally={ TrybotReference('test_master_a', 'test_builder_ppp'): 1, TrybotReference('test_master_a', 'test_builder_fff'): 0, TrybotReference('test_master_b', 'test_builder_ffp'): 1, }, ), self.get_stats('trybot-pass-count'))
appengine/chromium_cq_status/stats/test/trybot_stats_test.py
# StatsTest must be imported first in order to get proper ndb monkeypatching. from stats.analysis import PatchsetReference from stats.trybot_stats import TrybotReference from stats.test.stats_test import StatsTest passed = 'JOB_SUCCEEDED' failed = 'JOB_FAILED' running = 'JOB_RUNNING' test_builder_ppp = { 'master': 'test_master_a', 'builder': 'test_builder_ppp', 'url': 'ppp', } test_builder_fff = { 'master': 'test_master_a', 'builder': 'test_builder_fff', 'url': 'fff', } test_builder_ffp = { 'master': 'test_master_b', 'builder': 'test_builder_ffp', 'url': 'ffp', } class TrybotStatsTest(StatsTest): # Keep this shorter than 24 records. Each record adds an hour of # virtual time, and the tests aggregate over a day. trybot_records = list(enumerate([ {'issue': 1, 'patchset': 1, 'action': 'patch_start'}, {'issue': 1, 'patchset': 1, 'action': 'verifier_jobs_update', 'jobs': { running: [test_builder_ppp, test_builder_fff, test_builder_ffp] }, }, {'issue': 1, 'patchset': 1, 'action': 'verifier_jobs_update', 'jobs': { passed: [test_builder_ppp], failed: [test_builder_fff, test_builder_ffp], }, }, {'issue': 1, 'patchset': 1, 'action': 'patch_stop'}, {'issue': 1, 'patchset': 1, 'action': 'patch_start'}, {'issue': 1, 'patchset': 1, 'action': 'verifier_jobs_update', 'jobs': { passed: [test_builder_ppp], failed: [test_builder_fff], }, }, {'issue': 1, 'patchset': 1, 'action': 'verifier_jobs_update', 'jobs': { failed: [test_builder_ffp, test_builder_fff], passed: [test_builder_ppp], }, }, {'issue': 1, 'patchset': 1, 'action': 'patch_stop'}, {'issue': 1, 'patchset': 1, 'action': 'patch_start'}, {'issue': 1, 'patchset': 1, 'action': 'verifier_jobs_update', 'jobs': { passed: [test_builder_ppp], failed: [test_builder_fff], passed: [test_builder_ffp], }, }, {'issue': 1, 'patchset': 1, 'action': 'patch_stop'}, ])) def test_trybot_false_reject_count(self): self.analyze_records(*self.trybot_records) self.assertEquals(self.create_count( name='trybot-test_builder_ppp-false-reject-count', description=('Number of false rejects by the test_builder_ppp trybot. ' 'This counts any failed runs that also had passing runs ' 'on the same patch.'), tally={PatchsetReference(1, 1): 0}, ), self.get_stats('trybot-test_builder_ppp-false-reject-count')) self.assertEquals(self.create_count( name='trybot-test_builder_fff-false-reject-count', description=('Number of false rejects by the test_builder_fff trybot. ' 'This counts any failed runs that also had passing runs ' 'on the same patch.'), tally={PatchsetReference(1, 1): 0}, ), self.get_stats('trybot-test_builder_fff-false-reject-count')) self.assertEquals(self.create_count( name='trybot-test_builder_ffp-false-reject-count', description=('Number of false rejects by the test_builder_ffp trybot. ' 'This counts any failed runs that also had passing runs ' 'on the same patch.'), tally={PatchsetReference(1, 1): 2}, ), self.get_stats('trybot-test_builder_ffp-false-reject-count')) self.assertEquals(self.create_count( name='trybot-false-reject-count', description=('Number of false rejects across all trybots. ' 'This counts any failed runs that also had passing runs ' 'on the same patch.'), tally={TrybotReference('test_master_b', 'test_builder_ffp'): 2}, ), self.get_stats('trybot-false-reject-count')) def test_trybot_failed_run_count(self): self.analyze_records(*self.trybot_records) self.assertEquals(self.create_count( name='trybot-test_builder_ppp-fail-count', description = 'Number of failing runs by the test_builder_ppp trybot.', tally={PatchsetReference(1, 1): 0}, ), self.get_stats('trybot-test_builder_ppp-fail-count')) self.assertEquals(self.create_count( name='trybot-test_builder_fff-fail-count', description = 'Number of failing runs by the test_builder_fff trybot.', tally={PatchsetReference(1, 1): 3}, ), self.get_stats('trybot-test_builder_fff-fail-count')) self.assertEquals(self.create_count( name='trybot-test_builder_ffp-fail-count', description = 'Number of failing runs by the test_builder_ffp trybot.', tally={PatchsetReference(1, 1): 2}, ), self.get_stats('trybot-test_builder_ffp-fail-count')) self.assertEquals(self.create_count( name='trybot-fail-count', description = 'Number of failing runs across all trybots.', tally={ TrybotReference('test_master_a', 'test_builder_ppp'): 0, TrybotReference('test_master_a', 'test_builder_fff'): 3, TrybotReference('test_master_b', 'test_builder_ffp'): 2, }, ), self.get_stats('trybot-fail-count')) def test_trybot_successful_run_count(self): self.analyze_records(*self.trybot_records) self.assertEquals(self.create_count( name='trybot-test_builder_ppp-pass-count', description = 'Number of passing runs by the test_builder_ppp trybot.', tally={PatchsetReference(1, 1): 1}, ), self.get_stats('trybot-test_builder_ppp-pass-count')) self.assertEquals(self.create_count( name='trybot-test_builder_fff-pass-count', description = 'Number of passing runs by the test_builder_fff trybot.', tally={PatchsetReference(1, 1): 0}, ), self.get_stats('trybot-test_builder_fff-pass-count')) self.assertEquals(self.create_count( name='trybot-test_builder_ffp-pass-count', description = 'Number of passing runs by the test_builder_ffp trybot.', tally={PatchsetReference(1, 1): 1}, ), self.get_stats('trybot-test_builder_ffp-pass-count')) self.assertEquals(self.create_count( name='trybot-pass-count', description = 'Number of passing runs across all trybots.', tally={ TrybotReference('test_master_a', 'test_builder_ppp'): 1, TrybotReference('test_master_a', 'test_builder_fff'): 0, TrybotReference('test_master_b', 'test_builder_ffp'): 1, }, ), self.get_stats('trybot-pass-count'))
0.583322
0.461017
import sys import os from random import * # This file is what it is, I guess I might be able to do this another way, with # classes maybe (??) But for now, I'm starting out and this works, and I can # Understand how. def toInt(In): ''' this is so if you just write for example d20. it turns the '' in the Input list, into a 1, to roll a single die. I could've done it another way maybe, but getting the 'menu' with help and invalid input to work by my own was tireing, so this just wokrs. ''' if In[0] == '': return str(1) else: return In[0] def help(In): ''' Called when In is 'h' or 'H' ---------------- prints: Information on what the program expects as Input. ---------------- Input: Asks for a new input. ---------------- returns input In. ''' os.system('cls') print (''' Help To roll a die you have to write the # of die to roll followed by die denomination, for example, if you want to roll 3 six sided die, you would write '3d6' (No air quotes), '3D6' would also work, for single dice, 1d6 or d6 would both work. Supported denominations: d4, d6, d8, d10, d12, d20 ''') In = input("\n Type 'h' for help, 'c' to close or your dice roll. \n > ") return In def invIn(In): ''' Called when '' is entered as input. Takes 1 argument In. -------------------- prints error message --------------------- returns new input : In ''' print ("\n You have to input something...") In = input("\n Type 'h' for help, 'c' to close or your dice roll. \n > ") return In #This function is called when you get the right format, to initiate the roll. def dieRoll(roll): ''' Takes one input List 'roll' ------------------ Your roll input (now: In) after being processed by checkSyntax() ------------------ returns an int : your result ''' if roll[0] == '': numberOfDie = 1 else: numberOfDie = int(roll[0]) if roll[1] == 'd4' or roll[1] == 'D4': return rollD4(numberOfDie) elif roll[1] == 'd6' or roll[1] == 'D6': return rollD6(numberOfDie) elif roll[1] == 'd8' or roll[1] == 'D8': return rollD8(numberOfDie) elif roll[1] == 'd10' or roll[1] == 'D10': return rollD10(numberOfDie) elif roll[1] == 'd12' or roll[1] == 'D12': return rollD12(numberOfDie) elif roll[1] == 'd20' or roll[1] == 'D20': return rollD20(numberOfDie) # This are all the functions for the different die. def rollD4(numberOfDie): ''' Takes one input: numberOfDice -------------------------- returns a d4 die roll, times the number of die. ''' if numberOfDie == 1: return randint(1,4) else: return (randint(1,4) + rollD4(numberOfDie-1)) def rollD6(numberOfDie): ''' Takes one input: numberOfDice -------------------------- returns a d6 die roll, times the number of die. ''' if numberOfDie == 1: return randint(1,6) else: return (randint(1,6) + rollD6(numberOfDie-1)) def rollD8(numberOfDie): ''' Takes one input: numberOfDice -------------------------- returns a d8 die roll and adds any aditional rolls. ''' if numberOfDie == 1: return randint(1,8) else: return (randint(1,8) + rollD6(numberOfDie-1)) def rollD10(numberOfDie): ''' Takes one input: numberOfDice -------------------------- returns a d10 die roll, times the number of die. ''' if numberOfDie == 1: return randint(1,10) else: return (randint(1,10) + rollD6(numberOfDie-1)) def rollD12(numberOfDie): ''' Takes one input: numberOfDice -------------------------- returns a d12 die roll, times the number of die. ''' if numberOfDie == 1: return randint(1,12) else: return (randint(1,12) + rollD6(numberOfDie-1)) def rollD20(numberOfDie): ''' Takes one input: numberOfDice -------------------------- returns a d20 die roll, times the number of die. ''' if numberOfDie == 1: return randint(1,20) else: return (randint(1,20 ) + rollD6(numberOfDie-1)) def checkSyntax(In): """ Takes two inputs > In: Input from end User diceTypes: the dice types. ----------- Returns syntax: A list syntax = [Number of die to roll, type of dice] ----------- """ diceTypes = ['d4', 'd6', 'd8', 'd10', 'd12', 'd20', 'D4', 'D6', 'D8', 'D10', 'D12', 'D20'] numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ''] numberOfDice = '' diceType = '' for ch in range(len(In)): if In[ch] in numbers: numberOfDice += In[ch] elif In[ch] == 'd' or In[ch] == 'D': diceType = In[ch:len(In)+1] break else: break check = [numberOfDice, diceType] if check[0] == '': check[0] = '1' try: check[0] = int(check[0]) except: return 'error' if check[1] in diceTypes: return check else: return 'error'
Dice Roller 1.2 Eng/Funcs.py
import sys import os from random import * # This file is what it is, I guess I might be able to do this another way, with # classes maybe (??) But for now, I'm starting out and this works, and I can # Understand how. def toInt(In): ''' this is so if you just write for example d20. it turns the '' in the Input list, into a 1, to roll a single die. I could've done it another way maybe, but getting the 'menu' with help and invalid input to work by my own was tireing, so this just wokrs. ''' if In[0] == '': return str(1) else: return In[0] def help(In): ''' Called when In is 'h' or 'H' ---------------- prints: Information on what the program expects as Input. ---------------- Input: Asks for a new input. ---------------- returns input In. ''' os.system('cls') print (''' Help To roll a die you have to write the # of die to roll followed by die denomination, for example, if you want to roll 3 six sided die, you would write '3d6' (No air quotes), '3D6' would also work, for single dice, 1d6 or d6 would both work. Supported denominations: d4, d6, d8, d10, d12, d20 ''') In = input("\n Type 'h' for help, 'c' to close or your dice roll. \n > ") return In def invIn(In): ''' Called when '' is entered as input. Takes 1 argument In. -------------------- prints error message --------------------- returns new input : In ''' print ("\n You have to input something...") In = input("\n Type 'h' for help, 'c' to close or your dice roll. \n > ") return In #This function is called when you get the right format, to initiate the roll. def dieRoll(roll): ''' Takes one input List 'roll' ------------------ Your roll input (now: In) after being processed by checkSyntax() ------------------ returns an int : your result ''' if roll[0] == '': numberOfDie = 1 else: numberOfDie = int(roll[0]) if roll[1] == 'd4' or roll[1] == 'D4': return rollD4(numberOfDie) elif roll[1] == 'd6' or roll[1] == 'D6': return rollD6(numberOfDie) elif roll[1] == 'd8' or roll[1] == 'D8': return rollD8(numberOfDie) elif roll[1] == 'd10' or roll[1] == 'D10': return rollD10(numberOfDie) elif roll[1] == 'd12' or roll[1] == 'D12': return rollD12(numberOfDie) elif roll[1] == 'd20' or roll[1] == 'D20': return rollD20(numberOfDie) # This are all the functions for the different die. def rollD4(numberOfDie): ''' Takes one input: numberOfDice -------------------------- returns a d4 die roll, times the number of die. ''' if numberOfDie == 1: return randint(1,4) else: return (randint(1,4) + rollD4(numberOfDie-1)) def rollD6(numberOfDie): ''' Takes one input: numberOfDice -------------------------- returns a d6 die roll, times the number of die. ''' if numberOfDie == 1: return randint(1,6) else: return (randint(1,6) + rollD6(numberOfDie-1)) def rollD8(numberOfDie): ''' Takes one input: numberOfDice -------------------------- returns a d8 die roll and adds any aditional rolls. ''' if numberOfDie == 1: return randint(1,8) else: return (randint(1,8) + rollD6(numberOfDie-1)) def rollD10(numberOfDie): ''' Takes one input: numberOfDice -------------------------- returns a d10 die roll, times the number of die. ''' if numberOfDie == 1: return randint(1,10) else: return (randint(1,10) + rollD6(numberOfDie-1)) def rollD12(numberOfDie): ''' Takes one input: numberOfDice -------------------------- returns a d12 die roll, times the number of die. ''' if numberOfDie == 1: return randint(1,12) else: return (randint(1,12) + rollD6(numberOfDie-1)) def rollD20(numberOfDie): ''' Takes one input: numberOfDice -------------------------- returns a d20 die roll, times the number of die. ''' if numberOfDie == 1: return randint(1,20) else: return (randint(1,20 ) + rollD6(numberOfDie-1)) def checkSyntax(In): """ Takes two inputs > In: Input from end User diceTypes: the dice types. ----------- Returns syntax: A list syntax = [Number of die to roll, type of dice] ----------- """ diceTypes = ['d4', 'd6', 'd8', 'd10', 'd12', 'd20', 'D4', 'D6', 'D8', 'D10', 'D12', 'D20'] numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ''] numberOfDice = '' diceType = '' for ch in range(len(In)): if In[ch] in numbers: numberOfDice += In[ch] elif In[ch] == 'd' or In[ch] == 'D': diceType = In[ch:len(In)+1] break else: break check = [numberOfDice, diceType] if check[0] == '': check[0] = '1' try: check[0] = int(check[0]) except: return 'error' if check[1] in diceTypes: return check else: return 'error'
0.309963
0.297572
import random from builtins import range from .facecube import FaceCube from .cubiecube import CubieCube from .coordcube import CoordCube from .color import colors def verify(s): """ Check if the cube definition string s represents a solvable cube. @param s is the cube definition string , see {@link Facelet} @return 0: Cube is solvable<br> -1: There is not exactly one facelet of each colour<br> -2: Not all 12 edges exist exactly once<br> -3: Flip error: One edge has to be flipped<br> -4: Not all 8 corners exist exactly once<br> -5: Twist error: One corner has to be twisted<br> -6: Parity error: Two corners or two edges have to be exchanged """ count = [0] * 6 # new int[6] try: for i in range(54): assert s[i] in colors count[colors[s[i]]] += 1 except: return -1 for i in range(6): if count[i] != 9: return -1 fc = FaceCube(s) cc = fc.toCubieCube() return cc.verify() def randomCube(): """ Generates a random cube. @return A random cube in the string representation. Each cube of the cube space has the same probability. """ cc = CubieCube() cc.setFlip(random.randint(0, CoordCube.N_FLIP - 1)) cc.setTwist(random.randint(0, CoordCube.N_TWIST - 1)) while True: cc.setURFtoDLB(random.randint(0, CoordCube.N_URFtoDLB - 1)) cc.setURtoBR(random.randint(0, CoordCube.N_URtoBR - 1)) if (cc.edgeParity() ^ cc.cornerParity()) == 0: break fc = cc.toFaceCube() return fc.to_String() def randomLastLayerCube(): """ Generates a cube with a random last layer. @return A cube with a random last layer and otherwise solved facelets in the string representation. """ cc = CubieCube() cc.setFlip(random.choice([0, 24, 40, 48, 72, 80, 96, 120])) cc.setTwist(random.randint(0, 26)) while True: perms = [0, 624, 3744, 3840, 4344, 4440, 26064, 26160, 26664, 26760, 27360, 27984, 30384, 30480, 30984, 31080, 31680, 32304, 35304, 35400, 36000, 36624, 39744, 39840] cc.setURFtoDLB(random.choice(perms)) cc.setURtoBR(random.choice(perms)) if (cc.edgeParity() ^ cc.cornerParity()) == 0: break fc = cc.toFaceCube() return fc.to_String()
kociemba/pykociemba/tools.py
import random from builtins import range from .facecube import FaceCube from .cubiecube import CubieCube from .coordcube import CoordCube from .color import colors def verify(s): """ Check if the cube definition string s represents a solvable cube. @param s is the cube definition string , see {@link Facelet} @return 0: Cube is solvable<br> -1: There is not exactly one facelet of each colour<br> -2: Not all 12 edges exist exactly once<br> -3: Flip error: One edge has to be flipped<br> -4: Not all 8 corners exist exactly once<br> -5: Twist error: One corner has to be twisted<br> -6: Parity error: Two corners or two edges have to be exchanged """ count = [0] * 6 # new int[6] try: for i in range(54): assert s[i] in colors count[colors[s[i]]] += 1 except: return -1 for i in range(6): if count[i] != 9: return -1 fc = FaceCube(s) cc = fc.toCubieCube() return cc.verify() def randomCube(): """ Generates a random cube. @return A random cube in the string representation. Each cube of the cube space has the same probability. """ cc = CubieCube() cc.setFlip(random.randint(0, CoordCube.N_FLIP - 1)) cc.setTwist(random.randint(0, CoordCube.N_TWIST - 1)) while True: cc.setURFtoDLB(random.randint(0, CoordCube.N_URFtoDLB - 1)) cc.setURtoBR(random.randint(0, CoordCube.N_URtoBR - 1)) if (cc.edgeParity() ^ cc.cornerParity()) == 0: break fc = cc.toFaceCube() return fc.to_String() def randomLastLayerCube(): """ Generates a cube with a random last layer. @return A cube with a random last layer and otherwise solved facelets in the string representation. """ cc = CubieCube() cc.setFlip(random.choice([0, 24, 40, 48, 72, 80, 96, 120])) cc.setTwist(random.randint(0, 26)) while True: perms = [0, 624, 3744, 3840, 4344, 4440, 26064, 26160, 26664, 26760, 27360, 27984, 30384, 30480, 30984, 31080, 31680, 32304, 35304, 35400, 36000, 36624, 39744, 39840] cc.setURFtoDLB(random.choice(perms)) cc.setURtoBR(random.choice(perms)) if (cc.edgeParity() ^ cc.cornerParity()) == 0: break fc = cc.toFaceCube() return fc.to_String()
0.772187
0.526221
class ListNode: def __init__(self, key, val): self.key = key self.val = val self.next = None class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.head = None self.tail = None self.data = dict() def moveToTail(self, node: ListNode): if not node.next: return # swap value of current node and next node node.val, node.next.val = node.next.val, node.val node.key, node.next.key = node.next.key, node.key # swap ref in data map self.data[node.key] = node self.data[node.next.key] = node.next if self.tail == node.next: return # move node next to tail self.tail.next = node.next self.tail = self.tail.next node.next = node.next.next self.tail.next = None def get(self, key: int) -> int: node = self.data.get(key) if not node: return -1 val = node.val self.moveToTail(node) return val def put(self, key: int, value: int) -> None: node = self.data.get(key) if node: node.val = value self.moveToTail(node) return node = ListNode(key, value) if self.tail: self.tail.next = node else: self.head = node self.tail = node self.data[key] = node if len(self.data) > self.capacity: tmp = self.head self.head = self.head.next del self.data[tmp.key] def print_list(self): node = self.head while node: print('({}:{})'.format(node.key, node.val), end='->' if node.next else '') node = node.next print() # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value) if __name__ == '__main__': cache = LRUCache(capacity=5) cache.put(3, 3) cache.print_list() cache.put(1, 3) cache.print_list() cache.put(2, 3) cache.print_list() cache.put(1, 3) cache.print_list() cache.put(2, 3) cache.print_list() cache.put(3, 3) cache.print_list() cache.put(4, 3) cache.print_list() cache.put(5, 3) cache.print_list() cache.put(6, 3) cache.print_list()
leetcode/146-lru-cache.py
class ListNode: def __init__(self, key, val): self.key = key self.val = val self.next = None class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.head = None self.tail = None self.data = dict() def moveToTail(self, node: ListNode): if not node.next: return # swap value of current node and next node node.val, node.next.val = node.next.val, node.val node.key, node.next.key = node.next.key, node.key # swap ref in data map self.data[node.key] = node self.data[node.next.key] = node.next if self.tail == node.next: return # move node next to tail self.tail.next = node.next self.tail = self.tail.next node.next = node.next.next self.tail.next = None def get(self, key: int) -> int: node = self.data.get(key) if not node: return -1 val = node.val self.moveToTail(node) return val def put(self, key: int, value: int) -> None: node = self.data.get(key) if node: node.val = value self.moveToTail(node) return node = ListNode(key, value) if self.tail: self.tail.next = node else: self.head = node self.tail = node self.data[key] = node if len(self.data) > self.capacity: tmp = self.head self.head = self.head.next del self.data[tmp.key] def print_list(self): node = self.head while node: print('({}:{})'.format(node.key, node.val), end='->' if node.next else '') node = node.next print() # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value) if __name__ == '__main__': cache = LRUCache(capacity=5) cache.put(3, 3) cache.print_list() cache.put(1, 3) cache.print_list() cache.put(2, 3) cache.print_list() cache.put(1, 3) cache.print_list() cache.put(2, 3) cache.print_list() cache.put(3, 3) cache.print_list() cache.put(4, 3) cache.print_list() cache.put(5, 3) cache.print_list() cache.put(6, 3) cache.print_list()
0.684264
0.364919
import json from datetime import datetime import pytest from pydantic.error_wrappers import ValidationError as PydanticValidationError from node.blockchain.facade import BlockchainFacade from node.blockchain.inner_models import ( AccountState, Block, BlockMessageUpdate, GenesisBlockMessage, GenesisSignedChangeRequestMessage, SignedChangeRequest ) from node.blockchain.models import AccountState as ORMAccountState from node.blockchain.models import Block as ORMBlock from node.blockchain.models import Schedule from node.blockchain.types import AccountLock, Signature, Type from node.core.utils.cryptography import is_signature_valid @pytest.mark.django_db def test_create_from_block_message( genesis_block_message, primary_validator_key_pair, primary_validator_node, treasury_account_key_pair, treasury_amount ): assert not ORMAccountState.objects.exists() blockchain_facade = BlockchainFacade.get_instance() block = blockchain_facade.add_block_from_block_message( message=genesis_block_message, signing_key=primary_validator_key_pair.private, validate=False, ) assert block.signer == primary_validator_key_pair.public assert isinstance(block.signature, str) assert is_signature_valid( block.signer, block.message.make_binary_representation_for_cryptography(), Signature(block.signature) ) message = block.message assert message.number == 0 assert message.identifier is None assert message.type == Type.GENESIS assert message == genesis_block_message # Test rereading the block from the database orm_block = ORMBlock.objects.get(_id=0) block = Block.parse_raw(orm_block.body) assert block.signer == primary_validator_key_pair.public assert isinstance(block.signature, str) assert is_signature_valid( block.signer, block.message.make_binary_representation_for_cryptography(), Signature(block.signature) ) message = block.message assert message.number == 0 assert message.identifier is None assert message.type == Type.GENESIS assert message == genesis_block_message # Test account state write-through cache assert ORMAccountState.objects.count() == 2 account_state = ORMAccountState.objects.get(_id=primary_validator_key_pair.public) assert account_state.account_lock == primary_validator_key_pair.public assert account_state.balance == 0 assert account_state.node == primary_validator_node.dict() account_state = ORMAccountState.objects.get(_id=treasury_account_key_pair.public) assert account_state.account_lock == treasury_account_key_pair.public assert account_state.balance == treasury_amount # Test schedule write-through cache schedule = Schedule.objects.order_by('_id').all() assert tuple((item._id, item.node_identifier) for item in schedule) == ((0, primary_validator_key_pair.public),) @pytest.mark.django_db def test_create_from_alpha_account_root_file( primary_validator_key_pair, primary_validator_node, treasury_account_key_pair, account_root_file ): assert not ORMAccountState.objects.exists() blockchain_facade = BlockchainFacade.get_instance() request_message = GenesisSignedChangeRequestMessage.create_from_alpha_account_root_file( account_lock=AccountLock(primary_validator_key_pair.public), account_root_file=account_root_file, ) request = SignedChangeRequest.create_from_signed_change_request_message( request_message, primary_validator_key_pair.private ) genesis_block_message = GenesisBlockMessage.create_from_signed_change_request(request, primary_validator_node) block = blockchain_facade.add_block_from_block_message( message=genesis_block_message, signing_key=primary_validator_key_pair.private, validate=False, ) assert block.signer == primary_validator_key_pair.public assert isinstance(block.signature, str) assert is_signature_valid( block.signer, block.message.make_binary_representation_for_cryptography(), Signature(block.signature) ) message = block.message assert message.number == 0 assert message.identifier is None assert message.type == Type.GENESIS assert message == genesis_block_message # Test rereading the block from the database orm_block = ORMBlock.objects.get(_id=0) block = Block.parse_raw(orm_block.body) assert block.signer == primary_validator_key_pair.public assert isinstance(block.signature, str) assert is_signature_valid( block.signer, block.message.make_binary_representation_for_cryptography(), Signature(block.signature) ) message = block.message assert message.number == 0 assert message.identifier is None assert message.type == Type.GENESIS assert message == genesis_block_message # Test account state write-through cache assert ORMAccountState.objects.count() == 4 account_state = ORMAccountState.objects.get(_id=primary_validator_key_pair.public) assert account_state.account_lock == primary_validator_key_pair.public assert account_state.balance == 0 assert account_state.node == primary_validator_node.dict() account_state = ORMAccountState.objects.get(_id='8bf7df36676adbc294ba1a78ff9565dd65e2da73e4d46d5e11c7c3a6c803dff7') account_root_file_entry = account_root_file['8BF7DF36676ADBC294BA1A78FF9565DD65E2DA73E4D46D5E11C7C3A6C803DFF7'] assert account_state.account_lock == account_root_file_entry['balance_lock'].lower() assert account_state.balance == account_root_file_entry['balance'] account_state = ORMAccountState.objects.get(_id='009073c5985d3a715c3d44a33d5f928e893935fbab206d1d676d7d8b6e27ec85') account_root_file_entry = account_root_file['009073c5985d3a715c3d44a33d5f928e893935fbab206d1d676d7d8b6e27ec85'] assert account_state.account_lock == account_root_file_entry['balance_lock'] assert account_state.balance == account_root_file_entry['balance'] # Test schedule write-through cache schedule = Schedule.objects.order_by('_id').all() assert tuple((item._id, item.node_identifier) for item in schedule) == ((0, primary_validator_key_pair.public),) @pytest.mark.parametrize('kwargs', ( { 'number': 1 }, { 'identifier': '0' * 64 }, { 'type': Type.NODE_DECLARATION.value }, )) def test_cannot_create_invalid_genesis_block_message( primary_validator_key_pair, genesis_signed_change_request, kwargs ): message = GenesisBlockMessage( timestamp=datetime.utcnow(), update=BlockMessageUpdate(accounts={'0' * 64: AccountState(balance=10)}), request=genesis_signed_change_request, ) block = Block(signer='0' * 64, signature='0' * 128, message=message) block_dict = json.loads(block.json()) block_dict['message'].update(kwargs) with pytest.raises(PydanticValidationError): block.parse_raw(json.dumps(block_dict))
node/blockchain/tests/test_models/test_block/test_genesis.py
import json from datetime import datetime import pytest from pydantic.error_wrappers import ValidationError as PydanticValidationError from node.blockchain.facade import BlockchainFacade from node.blockchain.inner_models import ( AccountState, Block, BlockMessageUpdate, GenesisBlockMessage, GenesisSignedChangeRequestMessage, SignedChangeRequest ) from node.blockchain.models import AccountState as ORMAccountState from node.blockchain.models import Block as ORMBlock from node.blockchain.models import Schedule from node.blockchain.types import AccountLock, Signature, Type from node.core.utils.cryptography import is_signature_valid @pytest.mark.django_db def test_create_from_block_message( genesis_block_message, primary_validator_key_pair, primary_validator_node, treasury_account_key_pair, treasury_amount ): assert not ORMAccountState.objects.exists() blockchain_facade = BlockchainFacade.get_instance() block = blockchain_facade.add_block_from_block_message( message=genesis_block_message, signing_key=primary_validator_key_pair.private, validate=False, ) assert block.signer == primary_validator_key_pair.public assert isinstance(block.signature, str) assert is_signature_valid( block.signer, block.message.make_binary_representation_for_cryptography(), Signature(block.signature) ) message = block.message assert message.number == 0 assert message.identifier is None assert message.type == Type.GENESIS assert message == genesis_block_message # Test rereading the block from the database orm_block = ORMBlock.objects.get(_id=0) block = Block.parse_raw(orm_block.body) assert block.signer == primary_validator_key_pair.public assert isinstance(block.signature, str) assert is_signature_valid( block.signer, block.message.make_binary_representation_for_cryptography(), Signature(block.signature) ) message = block.message assert message.number == 0 assert message.identifier is None assert message.type == Type.GENESIS assert message == genesis_block_message # Test account state write-through cache assert ORMAccountState.objects.count() == 2 account_state = ORMAccountState.objects.get(_id=primary_validator_key_pair.public) assert account_state.account_lock == primary_validator_key_pair.public assert account_state.balance == 0 assert account_state.node == primary_validator_node.dict() account_state = ORMAccountState.objects.get(_id=treasury_account_key_pair.public) assert account_state.account_lock == treasury_account_key_pair.public assert account_state.balance == treasury_amount # Test schedule write-through cache schedule = Schedule.objects.order_by('_id').all() assert tuple((item._id, item.node_identifier) for item in schedule) == ((0, primary_validator_key_pair.public),) @pytest.mark.django_db def test_create_from_alpha_account_root_file( primary_validator_key_pair, primary_validator_node, treasury_account_key_pair, account_root_file ): assert not ORMAccountState.objects.exists() blockchain_facade = BlockchainFacade.get_instance() request_message = GenesisSignedChangeRequestMessage.create_from_alpha_account_root_file( account_lock=AccountLock(primary_validator_key_pair.public), account_root_file=account_root_file, ) request = SignedChangeRequest.create_from_signed_change_request_message( request_message, primary_validator_key_pair.private ) genesis_block_message = GenesisBlockMessage.create_from_signed_change_request(request, primary_validator_node) block = blockchain_facade.add_block_from_block_message( message=genesis_block_message, signing_key=primary_validator_key_pair.private, validate=False, ) assert block.signer == primary_validator_key_pair.public assert isinstance(block.signature, str) assert is_signature_valid( block.signer, block.message.make_binary_representation_for_cryptography(), Signature(block.signature) ) message = block.message assert message.number == 0 assert message.identifier is None assert message.type == Type.GENESIS assert message == genesis_block_message # Test rereading the block from the database orm_block = ORMBlock.objects.get(_id=0) block = Block.parse_raw(orm_block.body) assert block.signer == primary_validator_key_pair.public assert isinstance(block.signature, str) assert is_signature_valid( block.signer, block.message.make_binary_representation_for_cryptography(), Signature(block.signature) ) message = block.message assert message.number == 0 assert message.identifier is None assert message.type == Type.GENESIS assert message == genesis_block_message # Test account state write-through cache assert ORMAccountState.objects.count() == 4 account_state = ORMAccountState.objects.get(_id=primary_validator_key_pair.public) assert account_state.account_lock == primary_validator_key_pair.public assert account_state.balance == 0 assert account_state.node == primary_validator_node.dict() account_state = ORMAccountState.objects.get(_id='8bf7df36676adbc294ba1a78ff9565dd65e2da73e4d46d5e11c7c3a6c803dff7') account_root_file_entry = account_root_file['8BF7DF36676ADBC294BA1A78FF9565DD65E2DA73E4D46D5E11C7C3A6C803DFF7'] assert account_state.account_lock == account_root_file_entry['balance_lock'].lower() assert account_state.balance == account_root_file_entry['balance'] account_state = ORMAccountState.objects.get(_id='009073c5985d3a715c3d44a33d5f928e893935fbab206d1d676d7d8b6e27ec85') account_root_file_entry = account_root_file['009073c5985d3a715c3d44a33d5f928e893935fbab206d1d676d7d8b6e27ec85'] assert account_state.account_lock == account_root_file_entry['balance_lock'] assert account_state.balance == account_root_file_entry['balance'] # Test schedule write-through cache schedule = Schedule.objects.order_by('_id').all() assert tuple((item._id, item.node_identifier) for item in schedule) == ((0, primary_validator_key_pair.public),) @pytest.mark.parametrize('kwargs', ( { 'number': 1 }, { 'identifier': '0' * 64 }, { 'type': Type.NODE_DECLARATION.value }, )) def test_cannot_create_invalid_genesis_block_message( primary_validator_key_pair, genesis_signed_change_request, kwargs ): message = GenesisBlockMessage( timestamp=datetime.utcnow(), update=BlockMessageUpdate(accounts={'0' * 64: AccountState(balance=10)}), request=genesis_signed_change_request, ) block = Block(signer='0' * 64, signature='0' * 128, message=message) block_dict = json.loads(block.json()) block_dict['message'].update(kwargs) with pytest.raises(PydanticValidationError): block.parse_raw(json.dumps(block_dict))
0.663778
0.38027
generator.""" import json import os import random TWEETS = None def _get_tweets(db_path="tweets.json"): """Get Trump's tweets, caching after first use.""" global TWEETS # Cache tweets if they haven't been fetched yet if TWEETS is None: # Try to read from a saved file if os.path.exists(db_path): with open(db_path) as f: TWEETS = json.load(f) # Fall back to reading from the API, but caching to a file. else: from thedonald import tweets TWEETS = tweets.write_tweets_to_file(db_path) # Return from cache return TWEETS def _next_word_choices(search): """Get a list of word choices for next_word(). This favors more frequently used words by allowing for words to be included multiple times, thus boosting their chances of selection.""" choices = [] for i in _get_tweets(): words = i.split() indices = [index for index, word in enumerate(words) if word == search] choices.extend([words[i + 1] for i in indices if i < len(words) - 1]) return choices def random_word(): """Get a random word from one of Trump's tweets.""" return random.choice(" ".join(_get_tweets()).split()) def random_starting_word(): """Get a random word to start a sentence.""" return random.choice([t.split()[0] for t in _get_tweets()]) def next_word(word): """Choose a word to succeed a given word based on what Trump would put there.""" choices = _next_word_choices(word) if choices: return random.choice(_next_word_choices(word)) else: return False def sentence(): """Generate a random sentence using a Markov chain on Trump's tweets.""" out = [random_starting_word()] while not out[-1][-1] in ".!?": nxt = next_word(out[-1]) if nxt: out.append(nxt) else: # If no words follow it, just stop there. break return " ".join(out) def generate(): return " ".join([sentence() for _ in range(random.randint(1, 3))])
thedonald/__init__.py
generator.""" import json import os import random TWEETS = None def _get_tweets(db_path="tweets.json"): """Get Trump's tweets, caching after first use.""" global TWEETS # Cache tweets if they haven't been fetched yet if TWEETS is None: # Try to read from a saved file if os.path.exists(db_path): with open(db_path) as f: TWEETS = json.load(f) # Fall back to reading from the API, but caching to a file. else: from thedonald import tweets TWEETS = tweets.write_tweets_to_file(db_path) # Return from cache return TWEETS def _next_word_choices(search): """Get a list of word choices for next_word(). This favors more frequently used words by allowing for words to be included multiple times, thus boosting their chances of selection.""" choices = [] for i in _get_tweets(): words = i.split() indices = [index for index, word in enumerate(words) if word == search] choices.extend([words[i + 1] for i in indices if i < len(words) - 1]) return choices def random_word(): """Get a random word from one of Trump's tweets.""" return random.choice(" ".join(_get_tweets()).split()) def random_starting_word(): """Get a random word to start a sentence.""" return random.choice([t.split()[0] for t in _get_tweets()]) def next_word(word): """Choose a word to succeed a given word based on what Trump would put there.""" choices = _next_word_choices(word) if choices: return random.choice(_next_word_choices(word)) else: return False def sentence(): """Generate a random sentence using a Markov chain on Trump's tweets.""" out = [random_starting_word()] while not out[-1][-1] in ".!?": nxt = next_word(out[-1]) if nxt: out.append(nxt) else: # If no words follow it, just stop there. break return " ".join(out) def generate(): return " ".join([sentence() for _ in range(random.randint(1, 3))])
0.669313
0.20144
import gym import numpy as np class GymWrapper(gym.Env): """OpenAI Gym interface for the source-tracking POMDP. Args: sim (SourceTracking): an instance of the SourceTracking class with draw_source = True stop_t (int, optional): maximum number of timesteps, it should be large enough to (almost) never be reached """ def __init__( self, sim, stop_t=100000, # should be large enough to (almost) never be reached ): super().__init__() self.sim = sim # instance of SourceTrackingBounce if not self.sim.draw_source: raise Exception("GymWrapper requires draw_source = True") self.action_space = gym.spaces.Discrete(self.sim.Nactions) self.observation_space = gym.spaces.Box(low=0.0, high=1.0, shape=tuple([2 * self.sim.N - 1] * self.sim.Ndim), dtype=np.float32) self.stop_t = stop_t def step(self, action): """Make a step in the environment. Args: action (int): the action to execute Returns: observation (ndarray): p_source centered on the agent reward (float): always a -1 time penalty done (bool): whether the search is over info (dict): contains the hits received, whether the maximum number of steps is reached, and whether the source was found """ if self.beyond_done: raise Exception("Cannot call step() once done, need to reset first!") # make a step in source-tracking sim hit, _, found = self.sim.step(action, quiet=True) # increment steps self.t += 1 # reward = time penalty reward = -1 # timeout timeout = False if self.t >= self.stop_t: timeout = True # observation observation = np.array(self.sim._centeragent(self.sim.p_source, self.sim.agent), dtype=np.float32) # info info = { "hit": hit, "timeout": timeout, "found": found, } # done done = False if found or timeout: done = True self.beyond_done = True return observation, reward, done, info def reset(self, ): """Reset the search. Returns: observation (ndarray): p_source centered on the agent """ self.t = 0 self.beyond_done = False self.sim.restart() observation = np.array(self.sim._centeragent(self.sim.p_source, self.sim.agent), dtype=np.float32) return observation
otto/classes/gymwrapper.py
import gym import numpy as np class GymWrapper(gym.Env): """OpenAI Gym interface for the source-tracking POMDP. Args: sim (SourceTracking): an instance of the SourceTracking class with draw_source = True stop_t (int, optional): maximum number of timesteps, it should be large enough to (almost) never be reached """ def __init__( self, sim, stop_t=100000, # should be large enough to (almost) never be reached ): super().__init__() self.sim = sim # instance of SourceTrackingBounce if not self.sim.draw_source: raise Exception("GymWrapper requires draw_source = True") self.action_space = gym.spaces.Discrete(self.sim.Nactions) self.observation_space = gym.spaces.Box(low=0.0, high=1.0, shape=tuple([2 * self.sim.N - 1] * self.sim.Ndim), dtype=np.float32) self.stop_t = stop_t def step(self, action): """Make a step in the environment. Args: action (int): the action to execute Returns: observation (ndarray): p_source centered on the agent reward (float): always a -1 time penalty done (bool): whether the search is over info (dict): contains the hits received, whether the maximum number of steps is reached, and whether the source was found """ if self.beyond_done: raise Exception("Cannot call step() once done, need to reset first!") # make a step in source-tracking sim hit, _, found = self.sim.step(action, quiet=True) # increment steps self.t += 1 # reward = time penalty reward = -1 # timeout timeout = False if self.t >= self.stop_t: timeout = True # observation observation = np.array(self.sim._centeragent(self.sim.p_source, self.sim.agent), dtype=np.float32) # info info = { "hit": hit, "timeout": timeout, "found": found, } # done done = False if found or timeout: done = True self.beyond_done = True return observation, reward, done, info def reset(self, ): """Reset the search. Returns: observation (ndarray): p_source centered on the agent """ self.t = 0 self.beyond_done = False self.sim.restart() observation = np.array(self.sim._centeragent(self.sim.p_source, self.sim.agent), dtype=np.float32) return observation
0.890972
0.468487
from os.path import commonprefix __unittest = True _MAX_LENGTH = 80 _PLACEHOLDER_LEN = 12 _MIN_BEGIN_LEN = 5 _MIN_END_LEN = 5 _MIN_COMMON_LEN = 5 _MIN_DIFF_LEN = _MAX_LENGTH - \ (_MIN_BEGIN_LEN + _PLACEHOLDER_LEN + _MIN_COMMON_LEN + _PLACEHOLDER_LEN + _MIN_END_LEN) assert _MIN_DIFF_LEN >= 0 def _shorten(s, prefixlen, suffixlen): skip = len(s) - prefixlen - suffixlen if skip > _PLACEHOLDER_LEN: s = '%s[%d chars]%s' % (s[:prefixlen], skip, s[len(s) - suffixlen:]) return s def _common_shorten_repr(*args): args = tuple(map(safe_repr, args)) maxlen = max(map(len, args)) if maxlen <= _MAX_LENGTH: return args prefix = commonprefix(args) prefixlen = len(prefix) common_len = _MAX_LENGTH - \ (maxlen - prefixlen + _MIN_BEGIN_LEN + _PLACEHOLDER_LEN) if common_len > _MIN_COMMON_LEN: assert _MIN_BEGIN_LEN + _PLACEHOLDER_LEN + _MIN_COMMON_LEN + \ (maxlen - prefixlen) < _MAX_LENGTH prefix = _shorten(prefix, _MIN_BEGIN_LEN, common_len) return tuple(prefix + s[prefixlen:] for s in args) prefix = _shorten(prefix, _MIN_BEGIN_LEN, _MIN_COMMON_LEN) return tuple(prefix + _shorten(s[prefixlen:], _MIN_DIFF_LEN, _MIN_END_LEN) for s in args) def safe_repr(obj, short=False): try: result = repr(obj) except Exception: result = object.__repr__(obj) if not short or len(result) < _MAX_LENGTH: return result return result[:_MAX_LENGTH] + ' [truncated]...' def safe_str(obj): try: return str(obj) except Exception: return object.__str__(obj) def strclass(cls): return "%s.%s" % (cls.__module__, getattr(cls, '__qualname__', cls.__name__)) def unorderable_list_difference(expected, actual, ignore_duplicate=False): """Same behavior as sorted_list_difference but for lists of unorderable items (like dicts). As it does a linear search per item (remove) it has O(n*n) performance. """ missing = [] unexpected = [] while expected: item = expected.pop() try: actual.remove(item) except ValueError: missing.append(item) if ignore_duplicate: for lst in expected, actual: try: while True: lst.remove(item) except ValueError: pass if ignore_duplicate: while actual: item = actual.pop() unexpected.append(item) try: while True: actual.remove(item) except ValueError: pass return missing, unexpected # anything left in actual is unexpected return missing, actual def three_way_cmp(x, y): """Return -1 if x < y, 0 if x == y and 1 if x > y""" return (x > y) - (x < y)
Lib/site-packages/unittest2/util.py
from os.path import commonprefix __unittest = True _MAX_LENGTH = 80 _PLACEHOLDER_LEN = 12 _MIN_BEGIN_LEN = 5 _MIN_END_LEN = 5 _MIN_COMMON_LEN = 5 _MIN_DIFF_LEN = _MAX_LENGTH - \ (_MIN_BEGIN_LEN + _PLACEHOLDER_LEN + _MIN_COMMON_LEN + _PLACEHOLDER_LEN + _MIN_END_LEN) assert _MIN_DIFF_LEN >= 0 def _shorten(s, prefixlen, suffixlen): skip = len(s) - prefixlen - suffixlen if skip > _PLACEHOLDER_LEN: s = '%s[%d chars]%s' % (s[:prefixlen], skip, s[len(s) - suffixlen:]) return s def _common_shorten_repr(*args): args = tuple(map(safe_repr, args)) maxlen = max(map(len, args)) if maxlen <= _MAX_LENGTH: return args prefix = commonprefix(args) prefixlen = len(prefix) common_len = _MAX_LENGTH - \ (maxlen - prefixlen + _MIN_BEGIN_LEN + _PLACEHOLDER_LEN) if common_len > _MIN_COMMON_LEN: assert _MIN_BEGIN_LEN + _PLACEHOLDER_LEN + _MIN_COMMON_LEN + \ (maxlen - prefixlen) < _MAX_LENGTH prefix = _shorten(prefix, _MIN_BEGIN_LEN, common_len) return tuple(prefix + s[prefixlen:] for s in args) prefix = _shorten(prefix, _MIN_BEGIN_LEN, _MIN_COMMON_LEN) return tuple(prefix + _shorten(s[prefixlen:], _MIN_DIFF_LEN, _MIN_END_LEN) for s in args) def safe_repr(obj, short=False): try: result = repr(obj) except Exception: result = object.__repr__(obj) if not short or len(result) < _MAX_LENGTH: return result return result[:_MAX_LENGTH] + ' [truncated]...' def safe_str(obj): try: return str(obj) except Exception: return object.__str__(obj) def strclass(cls): return "%s.%s" % (cls.__module__, getattr(cls, '__qualname__', cls.__name__)) def unorderable_list_difference(expected, actual, ignore_duplicate=False): """Same behavior as sorted_list_difference but for lists of unorderable items (like dicts). As it does a linear search per item (remove) it has O(n*n) performance. """ missing = [] unexpected = [] while expected: item = expected.pop() try: actual.remove(item) except ValueError: missing.append(item) if ignore_duplicate: for lst in expected, actual: try: while True: lst.remove(item) except ValueError: pass if ignore_duplicate: while actual: item = actual.pop() unexpected.append(item) try: while True: actual.remove(item) except ValueError: pass return missing, unexpected # anything left in actual is unexpected return missing, actual def three_way_cmp(x, y): """Return -1 if x < y, 0 if x == y and 1 if x > y""" return (x > y) - (x < y)
0.478773
0.173919
from flask import Flask from flask_mail import Mail, Message import pandas as pd import logging import requests import time from local_settings import * import datetime import gc import pymysql import warnings app = Flask(__name__) email_service = Mail(app) # ensure info logs are printed logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.INFO, datefmt='%m/%d/%Y %I:%M:%S %p') # connect to sql def getSQLConn(host, user, password): return pymysql.connect(host=host,\ user=user,\ passwd=password, autocommit=True) mysql_conn = getSQLConn(MYSQL_AUTH['host'], MYSQL_AUTH['user'], MYSQL_AUTH['password']) # run query def runQuery(mysql_conn, query): with mysql_conn.cursor() as cursor: with warnings.catch_warnings(): warnings.simplefilter('ignore') cursor.execute(query) # convert Kelvin to Fahrenheit def K_to_F(degrees_kelvin): return int((float(degrees_kelvin) * (9/5)) - 459.67) def weather_api_service(cityIDset, dateFact, tomorrow, mysql_conn, city_dict): # truncate table tblFactCityWeather with current data and data older than 10 days query = """DELETE from klaviyo.tblFactCityWeather where dateFact=CURRENT_DATE or dateFact<date_sub(CURRENT_DATE, interval 10 day) """ runQuery(mysql_conn, query) for _i, cityID in enumerate(cityIDset): # current weather api call r = requests.get('http://api.openweathermap.org/data/2.5/weather?id=%s&appid=%s' % \ (cityID, OPENWEATHERMAP_AUTH['api_key'])) obj = r.json() today_weather = '-'.join([obj['weather'][0]['main'], obj['weather'][0]['description']]) today_max_degrees_F = K_to_F(obj['main']['temp_max']) time.sleep(1.5) # reduce cadence of api calls # forecast weather api call r = requests.get('http://api.openweathermap.org/data/2.5/forecast?id=%s&appid=%s' % \ (cityID, OPENWEATHERMAP_AUTH['api_key'])) obj = r.json() # ony get objects for tmrw tmrw_objs = [x for x in obj['list'] if x['dt_txt'][0:10] == tomorrow] tomorrow_max_degrees_F = K_to_F(max([tmrw_obj['main']['temp_max'] for tmrw_obj in tmrw_objs])) query = "INSERT INTO klaviyo.tblFactCityWeather(city_id, dateFact, today_weather, today_max_degrees_F, \ tomorrow_max_degrees_F) VALUES (%i, '%s', '%s', %i, %i)" % (cityID, dateFact, today_weather, today_max_degrees_F, \ tomorrow_max_degrees_F) runQuery(mysql_conn, query) logging.info('%s - %s - %s - %s - %s - %s' % (city_dict[str(cityID)], cityID, dateFact, today_weather, \ today_max_degrees_F, tomorrow_max_degrees_F)) if _i % 20 == 5: gc.collect(); return logging.info('finished weather api service') def weather_email_service(email_service, app, mysql_conn, city_dict): # truncate table tblDimEmailCity with subscriptions older than 10 days truncate_query = """DELETE from klaviyo.tblDimEmailCity where sign_up_date<date_sub(CURRENT_DATE, interval 10 day) """ runQuery(mysql_conn, truncate_query) # tblDimEmailCity --> pandas dataframe & constrain city ids to consider by data in tblDimEmailCity tblDimEmailCity = pd.read_sql_query('SELECT email, city_id FROM klaviyo.tblDimEmailCity', con=mysql_conn) city_id_set = set(tblDimEmailCity['city_id']) city_id_string = str(city_id_set).replace('{','').replace('}','') # create tblFactCityWeather_dict for today's weather api data constrained to city_id_set tfcw_df = pd.read_sql_query('SELECT city_id, today_weather, today_max_degrees_F, tomorrow_max_degrees_F \ FROM klaviyo.tblFactCityWeather where dateFact=CURRENT_DATE and city_id in (%s)' % (city_id_string), con=mysql_conn) tblFactCityWeather_dict = dict() zipped_array = zip(tfcw_df['city_id'], tfcw_df['today_weather'], tfcw_df['today_max_degrees_F'], tfcw_df['tomorrow_max_degrees_F']) for city_id, today_weather, today_F, tomorrow_F in zipped_array: tblFactCityWeather_dict[city_id] = [str(today_weather).lower(), int(today_F), int(tomorrow_F)] for city_id in city_id_set: gc.collect(); # find set of recipients per city id _tblDimEmailCity = tblDimEmailCity[tblDimEmailCity['city_id'] == city_id] _tblDimEmailCity = _tblDimEmailCity.reset_index(drop = True) recipients = set(_tblDimEmailCity['email']) logging.info('recipients = %s' % recipients) today_weather = tblFactCityWeather_dict[city_id][0] today_F = tblFactCityWeather_dict[city_id][1] tomorrow_F = tblFactCityWeather_dict[city_id][2] # subject_value + gif_link logic precipitation_words = ['mist','rain','sleet','snow','hail'] sunny_words = ['sunny','clear'] if any(x in today_weather for x in sunny_words): logging.info('sunny') subject_value = "It's nice out! Enjoy a discount on us." gif_link = 'https://media.giphy.com/media/nYiHd4Mh3w6fS/giphy.gif' elif today_F >= tomorrow_F + 5: logging.info('warm') subject_value = "It's nice out! Enjoy a discount on us." gif_link = 'https://media.giphy.com/media/nYiHd4Mh3w6fS/giphy.gif' elif any(x in today_weather for x in precipitation_words): logging.info('precipitation') subject_value = "Not so nice out? That's okay, enjoy a discount on us." gif_link = 'https://media.giphy.com/media/1hM7Uh46ixnsWRMA7w/giphy.gif' elif today_F + 5 <= tomorrow_F: logging.info('cold') subject_value = "Not so nice out? That's okay, enjoy a discount on us." gif_link = 'https://media.giphy.com/media/26FLdaDQ5f72FPbEI/giphy.gif' else: logging.info('other') subject_value = "Enjoy a discount on us." gif_link = 'https://media.giphy.com/media/3o6vXNLzXdW4sbFRGo/giphy.gif' with app.app_context(): with email_service.connect() as conn: for recipient in recipients: msg = Message(subject_value,recipients=[recipient],sender="<EMAIL>") msg.html = """ %s - %s degrees F - %s <br><br><img src="%s" \ width="640" height="480"> """ % (city_dict[str(city_id)], \ today_F, today_weather, gif_link) try: conn.send(msg) except: logging.error('failed to send to %s' % recipient) return logging.info('finished weather email service') # today's date dateFact = datetime.datetime.now().strftime("%Y-%m-%d") # tomorrow's date tomorrow = str((datetime.datetime.now() + datetime.timedelta(1)).strftime('%Y-%m-%d')) # weather api service weather_api_service(cityIDset, dateFact, tomorrow, mysql_conn, city_dict) # weather email service weather_email_service(email_service, app, mysql_conn, city_dict)
weather_api_and_email_service.py
from flask import Flask from flask_mail import Mail, Message import pandas as pd import logging import requests import time from local_settings import * import datetime import gc import pymysql import warnings app = Flask(__name__) email_service = Mail(app) # ensure info logs are printed logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.INFO, datefmt='%m/%d/%Y %I:%M:%S %p') # connect to sql def getSQLConn(host, user, password): return pymysql.connect(host=host,\ user=user,\ passwd=password, autocommit=True) mysql_conn = getSQLConn(MYSQL_AUTH['host'], MYSQL_AUTH['user'], MYSQL_AUTH['password']) # run query def runQuery(mysql_conn, query): with mysql_conn.cursor() as cursor: with warnings.catch_warnings(): warnings.simplefilter('ignore') cursor.execute(query) # convert Kelvin to Fahrenheit def K_to_F(degrees_kelvin): return int((float(degrees_kelvin) * (9/5)) - 459.67) def weather_api_service(cityIDset, dateFact, tomorrow, mysql_conn, city_dict): # truncate table tblFactCityWeather with current data and data older than 10 days query = """DELETE from klaviyo.tblFactCityWeather where dateFact=CURRENT_DATE or dateFact<date_sub(CURRENT_DATE, interval 10 day) """ runQuery(mysql_conn, query) for _i, cityID in enumerate(cityIDset): # current weather api call r = requests.get('http://api.openweathermap.org/data/2.5/weather?id=%s&appid=%s' % \ (cityID, OPENWEATHERMAP_AUTH['api_key'])) obj = r.json() today_weather = '-'.join([obj['weather'][0]['main'], obj['weather'][0]['description']]) today_max_degrees_F = K_to_F(obj['main']['temp_max']) time.sleep(1.5) # reduce cadence of api calls # forecast weather api call r = requests.get('http://api.openweathermap.org/data/2.5/forecast?id=%s&appid=%s' % \ (cityID, OPENWEATHERMAP_AUTH['api_key'])) obj = r.json() # ony get objects for tmrw tmrw_objs = [x for x in obj['list'] if x['dt_txt'][0:10] == tomorrow] tomorrow_max_degrees_F = K_to_F(max([tmrw_obj['main']['temp_max'] for tmrw_obj in tmrw_objs])) query = "INSERT INTO klaviyo.tblFactCityWeather(city_id, dateFact, today_weather, today_max_degrees_F, \ tomorrow_max_degrees_F) VALUES (%i, '%s', '%s', %i, %i)" % (cityID, dateFact, today_weather, today_max_degrees_F, \ tomorrow_max_degrees_F) runQuery(mysql_conn, query) logging.info('%s - %s - %s - %s - %s - %s' % (city_dict[str(cityID)], cityID, dateFact, today_weather, \ today_max_degrees_F, tomorrow_max_degrees_F)) if _i % 20 == 5: gc.collect(); return logging.info('finished weather api service') def weather_email_service(email_service, app, mysql_conn, city_dict): # truncate table tblDimEmailCity with subscriptions older than 10 days truncate_query = """DELETE from klaviyo.tblDimEmailCity where sign_up_date<date_sub(CURRENT_DATE, interval 10 day) """ runQuery(mysql_conn, truncate_query) # tblDimEmailCity --> pandas dataframe & constrain city ids to consider by data in tblDimEmailCity tblDimEmailCity = pd.read_sql_query('SELECT email, city_id FROM klaviyo.tblDimEmailCity', con=mysql_conn) city_id_set = set(tblDimEmailCity['city_id']) city_id_string = str(city_id_set).replace('{','').replace('}','') # create tblFactCityWeather_dict for today's weather api data constrained to city_id_set tfcw_df = pd.read_sql_query('SELECT city_id, today_weather, today_max_degrees_F, tomorrow_max_degrees_F \ FROM klaviyo.tblFactCityWeather where dateFact=CURRENT_DATE and city_id in (%s)' % (city_id_string), con=mysql_conn) tblFactCityWeather_dict = dict() zipped_array = zip(tfcw_df['city_id'], tfcw_df['today_weather'], tfcw_df['today_max_degrees_F'], tfcw_df['tomorrow_max_degrees_F']) for city_id, today_weather, today_F, tomorrow_F in zipped_array: tblFactCityWeather_dict[city_id] = [str(today_weather).lower(), int(today_F), int(tomorrow_F)] for city_id in city_id_set: gc.collect(); # find set of recipients per city id _tblDimEmailCity = tblDimEmailCity[tblDimEmailCity['city_id'] == city_id] _tblDimEmailCity = _tblDimEmailCity.reset_index(drop = True) recipients = set(_tblDimEmailCity['email']) logging.info('recipients = %s' % recipients) today_weather = tblFactCityWeather_dict[city_id][0] today_F = tblFactCityWeather_dict[city_id][1] tomorrow_F = tblFactCityWeather_dict[city_id][2] # subject_value + gif_link logic precipitation_words = ['mist','rain','sleet','snow','hail'] sunny_words = ['sunny','clear'] if any(x in today_weather for x in sunny_words): logging.info('sunny') subject_value = "It's nice out! Enjoy a discount on us." gif_link = 'https://media.giphy.com/media/nYiHd4Mh3w6fS/giphy.gif' elif today_F >= tomorrow_F + 5: logging.info('warm') subject_value = "It's nice out! Enjoy a discount on us." gif_link = 'https://media.giphy.com/media/nYiHd4Mh3w6fS/giphy.gif' elif any(x in today_weather for x in precipitation_words): logging.info('precipitation') subject_value = "Not so nice out? That's okay, enjoy a discount on us." gif_link = 'https://media.giphy.com/media/1hM7Uh46ixnsWRMA7w/giphy.gif' elif today_F + 5 <= tomorrow_F: logging.info('cold') subject_value = "Not so nice out? That's okay, enjoy a discount on us." gif_link = 'https://media.giphy.com/media/26FLdaDQ5f72FPbEI/giphy.gif' else: logging.info('other') subject_value = "Enjoy a discount on us." gif_link = 'https://media.giphy.com/media/3o6vXNLzXdW4sbFRGo/giphy.gif' with app.app_context(): with email_service.connect() as conn: for recipient in recipients: msg = Message(subject_value,recipients=[recipient],sender="<EMAIL>") msg.html = """ %s - %s degrees F - %s <br><br><img src="%s" \ width="640" height="480"> """ % (city_dict[str(city_id)], \ today_F, today_weather, gif_link) try: conn.send(msg) except: logging.error('failed to send to %s' % recipient) return logging.info('finished weather email service') # today's date dateFact = datetime.datetime.now().strftime("%Y-%m-%d") # tomorrow's date tomorrow = str((datetime.datetime.now() + datetime.timedelta(1)).strftime('%Y-%m-%d')) # weather api service weather_api_service(cityIDset, dateFact, tomorrow, mysql_conn, city_dict) # weather email service weather_email_service(email_service, app, mysql_conn, city_dict)
0.247532
0.100172
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.svm import LinearSVC from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score from sklearn.preprocessing import PolynomialFeatures import matplotlib.pyplot as plt import matplotlib.colors as mc import random import colorsys from radonComputation import * import math import pickle import os def getACC(model, X, y): y_pred = model.predict(X) return accuracy_score(y, y_pred) def lighten_color(color, amount=0.5): try: c = mc.cnames[color] except: c = color c = colorsys.rgb_to_hls(*mc.to_rgb(c)) return colorsys.hls_to_rgb(c[0], 1 - amount * (1 - c[1]), c[2]) def plotACCs(ax, accs, label, color=None, alpha=0.5): X = range(len(accs)) m = len(accs[0]) amount = 0.8/m mean = [np.mean(accs[i]) for i in X] p = ax.plot(X,mean,label=label, zorder=m+1, color=color, linewidth=2) baseColor = p[0].get_color() for i in range(m): acc = [a[i] for a in accs] adjColor = lighten_color(baseColor, i*amount + 0.1) ax.plot(X,acc, c=adjColor, alpha=alpha) def plotResults(trainACCs, testACCs, title, exp_path, bSave = True): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) plotACCs(ax, trainACCs, 'train') plotACCs(ax, testACCs, 'test') plt.legend() plt.title(title) if bSave: plt.savefig(os.path.join(exp_path, "results.png"), dpi=300) else: plt.show() def plotComparison(trainACCs1, testACCs1, trainACCs2, testACCs2, method1, method2, colors=None, alphas=[0.5,0.5], filename=None): fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(13.0,4.8)) fig.suptitle('Comparison '+method1+' vs '+method2) rounds = len(trainACCs1) plotACCs(ax1, trainACCs1, method1+'_train', color = None if colors == None else colors[0], alpha=alphas[0]) plotACCs(ax1, testACCs1, method1+'_test', color = None if colors == None else colors[1], alpha=alphas[0]) plotACCs(ax2, trainACCs2, method2+'_train', color = None if colors == None else colors[2], alpha=alphas[1]) plotACCs(ax2, testACCs2, method2+'_test', color = None if colors == None else colors[3], alpha=alphas[1]) ax1.legend() ax2.legend() ax1.set_title(method1) ax2.set_title(method2) ax1.set_xlabel("rounds") ax2.set_xlabel("rounds") ax1.set_ylabel("accuracy") plt.subplots_adjust(wspace=0.1, hspace=0) if filename is not None: plt.savefig(filename) plt.show() def splitIntoLocalData(X_train, y_train, m, n_local, rng): n = y_train.shape[0] if m*n_local > n: print("Error: not enough data (n=",n,") for",m,"sets of size ",n_local,". Reducing local size to",n//m,".") n_local = n // m idxs = np.arange(n) rng.shuffle(idxs) bucket_size = n_local i = 0 Xs, Ys = [],[] while (i+1)*bucket_size <= n and i < m: idx = idxs[i*bucket_size:(i+1)*bucket_size] Xs.append(X_train[idx,:]) Ys.append(y_train[idx]) i += 1 return Xs, Ys def averageSVCs(models): m = len(models) avgCoef = np.zeros(models[0].coef_.shape) avgIntercept = np.zeros(models[0].intercept_.shape) for model in models: avgCoef += model.coef_.copy() avgIntercept += model.intercept_.copy() avgCoef /= float(m) avgIntercept /= float(m) for model in models: model.coef_ = avgCoef.copy() model.intercept_ = avgIntercept.copy() return models def simpleDaisyChain(models, perm): models = models[perm] return models def runAveraging(local_Xtrains, local_ytrains, localModels, X_test, y_test, rounds, rng, b=1, classes = None): trainACCs, testACCs = [], [] m = len(localModels) if classes is None: classes = np.unique(y_test) trainACCs, testACCs = [],[] for r in range(rounds): for i in range(m): localModels[i].partial_fit(local_Xtrains[i], local_ytrains[i], classes = classes) if (r+1) % b == 0: #we don't want to average in the first round... localModels = averageSVCs(localModels) trainACCs.append([]) testACCs.append([]) for i in range(m): trainACCs[-1].append(getACC(localModels[i], local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(localModels[i], X_test, y_test)) #final model avgModel = averageSVCs(localModels)[0] for i in range(m): trainACCs[-1].append(getACC(avgModel, local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(avgModel, X_test, y_test)) return avgModel, trainACCs, testACCs def runSimpleDaisyChaining(local_Xtrains, local_ytrains, localModels, X_test, y_test, rounds, rng, b=1, classes = None, fix_permutation=False): trainACCs, testACCs = [], [] m = len(localModels) if classes is None: classes = np.unique(y_test) trainACCs, testACCs = [],[] perm = np.arange(m) rng.shuffle(perm) for r in range(rounds): for i in range(m): localModels[i].partial_fit(local_Xtrains[i], local_ytrains[i], classes = classes) if r % b == 0: if not fix_permutation: rng.shuffle(perm) localModels = simpleDaisyChain(localModels, perm) trainACCs.append([]) testACCs.append([]) for i in range(m): trainACCs[-1].append(getACC(localModels[i], local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(localModels[i], X_test, y_test)) #final model avgModel = averageSVCs(localModels)[0] for i in range(m): trainACCs[-1].append(getACC(avgModel, local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(avgModel, X_test, y_test)) return avgModel, trainACCs, testACCs def runAverageAndDaisyChaining(local_Xtrains, local_ytrains, localModels, X_test, y_test, rounds, rng, b=1, bavg = 2, classes = None, fix_permutation=False): trainACCs, testACCs = [], [] m = len(localModels) if classes is None: classes = np.unique(y_test) trainACCs, testACCs = [],[] perm = np.arange(m) rng.shuffle(perm) for r in range(rounds): for i in range(m): localModels[i].partial_fit(local_Xtrains[i], local_ytrains[i], classes = classes) if r % b == 0: if not fix_permutation: rng.shuffle(perm) localModels = simpleDaisyChain(localModels, perm) if (r+1) % bavg == 0: localModels = averageSVCs(localModels) trainACCs.append([]) testACCs.append([]) for i in range(m): trainACCs[-1].append(getACC(localModels[i], local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(localModels[i], X_test, y_test)) #final model avgModel = averageSVCs(localModels)[0] for i in range(m): trainACCs[-1].append(getACC(avgModel, local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(avgModel, X_test, y_test)) return avgModel, trainACCs, testACCs def radonPointLinearModelsMaxH(models): m = len(models) S = [] coefDim = len(models[0].coef_[0].tolist()) interceptDim = 1 radonNumber = coefDim + interceptDim + 2 maxHeight = math.floor(math.log(m)/math.log(radonNumber)) for model in models: s = model.coef_[0].tolist() s.append(model.intercept_[0]) S.append(s) S = np.array(S) r = getRadonPointHierarchical(S,maxHeight) for model in models: model.coef_ = np.array(r[:coefDim]).reshape(1,coefDim) model.intercept_ = np.array(r[coefDim:]) return models def simpleDaisyChain(models, perm): models = models[perm] return models def runRadonPoint(local_Xtrains, local_ytrains, localModels, X_test, y_test, rounds, rng, b=1, classes = None, exp_path = ""): trainACCs, testACCs = [], [] m = len(localModels) if classes is None: classes = np.unique(y_test) trainACCs, testACCs = [],[] for r in range(rounds): for i in range(m): localModels[i].partial_fit(local_Xtrains[i], local_ytrains[i], classes = classes) if (r+1) % b == 0: #we don't want to average in the first round... localModels = radonPointLinearModelsMaxH(localModels) trainACCs.append([]) testACCs.append([]) for i in range(m): trainACCs[-1].append(getACC(localModels[i], local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(localModels[i], X_test, y_test)) if r % 10 == 0: print("round ",r) pickle.dump(trainACCs, open(os.path.join(exp_path, "trainACCs_tmp.pck"),'wb')) pickle.dump(testACCs, open(os.path.join(exp_path, "testACCs_tmp.pck"),'wb')) #final model avgModel = radonPointLinearModelsMaxH(localModels)[0] for i in range(m): trainACCs[-1].append(getACC(avgModel, local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(avgModel, X_test, y_test)) return avgModel, trainACCs, testACCs def runSimpleDaisyChaining(local_Xtrains, local_ytrains, localModels, X_test, y_test, rounds, rng, b=1, classes = None, fix_permutation=False): trainACCs, testACCs = [], [] m = len(localModels) if classes is None: classes = np.unique(y_test) trainACCs, testACCs = [],[] perm = np.arange(m) rng.shuffle(perm) for r in range(rounds): for i in range(m): localModels[i].partial_fit(local_Xtrains[i], local_ytrains[i], classes = classes) if r % b == 0: if not fix_permutation: rng.shuffle(perm) localModels = simpleDaisyChain(localModels, perm) trainACCs.append([]) testACCs.append([]) for i in range(m): trainACCs[-1].append(getACC(localModels[i], local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(localModels[i], X_test, y_test)) #final model avgModel = averageSVCs(localModels)[0] for i in range(m): trainACCs[-1].append(getACC(avgModel, local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(avgModel, X_test, y_test)) return avgModel, trainACCs, testACCs def runRadonPointAndDaisyChaining(local_Xtrains, local_ytrains, localModels, X_test, y_test, rounds, rng, b=1, bavg = 2, classes = None, fix_permutation=False, exp_path = ""): trainACCs, testACCs = [], [] m = len(localModels) if classes is None: classes = np.unique(y_test) trainACCs, testACCs = [],[] perm = np.arange(m) rng.shuffle(perm) for r in range(rounds): for i in range(m): localModels[i].partial_fit(local_Xtrains[i], local_ytrains[i], classes = classes) if r % b == 0: if not fix_permutation: rng.shuffle(perm) localModels = simpleDaisyChain(localModels, perm) if (r+1) % bavg == 0: localModels = radonPointLinearModelsMaxH(localModels) trainACCs.append([]) testACCs.append([]) for i in range(m): trainACCs[-1].append(getACC(localModels[i], local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(localModels[i], X_test, y_test)) if r % 10 == 0: print("round ",r) pickle.dump(trainACCs, open(os.path.join(exp_path, "trainACCs_tmp.pck"),'wb')) pickle.dump(testACCs, open(os.path.join(exp_path, "testACCs_tmp.pck"),'wb')) #final model avgModel = radonPointLinearModelsMaxH(localModels)[0] for i in range(m): trainACCs[-1].append(getACC(avgModel, local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(avgModel, X_test, y_test)) return avgModel, trainACCs, testACCs
SUSY_Radon/utils.py
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.svm import LinearSVC from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score from sklearn.preprocessing import PolynomialFeatures import matplotlib.pyplot as plt import matplotlib.colors as mc import random import colorsys from radonComputation import * import math import pickle import os def getACC(model, X, y): y_pred = model.predict(X) return accuracy_score(y, y_pred) def lighten_color(color, amount=0.5): try: c = mc.cnames[color] except: c = color c = colorsys.rgb_to_hls(*mc.to_rgb(c)) return colorsys.hls_to_rgb(c[0], 1 - amount * (1 - c[1]), c[2]) def plotACCs(ax, accs, label, color=None, alpha=0.5): X = range(len(accs)) m = len(accs[0]) amount = 0.8/m mean = [np.mean(accs[i]) for i in X] p = ax.plot(X,mean,label=label, zorder=m+1, color=color, linewidth=2) baseColor = p[0].get_color() for i in range(m): acc = [a[i] for a in accs] adjColor = lighten_color(baseColor, i*amount + 0.1) ax.plot(X,acc, c=adjColor, alpha=alpha) def plotResults(trainACCs, testACCs, title, exp_path, bSave = True): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) plotACCs(ax, trainACCs, 'train') plotACCs(ax, testACCs, 'test') plt.legend() plt.title(title) if bSave: plt.savefig(os.path.join(exp_path, "results.png"), dpi=300) else: plt.show() def plotComparison(trainACCs1, testACCs1, trainACCs2, testACCs2, method1, method2, colors=None, alphas=[0.5,0.5], filename=None): fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(13.0,4.8)) fig.suptitle('Comparison '+method1+' vs '+method2) rounds = len(trainACCs1) plotACCs(ax1, trainACCs1, method1+'_train', color = None if colors == None else colors[0], alpha=alphas[0]) plotACCs(ax1, testACCs1, method1+'_test', color = None if colors == None else colors[1], alpha=alphas[0]) plotACCs(ax2, trainACCs2, method2+'_train', color = None if colors == None else colors[2], alpha=alphas[1]) plotACCs(ax2, testACCs2, method2+'_test', color = None if colors == None else colors[3], alpha=alphas[1]) ax1.legend() ax2.legend() ax1.set_title(method1) ax2.set_title(method2) ax1.set_xlabel("rounds") ax2.set_xlabel("rounds") ax1.set_ylabel("accuracy") plt.subplots_adjust(wspace=0.1, hspace=0) if filename is not None: plt.savefig(filename) plt.show() def splitIntoLocalData(X_train, y_train, m, n_local, rng): n = y_train.shape[0] if m*n_local > n: print("Error: not enough data (n=",n,") for",m,"sets of size ",n_local,". Reducing local size to",n//m,".") n_local = n // m idxs = np.arange(n) rng.shuffle(idxs) bucket_size = n_local i = 0 Xs, Ys = [],[] while (i+1)*bucket_size <= n and i < m: idx = idxs[i*bucket_size:(i+1)*bucket_size] Xs.append(X_train[idx,:]) Ys.append(y_train[idx]) i += 1 return Xs, Ys def averageSVCs(models): m = len(models) avgCoef = np.zeros(models[0].coef_.shape) avgIntercept = np.zeros(models[0].intercept_.shape) for model in models: avgCoef += model.coef_.copy() avgIntercept += model.intercept_.copy() avgCoef /= float(m) avgIntercept /= float(m) for model in models: model.coef_ = avgCoef.copy() model.intercept_ = avgIntercept.copy() return models def simpleDaisyChain(models, perm): models = models[perm] return models def runAveraging(local_Xtrains, local_ytrains, localModels, X_test, y_test, rounds, rng, b=1, classes = None): trainACCs, testACCs = [], [] m = len(localModels) if classes is None: classes = np.unique(y_test) trainACCs, testACCs = [],[] for r in range(rounds): for i in range(m): localModels[i].partial_fit(local_Xtrains[i], local_ytrains[i], classes = classes) if (r+1) % b == 0: #we don't want to average in the first round... localModels = averageSVCs(localModels) trainACCs.append([]) testACCs.append([]) for i in range(m): trainACCs[-1].append(getACC(localModels[i], local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(localModels[i], X_test, y_test)) #final model avgModel = averageSVCs(localModels)[0] for i in range(m): trainACCs[-1].append(getACC(avgModel, local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(avgModel, X_test, y_test)) return avgModel, trainACCs, testACCs def runSimpleDaisyChaining(local_Xtrains, local_ytrains, localModels, X_test, y_test, rounds, rng, b=1, classes = None, fix_permutation=False): trainACCs, testACCs = [], [] m = len(localModels) if classes is None: classes = np.unique(y_test) trainACCs, testACCs = [],[] perm = np.arange(m) rng.shuffle(perm) for r in range(rounds): for i in range(m): localModels[i].partial_fit(local_Xtrains[i], local_ytrains[i], classes = classes) if r % b == 0: if not fix_permutation: rng.shuffle(perm) localModels = simpleDaisyChain(localModels, perm) trainACCs.append([]) testACCs.append([]) for i in range(m): trainACCs[-1].append(getACC(localModels[i], local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(localModels[i], X_test, y_test)) #final model avgModel = averageSVCs(localModels)[0] for i in range(m): trainACCs[-1].append(getACC(avgModel, local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(avgModel, X_test, y_test)) return avgModel, trainACCs, testACCs def runAverageAndDaisyChaining(local_Xtrains, local_ytrains, localModels, X_test, y_test, rounds, rng, b=1, bavg = 2, classes = None, fix_permutation=False): trainACCs, testACCs = [], [] m = len(localModels) if classes is None: classes = np.unique(y_test) trainACCs, testACCs = [],[] perm = np.arange(m) rng.shuffle(perm) for r in range(rounds): for i in range(m): localModels[i].partial_fit(local_Xtrains[i], local_ytrains[i], classes = classes) if r % b == 0: if not fix_permutation: rng.shuffle(perm) localModels = simpleDaisyChain(localModels, perm) if (r+1) % bavg == 0: localModels = averageSVCs(localModels) trainACCs.append([]) testACCs.append([]) for i in range(m): trainACCs[-1].append(getACC(localModels[i], local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(localModels[i], X_test, y_test)) #final model avgModel = averageSVCs(localModels)[0] for i in range(m): trainACCs[-1].append(getACC(avgModel, local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(avgModel, X_test, y_test)) return avgModel, trainACCs, testACCs def radonPointLinearModelsMaxH(models): m = len(models) S = [] coefDim = len(models[0].coef_[0].tolist()) interceptDim = 1 radonNumber = coefDim + interceptDim + 2 maxHeight = math.floor(math.log(m)/math.log(radonNumber)) for model in models: s = model.coef_[0].tolist() s.append(model.intercept_[0]) S.append(s) S = np.array(S) r = getRadonPointHierarchical(S,maxHeight) for model in models: model.coef_ = np.array(r[:coefDim]).reshape(1,coefDim) model.intercept_ = np.array(r[coefDim:]) return models def simpleDaisyChain(models, perm): models = models[perm] return models def runRadonPoint(local_Xtrains, local_ytrains, localModels, X_test, y_test, rounds, rng, b=1, classes = None, exp_path = ""): trainACCs, testACCs = [], [] m = len(localModels) if classes is None: classes = np.unique(y_test) trainACCs, testACCs = [],[] for r in range(rounds): for i in range(m): localModels[i].partial_fit(local_Xtrains[i], local_ytrains[i], classes = classes) if (r+1) % b == 0: #we don't want to average in the first round... localModels = radonPointLinearModelsMaxH(localModels) trainACCs.append([]) testACCs.append([]) for i in range(m): trainACCs[-1].append(getACC(localModels[i], local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(localModels[i], X_test, y_test)) if r % 10 == 0: print("round ",r) pickle.dump(trainACCs, open(os.path.join(exp_path, "trainACCs_tmp.pck"),'wb')) pickle.dump(testACCs, open(os.path.join(exp_path, "testACCs_tmp.pck"),'wb')) #final model avgModel = radonPointLinearModelsMaxH(localModels)[0] for i in range(m): trainACCs[-1].append(getACC(avgModel, local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(avgModel, X_test, y_test)) return avgModel, trainACCs, testACCs def runSimpleDaisyChaining(local_Xtrains, local_ytrains, localModels, X_test, y_test, rounds, rng, b=1, classes = None, fix_permutation=False): trainACCs, testACCs = [], [] m = len(localModels) if classes is None: classes = np.unique(y_test) trainACCs, testACCs = [],[] perm = np.arange(m) rng.shuffle(perm) for r in range(rounds): for i in range(m): localModels[i].partial_fit(local_Xtrains[i], local_ytrains[i], classes = classes) if r % b == 0: if not fix_permutation: rng.shuffle(perm) localModels = simpleDaisyChain(localModels, perm) trainACCs.append([]) testACCs.append([]) for i in range(m): trainACCs[-1].append(getACC(localModels[i], local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(localModels[i], X_test, y_test)) #final model avgModel = averageSVCs(localModels)[0] for i in range(m): trainACCs[-1].append(getACC(avgModel, local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(avgModel, X_test, y_test)) return avgModel, trainACCs, testACCs def runRadonPointAndDaisyChaining(local_Xtrains, local_ytrains, localModels, X_test, y_test, rounds, rng, b=1, bavg = 2, classes = None, fix_permutation=False, exp_path = ""): trainACCs, testACCs = [], [] m = len(localModels) if classes is None: classes = np.unique(y_test) trainACCs, testACCs = [],[] perm = np.arange(m) rng.shuffle(perm) for r in range(rounds): for i in range(m): localModels[i].partial_fit(local_Xtrains[i], local_ytrains[i], classes = classes) if r % b == 0: if not fix_permutation: rng.shuffle(perm) localModels = simpleDaisyChain(localModels, perm) if (r+1) % bavg == 0: localModels = radonPointLinearModelsMaxH(localModels) trainACCs.append([]) testACCs.append([]) for i in range(m): trainACCs[-1].append(getACC(localModels[i], local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(localModels[i], X_test, y_test)) if r % 10 == 0: print("round ",r) pickle.dump(trainACCs, open(os.path.join(exp_path, "trainACCs_tmp.pck"),'wb')) pickle.dump(testACCs, open(os.path.join(exp_path, "testACCs_tmp.pck"),'wb')) #final model avgModel = radonPointLinearModelsMaxH(localModels)[0] for i in range(m): trainACCs[-1].append(getACC(avgModel, local_Xtrains[i], local_ytrains[i])) testACCs[-1].append(getACC(avgModel, X_test, y_test)) return avgModel, trainACCs, testACCs
0.420719
0.45538
"""create_gt_txt_from_mat.py""" import os import argparse import tqdm import numpy as np from scipy.io import loadmat from cython_bbox import bbox_overlaps _MAP = { '0': '0--Parade', '1': '1--Handshaking', '2': '2--Demonstration', '3': '3--Riot', '4': '4--Dancing', '5': '5--Car_Accident', '6': '6--Funeral', '7': '7--Cheering', '8': '8--Election_Campain', '9': '9--Press_Conference', '10': '10--People_Marching', '11': '11--Meeting', '12': '12--Group', '13': '13--Interview', '14': '14--Traffic', '15': '15--Stock_Market', '16': '16--Award_Ceremony', '17': '17--Ceremony', '18': '18--Concerts', '19': '19--Couple', '20': '20--Family_Group', '21': '21--Festival', '22': '22--Picnic', '23': '23--Shoppers', '24': '24--Soldier_Firing', '25': '25--Soldier_Patrol', '26': '26--Soldier_Drilling', '27': '27--Spa', '28': '28--Sports_Fan', '29': '29--Students_Schoolkids', '30': '30--Surgeons', '31': '31--Waiter_Waitress', '32': '32--Worker_Laborer', '33': '33--Running', '34': '34--Baseball', '35': '35--Basketball', '36': '36--Football', '37': '37--Soccer', '38': '38--Tennis', '39': '39--Ice_Skating', '40': '40--Gymnastics', '41': '41--Swimming', '42': '42--Car_Racing', '43': '43--Row_Boat', '44': '44--Aerobics', '45': '45--Balloonist', '46': '46--Jockey', '47': '47--Matador_Bullfighter', '48': '48--Parachutist_Paratrooper', '49': '49--Greeting', '50': '50--Celebration_Or_Party', '51': '51--Dresses', '52': '52--Photographers', '53': '53--Raid', '54': '54--Rescue', '55': '55--Sports_Coach_Trainer', '56': '56--Voter', '57': '57--Angler', '58': '58--Hockey', '59': '59--people--driving--car', '61': '61--Street_Battle' } def get_gt_boxes(gt_dir): """ gt dir: (wider_face_val.mat, wider_easy_val.mat, wider_medium_val.mat, wider_hard_val.mat)""" gt_mat = loadmat(os.path.join(gt_dir, 'wider_face_val.mat')) hard_mat = loadmat(os.path.join(gt_dir, 'wider_hard_val.mat')) medium_mat = loadmat(os.path.join(gt_dir, 'wider_medium_val.mat')) easy_mat = loadmat(os.path.join(gt_dir, 'wider_easy_val.mat')) facebox_list = gt_mat['face_bbx_list'] event_list = gt_mat['event_list'] file_list = gt_mat['file_list'] hard_gt_list = hard_mat['gt_list'] medium_gt_list = medium_mat['gt_list'] easy_gt_list = easy_mat['gt_list'] return facebox_list, event_list, file_list, hard_gt_list, medium_gt_list, easy_gt_list def norm_score(pred): """ norm score pred {key: [[x1,y1,x2,y2,s]]} """ max_score = 0 min_score = 1 for _, k in pred.items(): for _, v in k.items(): if v: _min = np.min(v[:, -1]) _max = np.max(v[:, -1]) max_score = max(_max, max_score) min_score = min(_min, min_score) else: continue diff = max_score - min_score for _, k in pred.items(): for _, v in k.items(): if v: v[:, -1] = (v[:, -1] - min_score) / diff else: continue def image_eval(pred, gt, ignore, iou_thresh): """ single image evaluation pred: Nx5 gt: Nx4 ignore: """ _pred = pred.copy() _gt = gt.copy() pred_recall = np.zeros(_pred.shape[0]) recall_list = np.zeros(_gt.shape[0]) proposal_list = np.ones(_pred.shape[0]) _pred[:, 2] = _pred[:, 2] + _pred[:, 0] _pred[:, 3] = _pred[:, 3] + _pred[:, 1] _gt[:, 2] = _gt[:, 2] + _gt[:, 0] _gt[:, 3] = _gt[:, 3] + _gt[:, 1] overlaps = bbox_overlaps(_pred[:, :4], _gt) for h in range(_pred.shape[0]): gt_overlap = overlaps[h] max_overlap, max_idx = gt_overlap.max(), gt_overlap.argmax() if max_overlap >= iou_thresh: if ignore[max_idx] == 0: recall_list[max_idx] = -1 proposal_list[h] = -1 elif recall_list[max_idx] == 0: recall_list[max_idx] = 1 r_keep_index = np.where(recall_list == 1)[0] pred_recall[h] = len(r_keep_index) return pred_recall, proposal_list def img_pr_info(thresh_num, pred_info, proposal_list, pred_recall): """ img_pr_info """ pr_info = np.zeros((thresh_num, 2)).astype('float') for t in range(thresh_num): thresh = 1 - (t + 1) / thresh_num r_index = np.where(pred_info[:, 4] >= thresh)[0] if r_index: r_index = r_index[-1] p_index = np.where(proposal_list[:r_index + 1] == 1)[0] pr_info[t, 0] = len(p_index) pr_info[t, 1] = pred_recall[r_index] else: pr_info[t, 0] = 0 pr_info[t, 1] = 0 return pr_info def dataset_pr_info(thresh_num, pr_curve, count_face): _pr_curve = np.zeros((thresh_num, 2)) for i in range(thresh_num): _pr_curve[i, 0] = pr_curve[i, 1] / pr_curve[i, 0] _pr_curve[i, 1] = pr_curve[i, 1] / count_face return _pr_curve def voc_ap(rec, prec): """ voc_ap """ # correct AP calculation # first append sentinel values at the end mrec = np.concatenate(([0.], rec, [1.])) mpre = np.concatenate(([0.], prec, [0.])) # compute the precision envelope for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrec[1:] != mrec[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap def evaluation(pred, gt_path, iou_thresh=0.5): """ evaluation """ facebox_list, event_list, file_list, hard_gt_list, medium_gt_list, easy_gt_list = get_gt_boxes(gt_path) event_num = len(event_list) settings = ['easy', 'medium', 'hard'] setting_gts = [easy_gt_list, medium_gt_list, hard_gt_list] for setting_id in range(3): # different setting gt_list = setting_gts[setting_id] # [hard, medium, easy] pbar = tqdm.tqdm(range(event_num)) outputTxtDir = './bbx_gt_txt/' if not os.path.exists(outputTxtDir): os.makedirs(outputTxtDir) outputTxtFile = outputTxtDir + settings[setting_id] + '.txt' if os.path.exists(outputTxtFile): os.remove(outputTxtFile) for i in pbar: pbar.set_description('Processing {}'.format(settings[setting_id])) img_list = file_list[i][0] sub_gt_list = gt_list[i][0] gt_bbx_list = facebox_list[i][0] for j in range(len(img_list)): gt_boxes = gt_bbx_list[j][0] keep_index = sub_gt_list[j][0] imgName = img_list[j][0][0] imgPath = _MAP[imgName.split('_')[0]] + '/' + imgName + '.jpg' faceNum = len(keep_index) with open(outputTxtFile, 'a') as txtFile: txtFile.write(imgPath + '\n') txtFile.write(str(faceNum) + '\n') if faceNum == 0: txtFile.write(str(faceNum) + '\n') for index in keep_index: curI = index[0] - 1 bbox = gt_boxes[curI] txtFile.write('%d %d %d %d\n' % (bbox[0], bbox[1], bbox[2], bbox[3])) txtFile.close() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-p', '--pred') parser.add_argument('-g', '--gt', default='./eval_tools/ground_truth/') args = parser.parse_args() evaluation(args.pred, args.gt)
research/cv/FaceDetection/infer/dataset_val/create_gt_txt_from_mat.py
"""create_gt_txt_from_mat.py""" import os import argparse import tqdm import numpy as np from scipy.io import loadmat from cython_bbox import bbox_overlaps _MAP = { '0': '0--Parade', '1': '1--Handshaking', '2': '2--Demonstration', '3': '3--Riot', '4': '4--Dancing', '5': '5--Car_Accident', '6': '6--Funeral', '7': '7--Cheering', '8': '8--Election_Campain', '9': '9--Press_Conference', '10': '10--People_Marching', '11': '11--Meeting', '12': '12--Group', '13': '13--Interview', '14': '14--Traffic', '15': '15--Stock_Market', '16': '16--Award_Ceremony', '17': '17--Ceremony', '18': '18--Concerts', '19': '19--Couple', '20': '20--Family_Group', '21': '21--Festival', '22': '22--Picnic', '23': '23--Shoppers', '24': '24--Soldier_Firing', '25': '25--Soldier_Patrol', '26': '26--Soldier_Drilling', '27': '27--Spa', '28': '28--Sports_Fan', '29': '29--Students_Schoolkids', '30': '30--Surgeons', '31': '31--Waiter_Waitress', '32': '32--Worker_Laborer', '33': '33--Running', '34': '34--Baseball', '35': '35--Basketball', '36': '36--Football', '37': '37--Soccer', '38': '38--Tennis', '39': '39--Ice_Skating', '40': '40--Gymnastics', '41': '41--Swimming', '42': '42--Car_Racing', '43': '43--Row_Boat', '44': '44--Aerobics', '45': '45--Balloonist', '46': '46--Jockey', '47': '47--Matador_Bullfighter', '48': '48--Parachutist_Paratrooper', '49': '49--Greeting', '50': '50--Celebration_Or_Party', '51': '51--Dresses', '52': '52--Photographers', '53': '53--Raid', '54': '54--Rescue', '55': '55--Sports_Coach_Trainer', '56': '56--Voter', '57': '57--Angler', '58': '58--Hockey', '59': '59--people--driving--car', '61': '61--Street_Battle' } def get_gt_boxes(gt_dir): """ gt dir: (wider_face_val.mat, wider_easy_val.mat, wider_medium_val.mat, wider_hard_val.mat)""" gt_mat = loadmat(os.path.join(gt_dir, 'wider_face_val.mat')) hard_mat = loadmat(os.path.join(gt_dir, 'wider_hard_val.mat')) medium_mat = loadmat(os.path.join(gt_dir, 'wider_medium_val.mat')) easy_mat = loadmat(os.path.join(gt_dir, 'wider_easy_val.mat')) facebox_list = gt_mat['face_bbx_list'] event_list = gt_mat['event_list'] file_list = gt_mat['file_list'] hard_gt_list = hard_mat['gt_list'] medium_gt_list = medium_mat['gt_list'] easy_gt_list = easy_mat['gt_list'] return facebox_list, event_list, file_list, hard_gt_list, medium_gt_list, easy_gt_list def norm_score(pred): """ norm score pred {key: [[x1,y1,x2,y2,s]]} """ max_score = 0 min_score = 1 for _, k in pred.items(): for _, v in k.items(): if v: _min = np.min(v[:, -1]) _max = np.max(v[:, -1]) max_score = max(_max, max_score) min_score = min(_min, min_score) else: continue diff = max_score - min_score for _, k in pred.items(): for _, v in k.items(): if v: v[:, -1] = (v[:, -1] - min_score) / diff else: continue def image_eval(pred, gt, ignore, iou_thresh): """ single image evaluation pred: Nx5 gt: Nx4 ignore: """ _pred = pred.copy() _gt = gt.copy() pred_recall = np.zeros(_pred.shape[0]) recall_list = np.zeros(_gt.shape[0]) proposal_list = np.ones(_pred.shape[0]) _pred[:, 2] = _pred[:, 2] + _pred[:, 0] _pred[:, 3] = _pred[:, 3] + _pred[:, 1] _gt[:, 2] = _gt[:, 2] + _gt[:, 0] _gt[:, 3] = _gt[:, 3] + _gt[:, 1] overlaps = bbox_overlaps(_pred[:, :4], _gt) for h in range(_pred.shape[0]): gt_overlap = overlaps[h] max_overlap, max_idx = gt_overlap.max(), gt_overlap.argmax() if max_overlap >= iou_thresh: if ignore[max_idx] == 0: recall_list[max_idx] = -1 proposal_list[h] = -1 elif recall_list[max_idx] == 0: recall_list[max_idx] = 1 r_keep_index = np.where(recall_list == 1)[0] pred_recall[h] = len(r_keep_index) return pred_recall, proposal_list def img_pr_info(thresh_num, pred_info, proposal_list, pred_recall): """ img_pr_info """ pr_info = np.zeros((thresh_num, 2)).astype('float') for t in range(thresh_num): thresh = 1 - (t + 1) / thresh_num r_index = np.where(pred_info[:, 4] >= thresh)[0] if r_index: r_index = r_index[-1] p_index = np.where(proposal_list[:r_index + 1] == 1)[0] pr_info[t, 0] = len(p_index) pr_info[t, 1] = pred_recall[r_index] else: pr_info[t, 0] = 0 pr_info[t, 1] = 0 return pr_info def dataset_pr_info(thresh_num, pr_curve, count_face): _pr_curve = np.zeros((thresh_num, 2)) for i in range(thresh_num): _pr_curve[i, 0] = pr_curve[i, 1] / pr_curve[i, 0] _pr_curve[i, 1] = pr_curve[i, 1] / count_face return _pr_curve def voc_ap(rec, prec): """ voc_ap """ # correct AP calculation # first append sentinel values at the end mrec = np.concatenate(([0.], rec, [1.])) mpre = np.concatenate(([0.], prec, [0.])) # compute the precision envelope for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrec[1:] != mrec[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap def evaluation(pred, gt_path, iou_thresh=0.5): """ evaluation """ facebox_list, event_list, file_list, hard_gt_list, medium_gt_list, easy_gt_list = get_gt_boxes(gt_path) event_num = len(event_list) settings = ['easy', 'medium', 'hard'] setting_gts = [easy_gt_list, medium_gt_list, hard_gt_list] for setting_id in range(3): # different setting gt_list = setting_gts[setting_id] # [hard, medium, easy] pbar = tqdm.tqdm(range(event_num)) outputTxtDir = './bbx_gt_txt/' if not os.path.exists(outputTxtDir): os.makedirs(outputTxtDir) outputTxtFile = outputTxtDir + settings[setting_id] + '.txt' if os.path.exists(outputTxtFile): os.remove(outputTxtFile) for i in pbar: pbar.set_description('Processing {}'.format(settings[setting_id])) img_list = file_list[i][0] sub_gt_list = gt_list[i][0] gt_bbx_list = facebox_list[i][0] for j in range(len(img_list)): gt_boxes = gt_bbx_list[j][0] keep_index = sub_gt_list[j][0] imgName = img_list[j][0][0] imgPath = _MAP[imgName.split('_')[0]] + '/' + imgName + '.jpg' faceNum = len(keep_index) with open(outputTxtFile, 'a') as txtFile: txtFile.write(imgPath + '\n') txtFile.write(str(faceNum) + '\n') if faceNum == 0: txtFile.write(str(faceNum) + '\n') for index in keep_index: curI = index[0] - 1 bbox = gt_boxes[curI] txtFile.write('%d %d %d %d\n' % (bbox[0], bbox[1], bbox[2], bbox[3])) txtFile.close() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-p', '--pred') parser.add_argument('-g', '--gt', default='./eval_tools/ground_truth/') args = parser.parse_args() evaluation(args.pred, args.gt)
0.398641
0.242441
from openerp.osv import osv,fields from openerp import models, fields, api, _ class CambioParaleloDetalle(models.Model): _name="cambio.paralelo.detalle" _order = "contador asc" paralelod_id =fields.Many2one('cambio.paralelo',string="Relacion") contador = fields.Integer(string="Número") jornada_id=fields.Many2one('jornada','Jornada',copy=False, index=True) seccion_id=fields.Many2one('seccion','Sección',copy=False, index=True) curso_id=fields.Many2one('curso','Curso',copy=False, index=True) paralelo_id=fields.Many2one('paralelo','Paralelo',copy=False, index=True) alumno_id=fields.Many2one('res.partner',string="Alumno") alumno_nombre = fields.Char(related='alumno_id.name',string="Alumno") codigo_alumno = fields.Char(related='alumno_id.codigo_alumno',string="Código") facturar = fields.Boolean('Facturar') #cobrar = fields.Boolean('Cobrar') class CambioParaleloDetalleDespues(models.Model): _name="cambio.paralelo.detalle_nuevo" _order = "contador asc" paralelod_nuevo_id =fields.Many2one('cambio.paralelo',string="Relacion") contador = fields.Integer(string="Número") jornada_id=fields.Many2one('jornada','Jornada',copy=False, index=True) seccion_id=fields.Many2one('seccion','Sección',copy=False, index=True) curso_id=fields.Many2one('curso','Curso',copy=False, index=True) paralelo_id=fields.Many2one('paralelo','Paralelo',copy=False, index=True) alumno_id=fields.Many2one('res.partner',string="Alumno") alumno_nombre = fields.Char(related='alumno_id.name',string="Alumno") codigo_alumno = fields.Char(related='alumno_id.codigo_alumno',string="Código") facturar = fields.Boolean('Facturar') #cobrar = fields.Boolean('Cobrar') class CambioParalelo(models.Model): _name="cambio.paralelo" _rec_name = 'jornada_actual_id' #actual jornada_actual_id=fields.Many2one('jornada','Jornada',copy=False, index=True) seccion_actual_id=fields.Many2one('seccion','Sección',copy=False, index=True) curso_actual_id=fields.Many2one('curso','Curso',copy=False, index=True) paralelo_actual_id=fields.Many2one('paralelo','Paralelo',copy=False, index=True) alumno_id=fields.Many2one('res.partner',string="Alumno") #nuevo jornada_nuevo_id=fields.Many2one('jornada','Jornada',copy=False, index=True) seccion_nuevo_id=fields.Many2one('seccion','Sección',copy=False, index=True) curso_nuevo_id=fields.Many2one('curso','Curso',copy=False, index=True) paralelo_nuevo_id=fields.Many2one('paralelo','Paralelo',copy=False, index=True) paralelo_line=fields.One2many('cambio.paralelo.detalle','paralelod_id',string="Relacion") paralelos_line_nuevo=fields.One2many('cambio.paralelo.detalle_nuevo','paralelod_nuevo_id',string="Relacion") usuario_id=fields.Many2one('res.users',string="Usuario", default=lambda self:self.env.user ,readonly=True) estado = fields.Selection( (('0','Borrador'), ('1','Ejecutado'), ('2','Anulado')) , 'Estados', required=False) accion = fields.Selection( (('0','Ninguno'), ('1','Facturar'), ('2','Cobrar'), ('3','Deshabilitar Facturación')) , 'Acción', required=False, default='0') @api.onchange('jornada_nuevo_id') def onchange_jornada(self): for l in self: if l.jornada_nuevo_id: l.seccion_nuevo_id=False l.curso_nuevo_id= False l.paralelo_nuevo_id = False @api.onchange('seccion_nuevo_id') def onchange_seccion(self): for l in self: if l.seccion_nuevo_id: l.curso_nuevo_id= False l.paralelo_nuevo_id = False @api.onchange('curso_nuevo_id') def onchange_curso(self): for l in self: if l.curso_nuevo_id: l.paralelo_nuevo_id = False @api.onchange('jornada_actual_id') def onchange_jornada_actual(self): for l in self: if l.jornada_actual_id: l.seccion_actual_id=False l.curso_actual_id= False l.paralelo_actual_id = False @api.onchange('seccion_actual_id') def onchange_seccion_actual(self): for l in self: if l.seccion_actual_id: l.curso_actual_id= False l.paralelo_actual_id = False @api.onchange('curso_actual_id') def onchange_curso_actual(self): for l in self: if l.curso_actual_id: l.paralelo_actual_id = False @api.multi def consultar(self): self.estado='0' self.env.cr.execute("""delete from cambio_paralelo_detalle""") if self.jornada_actual_id: if self.seccion_actual_id: if self.curso_actual_id: if self.paralelo_actual_id: obj_datos=self.env['res.partner'].search([ ('jornada_id','=',self.jornada_actual_id.id), ('seccion_id','=',self.seccion_actual_id.id), ('curso_id','=',self.curso_actual_id.id), ('paralelo_id','=',self.paralelo_actual_id.id), ('tipo','=','H')]) else: obj_datos=self.env['res.partner'].search([ ('jornada_id','=',self.jornada_actual_id.id), ('seccion_id','=',self.seccion_actual_id.id), ('curso_id','=',self.curso_actual_id.id), ('tipo','=','H')]) else: obj_datos=self.env['res.partner'].search([ ('jornada_id','=',self.jornada_actual_id.id), ('seccion_id','=',self.seccion_actual_id.id), ('tipo','=','H')]) else: obj_datos=self.env['res.partner'].search([('jornada_id','=',self.jornada_actual_id.id), ('tipo','=','H')]) orden=1 obj_detalle=self.env['cambio.paralelo.detalle'] for datos in obj_datos: dicc={} dicct={} obj_detalle.create({ 'contador':orden, 'jornada_id':datos.jornada_id.id, 'seccion_id':datos.seccion_id.id, 'curso_id':datos.curso_id.id, 'paralelo_id':datos.paralelo_id.id, 'alumno_id':datos.id, 'codigo':datos.codigo_alumno, 'facturar':True, 'cobrar':True, 'paralelod_id':self.id, }) orden=orden+1 @api.multi def ejecutar(self): self.estado='1' if self.accion=='0': if self.jornada_nuevo_id and self.seccion_nuevo_id and self.curso_nuevo_id and self.paralelo_nuevo_id: for datos in self.paralelo_line: obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) obj_alumno.jornada_anterior_id=obj_alumno.jornada_id.id obj_alumno.seccion_anterior_id=obj_alumno.seccion_id.id obj_alumno.curso_anterior_id=obj_alumno.curso_id.id obj_alumno.paralelo_anterior_id=obj_alumno.paralelo_id.id obj_alumno.update({'jornada_id':False}) obj_alumno.update({'seccion_id':False}) obj_alumno.update({'curso_id':False}) obj_alumno.update({'paralelo_id':False}) for datos in self.paralelo_line: obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) obj_alumno.write({'jornada_id':self.jornada_nuevo_id.id}) obj_alumno.jornada_id=self.jornada_nuevo_id.id obj_alumno.write({'seccion_id':self.seccion_nuevo_id.id}) obj_alumno.seccion_id=self.seccion_nuevo_id.id obj_alumno.write({'curso_id':self.curso_nuevo_id.id}) obj_alumno.curso_id=self.curso_nuevo_id.id obj_alumno.write({'paralelo_id':self.paralelo_nuevo_id.id}) obj_alumno.paralelo_id=self.paralelo_nuevo_id.id for nuevo in self.paralelo_line: orden=1 obj_alumno_nuevo = self.env['res.partner'].search([('id','=',nuevo.alumno_id.id),('tipo','=','H')]) obj_detalle=self.env['cambio.paralelo.detalle_nuevo'] for datos in obj_alumno_nuevo: dicc={} dicct={} obj_detalle.create({ 'contador':orden, 'jornada_id':datos.jornada_id.id, 'seccion_id':datos.seccion_id.id, 'curso_id':datos.curso_id.id, 'paralelo_id':datos.paralelo_id.id, 'alumno_id':datos.id, 'codigo':datos.codigo_alumno, 'facturar':True, 'cobrar':True, 'paralelod_nuevo_id':self.id, }) orden=orden+1 else: raise osv.except_osv(('Alerta'),("Debe llenar la jornada, seccion, curso y paralelo al que desea realizar el cambio de paralelo.")) elif self.accion=='1': for datos in self.paralelo_line: obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) obj_alumno_detalle = self.env['res.partner.historico'].create({ 'usuario_id':self.usuario_id.id, 'enero':obj_alumno.enero, 'febrero':obj_alumno.febrero, 'marzo':obj_alumno.marzo, 'abril':obj_alumno.abril, 'mayo':obj_alumno.mayo, 'junio':obj_alumno.junio, 'julio':obj_alumno.julio, 'agosto':obj_alumno.agosto, 'septiembre':obj_alumno.septiembre, 'octubre':obj_alumno.octubre, 'noviembre':obj_alumno.noviembre, 'diciembre':obj_alumno.diciembre, 'alumno_id':obj_alumno.id, 'accion':'1', }) obj_alumno.enero=True obj_alumno.febrero=True obj_alumno.marzo=True obj_alumno.abril=True obj_alumno.mayo=True obj_alumno.junio=True obj_alumno.julio=True obj_alumno.agosto=True obj_alumno.septiembre=True obj_alumno.octubre=True obj_alumno.noviembre=True obj_alumno.diciembre=True elif self.accion=='2': for datos in self.paralelo_line: datos.facturar=False obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) obj_alumno_detalle = self.env['res.partner.historico'].create({ 'usuario_id':self.usuario_id.id, 'enero':obj_alumno.enero, 'febrero':obj_alumno.febrero, 'marzo':obj_alumno.marzo, 'abril':obj_alumno.abril, 'mayo':obj_alumno.mayo, 'junio':obj_alumno.junio, 'julio':obj_alumno.julio, 'agosto':obj_alumno.agosto, 'septiembre':obj_alumno.septiembre, 'octubre':obj_alumno.octubre, 'noviembre':obj_alumno.noviembre, 'diciembre':obj_alumno.diciembre, 'alumno_id':obj_alumno.id, 'accion':'2', }) obj_alumno.enero=False obj_alumno.febrero=False obj_alumno.marzo=False obj_alumno.abril=False obj_alumno.mayo=False obj_alumno.junio=False obj_alumno.julio=False obj_alumno.agosto=False obj_alumno.septiembre=False obj_alumno.octubre=False obj_alumno.noviembre=False obj_alumno.diciembre=False elif self.accion=='3': for datos in self.paralelo_line: datos.facturar=False obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) obj_alumno.facturar=False @api.multi def anular(self): self.estado='2' if self.accion=='0': for datos in self.paralelos_line_nuevo: obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) obj_alumno.jornada_id=obj_alumno.jornada_anterior_id.id obj_alumno.seccion_id=obj_alumno.seccion_anterior_id.id obj_alumno.curso_id=obj_alumno.curso_anterior_id.id obj_alumno.paralelo_id=obj_alumno.paralelo_anterior_id.id obj_alumno.update({'jornada_anterior_id':False}) obj_alumno.update({'seccion_anterior_id':False}) obj_alumno.update({'curso_anterior_id':False}) obj_alumno.update({'paralelo_anterior_id':False}) elif self.accion=='1': for datos in self.paralelo_line: obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) for hist in obj_alumno.historico_id: obj_alumno.enero=hist.enero obj_alumno.febrero=hist.febrero obj_alumno.marzo=hist.marzo obj_alumno.abril=hist.abril obj_alumno.mayo=hist.mayo obj_alumno.junio=hist.junio obj_alumno.julio=hist.julio obj_alumno.agosto=hist.agosto obj_alumno.septiembre=hist.septiembre obj_alumno.octubre=hist.octubre obj_alumno.noviembre=hist.noviembre obj_alumno.diciembre=hist.diciembre self.env.cr.execute("delete from res_partner_historico where alumno_id={0} and accion='1'".format(obj_alumno.id)) elif self.accion=='2': for datos in self.paralelo_line: datos.cobrar=True obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) for hist in obj_alumno.historico_id: obj_alumno.enero=hist.enero obj_alumno.febrero=hist.febrero obj_alumno.marzo=hist.marzo obj_alumno.abril=hist.abril obj_alumno.mayo=hist.mayo obj_alumno.junio=hist.junio obj_alumno.julio=hist.julio obj_alumno.agosto=hist.agosto obj_alumno.septiembre=hist.septiembre obj_alumno.octubre=hist.octubre obj_alumno.noviembre=hist.noviembre obj_alumno.diciembre=hist.diciembre self.env.cr.execute("delete from res_partner_historico where alumno_id={0} and accion='2'".format(obj_alumno.id)) elif self.accion=='3': for datos in self.paralelo_line: datos.facturar=True obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) obj_alumno.facturar=True
hanibal/ans_escuela/cambio_paralelo.py
from openerp.osv import osv,fields from openerp import models, fields, api, _ class CambioParaleloDetalle(models.Model): _name="cambio.paralelo.detalle" _order = "contador asc" paralelod_id =fields.Many2one('cambio.paralelo',string="Relacion") contador = fields.Integer(string="Número") jornada_id=fields.Many2one('jornada','Jornada',copy=False, index=True) seccion_id=fields.Many2one('seccion','Sección',copy=False, index=True) curso_id=fields.Many2one('curso','Curso',copy=False, index=True) paralelo_id=fields.Many2one('paralelo','Paralelo',copy=False, index=True) alumno_id=fields.Many2one('res.partner',string="Alumno") alumno_nombre = fields.Char(related='alumno_id.name',string="Alumno") codigo_alumno = fields.Char(related='alumno_id.codigo_alumno',string="Código") facturar = fields.Boolean('Facturar') #cobrar = fields.Boolean('Cobrar') class CambioParaleloDetalleDespues(models.Model): _name="cambio.paralelo.detalle_nuevo" _order = "contador asc" paralelod_nuevo_id =fields.Many2one('cambio.paralelo',string="Relacion") contador = fields.Integer(string="Número") jornada_id=fields.Many2one('jornada','Jornada',copy=False, index=True) seccion_id=fields.Many2one('seccion','Sección',copy=False, index=True) curso_id=fields.Many2one('curso','Curso',copy=False, index=True) paralelo_id=fields.Many2one('paralelo','Paralelo',copy=False, index=True) alumno_id=fields.Many2one('res.partner',string="Alumno") alumno_nombre = fields.Char(related='alumno_id.name',string="Alumno") codigo_alumno = fields.Char(related='alumno_id.codigo_alumno',string="Código") facturar = fields.Boolean('Facturar') #cobrar = fields.Boolean('Cobrar') class CambioParalelo(models.Model): _name="cambio.paralelo" _rec_name = 'jornada_actual_id' #actual jornada_actual_id=fields.Many2one('jornada','Jornada',copy=False, index=True) seccion_actual_id=fields.Many2one('seccion','Sección',copy=False, index=True) curso_actual_id=fields.Many2one('curso','Curso',copy=False, index=True) paralelo_actual_id=fields.Many2one('paralelo','Paralelo',copy=False, index=True) alumno_id=fields.Many2one('res.partner',string="Alumno") #nuevo jornada_nuevo_id=fields.Many2one('jornada','Jornada',copy=False, index=True) seccion_nuevo_id=fields.Many2one('seccion','Sección',copy=False, index=True) curso_nuevo_id=fields.Many2one('curso','Curso',copy=False, index=True) paralelo_nuevo_id=fields.Many2one('paralelo','Paralelo',copy=False, index=True) paralelo_line=fields.One2many('cambio.paralelo.detalle','paralelod_id',string="Relacion") paralelos_line_nuevo=fields.One2many('cambio.paralelo.detalle_nuevo','paralelod_nuevo_id',string="Relacion") usuario_id=fields.Many2one('res.users',string="Usuario", default=lambda self:self.env.user ,readonly=True) estado = fields.Selection( (('0','Borrador'), ('1','Ejecutado'), ('2','Anulado')) , 'Estados', required=False) accion = fields.Selection( (('0','Ninguno'), ('1','Facturar'), ('2','Cobrar'), ('3','Deshabilitar Facturación')) , 'Acción', required=False, default='0') @api.onchange('jornada_nuevo_id') def onchange_jornada(self): for l in self: if l.jornada_nuevo_id: l.seccion_nuevo_id=False l.curso_nuevo_id= False l.paralelo_nuevo_id = False @api.onchange('seccion_nuevo_id') def onchange_seccion(self): for l in self: if l.seccion_nuevo_id: l.curso_nuevo_id= False l.paralelo_nuevo_id = False @api.onchange('curso_nuevo_id') def onchange_curso(self): for l in self: if l.curso_nuevo_id: l.paralelo_nuevo_id = False @api.onchange('jornada_actual_id') def onchange_jornada_actual(self): for l in self: if l.jornada_actual_id: l.seccion_actual_id=False l.curso_actual_id= False l.paralelo_actual_id = False @api.onchange('seccion_actual_id') def onchange_seccion_actual(self): for l in self: if l.seccion_actual_id: l.curso_actual_id= False l.paralelo_actual_id = False @api.onchange('curso_actual_id') def onchange_curso_actual(self): for l in self: if l.curso_actual_id: l.paralelo_actual_id = False @api.multi def consultar(self): self.estado='0' self.env.cr.execute("""delete from cambio_paralelo_detalle""") if self.jornada_actual_id: if self.seccion_actual_id: if self.curso_actual_id: if self.paralelo_actual_id: obj_datos=self.env['res.partner'].search([ ('jornada_id','=',self.jornada_actual_id.id), ('seccion_id','=',self.seccion_actual_id.id), ('curso_id','=',self.curso_actual_id.id), ('paralelo_id','=',self.paralelo_actual_id.id), ('tipo','=','H')]) else: obj_datos=self.env['res.partner'].search([ ('jornada_id','=',self.jornada_actual_id.id), ('seccion_id','=',self.seccion_actual_id.id), ('curso_id','=',self.curso_actual_id.id), ('tipo','=','H')]) else: obj_datos=self.env['res.partner'].search([ ('jornada_id','=',self.jornada_actual_id.id), ('seccion_id','=',self.seccion_actual_id.id), ('tipo','=','H')]) else: obj_datos=self.env['res.partner'].search([('jornada_id','=',self.jornada_actual_id.id), ('tipo','=','H')]) orden=1 obj_detalle=self.env['cambio.paralelo.detalle'] for datos in obj_datos: dicc={} dicct={} obj_detalle.create({ 'contador':orden, 'jornada_id':datos.jornada_id.id, 'seccion_id':datos.seccion_id.id, 'curso_id':datos.curso_id.id, 'paralelo_id':datos.paralelo_id.id, 'alumno_id':datos.id, 'codigo':datos.codigo_alumno, 'facturar':True, 'cobrar':True, 'paralelod_id':self.id, }) orden=orden+1 @api.multi def ejecutar(self): self.estado='1' if self.accion=='0': if self.jornada_nuevo_id and self.seccion_nuevo_id and self.curso_nuevo_id and self.paralelo_nuevo_id: for datos in self.paralelo_line: obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) obj_alumno.jornada_anterior_id=obj_alumno.jornada_id.id obj_alumno.seccion_anterior_id=obj_alumno.seccion_id.id obj_alumno.curso_anterior_id=obj_alumno.curso_id.id obj_alumno.paralelo_anterior_id=obj_alumno.paralelo_id.id obj_alumno.update({'jornada_id':False}) obj_alumno.update({'seccion_id':False}) obj_alumno.update({'curso_id':False}) obj_alumno.update({'paralelo_id':False}) for datos in self.paralelo_line: obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) obj_alumno.write({'jornada_id':self.jornada_nuevo_id.id}) obj_alumno.jornada_id=self.jornada_nuevo_id.id obj_alumno.write({'seccion_id':self.seccion_nuevo_id.id}) obj_alumno.seccion_id=self.seccion_nuevo_id.id obj_alumno.write({'curso_id':self.curso_nuevo_id.id}) obj_alumno.curso_id=self.curso_nuevo_id.id obj_alumno.write({'paralelo_id':self.paralelo_nuevo_id.id}) obj_alumno.paralelo_id=self.paralelo_nuevo_id.id for nuevo in self.paralelo_line: orden=1 obj_alumno_nuevo = self.env['res.partner'].search([('id','=',nuevo.alumno_id.id),('tipo','=','H')]) obj_detalle=self.env['cambio.paralelo.detalle_nuevo'] for datos in obj_alumno_nuevo: dicc={} dicct={} obj_detalle.create({ 'contador':orden, 'jornada_id':datos.jornada_id.id, 'seccion_id':datos.seccion_id.id, 'curso_id':datos.curso_id.id, 'paralelo_id':datos.paralelo_id.id, 'alumno_id':datos.id, 'codigo':datos.codigo_alumno, 'facturar':True, 'cobrar':True, 'paralelod_nuevo_id':self.id, }) orden=orden+1 else: raise osv.except_osv(('Alerta'),("Debe llenar la jornada, seccion, curso y paralelo al que desea realizar el cambio de paralelo.")) elif self.accion=='1': for datos in self.paralelo_line: obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) obj_alumno_detalle = self.env['res.partner.historico'].create({ 'usuario_id':self.usuario_id.id, 'enero':obj_alumno.enero, 'febrero':obj_alumno.febrero, 'marzo':obj_alumno.marzo, 'abril':obj_alumno.abril, 'mayo':obj_alumno.mayo, 'junio':obj_alumno.junio, 'julio':obj_alumno.julio, 'agosto':obj_alumno.agosto, 'septiembre':obj_alumno.septiembre, 'octubre':obj_alumno.octubre, 'noviembre':obj_alumno.noviembre, 'diciembre':obj_alumno.diciembre, 'alumno_id':obj_alumno.id, 'accion':'1', }) obj_alumno.enero=True obj_alumno.febrero=True obj_alumno.marzo=True obj_alumno.abril=True obj_alumno.mayo=True obj_alumno.junio=True obj_alumno.julio=True obj_alumno.agosto=True obj_alumno.septiembre=True obj_alumno.octubre=True obj_alumno.noviembre=True obj_alumno.diciembre=True elif self.accion=='2': for datos in self.paralelo_line: datos.facturar=False obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) obj_alumno_detalle = self.env['res.partner.historico'].create({ 'usuario_id':self.usuario_id.id, 'enero':obj_alumno.enero, 'febrero':obj_alumno.febrero, 'marzo':obj_alumno.marzo, 'abril':obj_alumno.abril, 'mayo':obj_alumno.mayo, 'junio':obj_alumno.junio, 'julio':obj_alumno.julio, 'agosto':obj_alumno.agosto, 'septiembre':obj_alumno.septiembre, 'octubre':obj_alumno.octubre, 'noviembre':obj_alumno.noviembre, 'diciembre':obj_alumno.diciembre, 'alumno_id':obj_alumno.id, 'accion':'2', }) obj_alumno.enero=False obj_alumno.febrero=False obj_alumno.marzo=False obj_alumno.abril=False obj_alumno.mayo=False obj_alumno.junio=False obj_alumno.julio=False obj_alumno.agosto=False obj_alumno.septiembre=False obj_alumno.octubre=False obj_alumno.noviembre=False obj_alumno.diciembre=False elif self.accion=='3': for datos in self.paralelo_line: datos.facturar=False obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) obj_alumno.facturar=False @api.multi def anular(self): self.estado='2' if self.accion=='0': for datos in self.paralelos_line_nuevo: obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) obj_alumno.jornada_id=obj_alumno.jornada_anterior_id.id obj_alumno.seccion_id=obj_alumno.seccion_anterior_id.id obj_alumno.curso_id=obj_alumno.curso_anterior_id.id obj_alumno.paralelo_id=obj_alumno.paralelo_anterior_id.id obj_alumno.update({'jornada_anterior_id':False}) obj_alumno.update({'seccion_anterior_id':False}) obj_alumno.update({'curso_anterior_id':False}) obj_alumno.update({'paralelo_anterior_id':False}) elif self.accion=='1': for datos in self.paralelo_line: obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) for hist in obj_alumno.historico_id: obj_alumno.enero=hist.enero obj_alumno.febrero=hist.febrero obj_alumno.marzo=hist.marzo obj_alumno.abril=hist.abril obj_alumno.mayo=hist.mayo obj_alumno.junio=hist.junio obj_alumno.julio=hist.julio obj_alumno.agosto=hist.agosto obj_alumno.septiembre=hist.septiembre obj_alumno.octubre=hist.octubre obj_alumno.noviembre=hist.noviembre obj_alumno.diciembre=hist.diciembre self.env.cr.execute("delete from res_partner_historico where alumno_id={0} and accion='1'".format(obj_alumno.id)) elif self.accion=='2': for datos in self.paralelo_line: datos.cobrar=True obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) for hist in obj_alumno.historico_id: obj_alumno.enero=hist.enero obj_alumno.febrero=hist.febrero obj_alumno.marzo=hist.marzo obj_alumno.abril=hist.abril obj_alumno.mayo=hist.mayo obj_alumno.junio=hist.junio obj_alumno.julio=hist.julio obj_alumno.agosto=hist.agosto obj_alumno.septiembre=hist.septiembre obj_alumno.octubre=hist.octubre obj_alumno.noviembre=hist.noviembre obj_alumno.diciembre=hist.diciembre self.env.cr.execute("delete from res_partner_historico where alumno_id={0} and accion='2'".format(obj_alumno.id)) elif self.accion=='3': for datos in self.paralelo_line: datos.facturar=True obj_alumno = self.env['res.partner'].search([('id','=',datos.alumno_id.id),('tipo','=','H')]) obj_alumno.facturar=True
0.160661
0.077169
import unittest import numpy as np import desimeter.transform.radec2tan as radec2tan class TestRADEC2TAN(unittest.TestCase): def test_hadec2xy(self): cha=12 cdec=24 x1 = np.random.uniform(size=3)-0.5 y1 = np.random.uniform(size=3)-0.5 ha1,dec1 = radec2tan.xy2hadec(x1,y1,cha,cdec) x2,y2 = radec2tan.hadec2xy(ha1,dec1,cha,cdec) assert(np.all(np.abs(x1-x2)<1e-6)) assert(np.all(np.abs(y1-y2)<1e-6)) # check orientation x,y = radec2tan.hadec2xy(cha+1,cdec,cha,cdec) assert(x>0) x,y = radec2tan.hadec2xy(cha,cdec+1,cha,cdec) assert(y>0) def test_scalar_and_array(self): cra = 12. cdec = 24. lst = 13. ra = cra + 1. dec = cdec + 1. mjd = 58864.3 x , y = radec2tan.radec2tan(ra,dec,tel_ra=cra,tel_dec=cdec,mjd=mjd,lst_deg=lst,hexrot_deg=0) # check we can convert to float x = float(x) y = float(y) # check sign assert(x<0) # because dra>0 assert(y>0) # because ddec>0 npt = 12 ra = cra + np.linspace(1,1.,npt) dec = cdec + np.linspace(-1,1.,npt) x , y = radec2tan.radec2tan(ra,dec,tel_ra=cra,tel_dec=cdec,mjd=mjd,lst_deg=lst,hexrot_deg=0) # check dimension of output array assert(x.shape == ra.shape) assert(y.shape == ra.shape) def test_polar_misalignment(self): # circle of coordinates in FP phi = np.linspace(0,np.pi,4) theta = 1./180*np.pi x1 = np.sin(theta)*np.cos(phi) y1 = np.sin(theta)*np.sin(phi) # pointings for cha in [60] : for cdec in [80] : ha1,dec1 = radec2tan.xy2hadec(x1,y1,cha,cdec) # apply rotation M = radec2tan.compute_polar_misalignment_rotation_matrix(me_arcsec=radec2tan.ME_ARCSEC,ma_arcsec=radec2tan.MA_ARCSEC) ha2,dec2 = radec2tan.getLONLAT(M.dot(radec2tan.getXYZ(ha1,dec1))) # back to FP coordinates cha2,cdec2 = radec2tan.getLONLAT(M.dot(radec2tan.getXYZ(cha,cdec))) x2,y2 = radec2tan.hadec2xy(ha2,dec2,cha2,cdec2) # measure field rotation angle x1 -= np.mean(x1) y1 -= np.mean(y1) x2 -= np.mean(x2) y2 -= np.mean(y2) angle = np.mean(radec2tan.arcsind((x1*y2-x2*y1)/np.sqrt((x1**2+y1**2)*(x2**2+y2**2)))) print("at HA= {} deg and Dec = {} deg, the mean field rotation angle= {:4.3f} deg ".format(cha,cdec,angle)) def test_precession(self): ra = 12. dec = 24. mjd = 58864.3 ra2,dec2 = radec2tan.apply_precession_from_icrs(ra, dec, mjd, use_astropy = False) ra2b,dec2b = radec2tan.apply_precession_from_icrs(ra, dec, mjd, use_astropy = True) print("precession this code dRA= {:4.1f} arcsec , dDec= {:4.1f} arcsec".format((ra2-ra)*3600.,(dec2-dec)*3600.)) print("precession astropy dRA= {:4.1f} arcsec , dDec= {:4.1f} arcsec".format((ra2b-ra)*3600.,(dec2b-dec)*3600.)) assert(np.abs(ra2-ra2b)<1.) # we care only about the relative variation of this in the focal plane assert(np.abs(dec2-dec2b)<1.) # we care only about the relative variation of this in the focal plane # test 1D ra = ra*np.ones(4) dec = dec*np.ones(4) ra2,dec2 = radec2tan.apply_precession_from_icrs(ra, dec, mjd, use_astropy = False) ra2b,dec2b = radec2tan.apply_precession_from_icrs(ra, dec, mjd, use_astropy = True) print("precession this code dRA= {} arcsec , dDec= {} arcsec".format((ra2-ra)*3600.,(dec2-dec)*3600.)) print("precession astropy dRA= {} arcsec , dDec= {} arcsec".format((ra2b-ra)*3600.,(dec2b-dec)*3600.)) def test_aberration(self): ra = 12. dec = 24. mjd = 58864.3 ra2,dec2 = radec2tan.apply_aberration(ra, dec, mjd, use_astropy = False) ra2b,dec2b = radec2tan.apply_aberration(ra, dec, mjd, use_astropy = True) print("aberration this code dRA= {:4.1f} arcsec , dDec= {:4.1f} arcsec".format((ra2-ra)*3600.,(dec2-dec)*3600.)) print("aberration astropy dRA= {:4.1f} arcsec , dDec= {:4.1f} arcsec".format((ra2b-ra)*3600.,(dec2b-dec)*3600.)) assert(np.abs(ra2-ra2b)<1.) # we care only about the relative variation of this in the focal plane assert(np.abs(dec2-dec2b)<1.) # we care only about the relative variation of this in the focal plane # test 1D ra = ra*np.ones(4) dec = dec*np.ones(4) ra2,dec2 = radec2tan.apply_aberration(ra, dec, mjd, use_astropy = False) ra2b,dec2b = radec2tan.apply_aberration(ra, dec, mjd, use_astropy = True) print("aberration this code dRA= {} arcsec , dDec= {} arcsec".format((ra2-ra)*3600.,(dec2-dec)*3600.)) print("aberration astropy dRA= {} arcsec , dDec= {} arcsec".format((ra2b-ra)*3600.,(dec2b-dec)*3600.)) def test_tan2radec(self): cra=12 cdec=24 lst = 13. ra = cra + 1. dec = cdec + 1. mjd = 58864.3 x,y = radec2tan.radec2tan(ra,dec,tel_ra=cra,tel_dec=cdec,mjd=mjd,lst_deg=lst,hexrot_deg=0.1) ra2,dec2 = radec2tan.tan2radec(x,y,tel_ra=cra,tel_dec=cdec,mjd=mjd,lst_deg=lst,hexrot_deg=0.1) dra=ra2-ra ddec=dec2-dec print("dra={} arcsec , ddec={} arcsec".format(dra*3600,ddec*3600)) assert(np.abs(dra*3600.)<0.001) # 1 milli-arcsec assert(np.abs(ddec*3600.)<0.001) # 1 milli-arcsec def test_refraction(self): alt = 30. # deg alt2 = radec2tan.apply_refraction(alt) alt3 = radec2tan.undo_refraction(alt2) print("At altitude={} deg, refraction={:4.1f} arcsec, and zero={:4.3f} arcsec".format(alt,(alt2-alt)*3600.,(alt3-alt)*3600.)) assert(np.abs((alt3-alt)*3600.)<0.001) # 1 milli-arcsec if __name__ == '__main__' : unittest.main()
py/desimeter/test/test_radec2tan.py
import unittest import numpy as np import desimeter.transform.radec2tan as radec2tan class TestRADEC2TAN(unittest.TestCase): def test_hadec2xy(self): cha=12 cdec=24 x1 = np.random.uniform(size=3)-0.5 y1 = np.random.uniform(size=3)-0.5 ha1,dec1 = radec2tan.xy2hadec(x1,y1,cha,cdec) x2,y2 = radec2tan.hadec2xy(ha1,dec1,cha,cdec) assert(np.all(np.abs(x1-x2)<1e-6)) assert(np.all(np.abs(y1-y2)<1e-6)) # check orientation x,y = radec2tan.hadec2xy(cha+1,cdec,cha,cdec) assert(x>0) x,y = radec2tan.hadec2xy(cha,cdec+1,cha,cdec) assert(y>0) def test_scalar_and_array(self): cra = 12. cdec = 24. lst = 13. ra = cra + 1. dec = cdec + 1. mjd = 58864.3 x , y = radec2tan.radec2tan(ra,dec,tel_ra=cra,tel_dec=cdec,mjd=mjd,lst_deg=lst,hexrot_deg=0) # check we can convert to float x = float(x) y = float(y) # check sign assert(x<0) # because dra>0 assert(y>0) # because ddec>0 npt = 12 ra = cra + np.linspace(1,1.,npt) dec = cdec + np.linspace(-1,1.,npt) x , y = radec2tan.radec2tan(ra,dec,tel_ra=cra,tel_dec=cdec,mjd=mjd,lst_deg=lst,hexrot_deg=0) # check dimension of output array assert(x.shape == ra.shape) assert(y.shape == ra.shape) def test_polar_misalignment(self): # circle of coordinates in FP phi = np.linspace(0,np.pi,4) theta = 1./180*np.pi x1 = np.sin(theta)*np.cos(phi) y1 = np.sin(theta)*np.sin(phi) # pointings for cha in [60] : for cdec in [80] : ha1,dec1 = radec2tan.xy2hadec(x1,y1,cha,cdec) # apply rotation M = radec2tan.compute_polar_misalignment_rotation_matrix(me_arcsec=radec2tan.ME_ARCSEC,ma_arcsec=radec2tan.MA_ARCSEC) ha2,dec2 = radec2tan.getLONLAT(M.dot(radec2tan.getXYZ(ha1,dec1))) # back to FP coordinates cha2,cdec2 = radec2tan.getLONLAT(M.dot(radec2tan.getXYZ(cha,cdec))) x2,y2 = radec2tan.hadec2xy(ha2,dec2,cha2,cdec2) # measure field rotation angle x1 -= np.mean(x1) y1 -= np.mean(y1) x2 -= np.mean(x2) y2 -= np.mean(y2) angle = np.mean(radec2tan.arcsind((x1*y2-x2*y1)/np.sqrt((x1**2+y1**2)*(x2**2+y2**2)))) print("at HA= {} deg and Dec = {} deg, the mean field rotation angle= {:4.3f} deg ".format(cha,cdec,angle)) def test_precession(self): ra = 12. dec = 24. mjd = 58864.3 ra2,dec2 = radec2tan.apply_precession_from_icrs(ra, dec, mjd, use_astropy = False) ra2b,dec2b = radec2tan.apply_precession_from_icrs(ra, dec, mjd, use_astropy = True) print("precession this code dRA= {:4.1f} arcsec , dDec= {:4.1f} arcsec".format((ra2-ra)*3600.,(dec2-dec)*3600.)) print("precession astropy dRA= {:4.1f} arcsec , dDec= {:4.1f} arcsec".format((ra2b-ra)*3600.,(dec2b-dec)*3600.)) assert(np.abs(ra2-ra2b)<1.) # we care only about the relative variation of this in the focal plane assert(np.abs(dec2-dec2b)<1.) # we care only about the relative variation of this in the focal plane # test 1D ra = ra*np.ones(4) dec = dec*np.ones(4) ra2,dec2 = radec2tan.apply_precession_from_icrs(ra, dec, mjd, use_astropy = False) ra2b,dec2b = radec2tan.apply_precession_from_icrs(ra, dec, mjd, use_astropy = True) print("precession this code dRA= {} arcsec , dDec= {} arcsec".format((ra2-ra)*3600.,(dec2-dec)*3600.)) print("precession astropy dRA= {} arcsec , dDec= {} arcsec".format((ra2b-ra)*3600.,(dec2b-dec)*3600.)) def test_aberration(self): ra = 12. dec = 24. mjd = 58864.3 ra2,dec2 = radec2tan.apply_aberration(ra, dec, mjd, use_astropy = False) ra2b,dec2b = radec2tan.apply_aberration(ra, dec, mjd, use_astropy = True) print("aberration this code dRA= {:4.1f} arcsec , dDec= {:4.1f} arcsec".format((ra2-ra)*3600.,(dec2-dec)*3600.)) print("aberration astropy dRA= {:4.1f} arcsec , dDec= {:4.1f} arcsec".format((ra2b-ra)*3600.,(dec2b-dec)*3600.)) assert(np.abs(ra2-ra2b)<1.) # we care only about the relative variation of this in the focal plane assert(np.abs(dec2-dec2b)<1.) # we care only about the relative variation of this in the focal plane # test 1D ra = ra*np.ones(4) dec = dec*np.ones(4) ra2,dec2 = radec2tan.apply_aberration(ra, dec, mjd, use_astropy = False) ra2b,dec2b = radec2tan.apply_aberration(ra, dec, mjd, use_astropy = True) print("aberration this code dRA= {} arcsec , dDec= {} arcsec".format((ra2-ra)*3600.,(dec2-dec)*3600.)) print("aberration astropy dRA= {} arcsec , dDec= {} arcsec".format((ra2b-ra)*3600.,(dec2b-dec)*3600.)) def test_tan2radec(self): cra=12 cdec=24 lst = 13. ra = cra + 1. dec = cdec + 1. mjd = 58864.3 x,y = radec2tan.radec2tan(ra,dec,tel_ra=cra,tel_dec=cdec,mjd=mjd,lst_deg=lst,hexrot_deg=0.1) ra2,dec2 = radec2tan.tan2radec(x,y,tel_ra=cra,tel_dec=cdec,mjd=mjd,lst_deg=lst,hexrot_deg=0.1) dra=ra2-ra ddec=dec2-dec print("dra={} arcsec , ddec={} arcsec".format(dra*3600,ddec*3600)) assert(np.abs(dra*3600.)<0.001) # 1 milli-arcsec assert(np.abs(ddec*3600.)<0.001) # 1 milli-arcsec def test_refraction(self): alt = 30. # deg alt2 = radec2tan.apply_refraction(alt) alt3 = radec2tan.undo_refraction(alt2) print("At altitude={} deg, refraction={:4.1f} arcsec, and zero={:4.3f} arcsec".format(alt,(alt2-alt)*3600.,(alt3-alt)*3600.)) assert(np.abs((alt3-alt)*3600.)<0.001) # 1 milli-arcsec if __name__ == '__main__' : unittest.main()
0.548432
0.530297
""" Base class for all plugin types """ from inspect import currentframe import os from typing import Optional import yaml from app.exceptions import PluginError # type: ignore import app.exceptions # type: ignore class BasePlugin(): """ Base class for plugins """ required_files: list[str] = [] # a list of files shipped with the plugin to be installed name: str = "" # The name of the plugin alternative_names: list[str] = [] # The is an optional list of alternative names description: Optional[str] = None # The description of this plugin def __init__(self) -> None: # self.machine = None self.plugin_path: Optional[str] = None self.machine_plugin = None # self.sysconf = {} self.conf: dict = {} self.attack_logger = None self.default_config_name = "default_config.yaml" def get_filename(self): """ Returns the current filename. """ cf = currentframe() # pylint: disable=invalid-name return cf.f_back.filename def get_linenumber(self): """ Returns the current linenumber. """ cf = currentframe() # pylint: disable=invalid-name return cf.f_back.f_lineno def get_playground(self): """ Returns the machine specific playground Which is the folder on the machine where we run our tasks in """ if self.machine_plugin is None: raise PluginError("Default machine not configured. Maybe you are creating an attack plugin. Then there are special attack/target machines") return self.machine_plugin.get_playground() def set_logger(self, attack_logger): """ Set the attack logger for this machine """ self.attack_logger = attack_logger def process_templates(self): # pylint: disable=no-self-use """ A method you can optionally implement to transfer your jinja2 templates into the files yo want to send to the target. See 'required_files' """ return def copy_to_attacker_and_defender(self): # pylint: disable=no-self-use """ Copy attacker/defender specific files to the machines """ return def setup(self): """ Prepare everything for the plugin """ self.process_templates() for a_file in self.required_files: src = os.path.join(os.path.dirname(self.plugin_path), a_file) self.vprint(src, 3) self.copy_to_machine(src) self.copy_to_attacker_and_defender() def set_machine_plugin(self, machine_plugin): """ Set the machine plugin class to communicate with @param machine_plugin: Machine plugin to communicate with """ self.machine_plugin = machine_plugin def set_sysconf(self, config): # pylint:disable=unused-argument """ Set system config @param config: A dict with system configuration relevant for all plugins """ # self.sysconf["abs_machinepath_internal"] = config["abs_machinepath_internal"] # self.sysconf["abs_machinepath_external"] = config["abs_machinepath_external"] self.load_default_config() def process_config(self, config: dict): """ process config and use defaults if stuff is missing @param config: The config dict """ # TODO: Move to python 3.9 syntax z = x | y self.conf = {**self.conf, **config} def copy_to_machine(self, filename: str): """ Copies a file shipped with the plugin to the machine share folder @param filename: File from the plugin folder to copy to the machine share. """ if self.machine_plugin is not None: self.machine_plugin.put(filename, self.machine_plugin.get_playground()) else: raise PluginError("Missing machine") def get_from_machine(self, src: str, dst: str): """ Get a file from the machine """ if self.machine_plugin is not None: self.machine_plugin.get(src, dst) # nosec else: raise PluginError("Missing machine") def run_cmd(self, command: str, disown: bool = False): """ Execute a command on the vm using the connection @param command: Command to execute @param disown: Run in background """ if self.machine_plugin is None: raise PluginError("machine to run command on is not registered") self.vprint(f" Plugin running command {command}", 3) res = self.machine_plugin.__call_remote_run__(command, disown=disown) return res def get_name(self): """ Returns the name of the plugin, please set in boilerplate """ if self.name: return self.name raise NotImplementedError def get_names(self) -> list[str]: """ Adds the name of the plugin to the alternative names and returns the list """ res = set() if self.name: res.add(self.name) for i in self.alternative_names: res.add(i) if len(res) > 0: return list(res) raise NotImplementedError def get_description(self): """ Returns the description of the plugin, please set in boilerplate """ if self.description: return self.description raise NotImplementedError def get_plugin_path(self): """ Returns the path the plugin file(s) are stored in """ return os.path.join(os.path.dirname(self.plugin_path)) def get_default_config_filename(self): """ Generate the default filename of the default configuration file """ return os.path.join(self.get_plugin_path(), self.default_config_name) def get_raw_default_config(self): """ Returns the default config as string. Usable as an example and for documentation """ if os.path.isfile(self.get_default_config_filename()): with open(self.get_default_config_filename(), "rt") as fh: return fh.read() else: return f"# The plugin {self.get_name()} does not support configuration" def load_default_config(self): """ Reads and returns the default config as dict """ filename = self.get_default_config_filename() if not os.path.isfile(filename): self.vprint(f"Did not find default config {filename}", 3) self.conf = {} else: with open(filename) as fh: self.vprint(f"Loading default config {filename}", 3) self.conf = yaml.safe_load(fh) if self.conf is None: self.conf = {} def get_config_section_name(self) -> str: """ Returns the name for the config sub-section to use for this plugin. Defaults to the name of the plugin. This method should be overwritten if it gets more complicated """ return self.get_name() def main_path(self) -> str: # pylint:disable=no-self-use """ Returns the main path of the Purple Dome installation """ app_dir = os.path.dirname(app.exceptions.__file__) return os.path.split(app_dir)[0] def vprint(self, text: str, verbosity: int): """ verbosity based stdout printing 0: Errors only 1: Main colored information 2: Detailed progress information 3: Debug logs, data dumps, everything @param text: The text to print @param verbosity: the verbosity level the text has. """ if self.attack_logger is not None: self.attack_logger.vprint(text, verbosity)
plugins/base/plugin_base.py
""" Base class for all plugin types """ from inspect import currentframe import os from typing import Optional import yaml from app.exceptions import PluginError # type: ignore import app.exceptions # type: ignore class BasePlugin(): """ Base class for plugins """ required_files: list[str] = [] # a list of files shipped with the plugin to be installed name: str = "" # The name of the plugin alternative_names: list[str] = [] # The is an optional list of alternative names description: Optional[str] = None # The description of this plugin def __init__(self) -> None: # self.machine = None self.plugin_path: Optional[str] = None self.machine_plugin = None # self.sysconf = {} self.conf: dict = {} self.attack_logger = None self.default_config_name = "default_config.yaml" def get_filename(self): """ Returns the current filename. """ cf = currentframe() # pylint: disable=invalid-name return cf.f_back.filename def get_linenumber(self): """ Returns the current linenumber. """ cf = currentframe() # pylint: disable=invalid-name return cf.f_back.f_lineno def get_playground(self): """ Returns the machine specific playground Which is the folder on the machine where we run our tasks in """ if self.machine_plugin is None: raise PluginError("Default machine not configured. Maybe you are creating an attack plugin. Then there are special attack/target machines") return self.machine_plugin.get_playground() def set_logger(self, attack_logger): """ Set the attack logger for this machine """ self.attack_logger = attack_logger def process_templates(self): # pylint: disable=no-self-use """ A method you can optionally implement to transfer your jinja2 templates into the files yo want to send to the target. See 'required_files' """ return def copy_to_attacker_and_defender(self): # pylint: disable=no-self-use """ Copy attacker/defender specific files to the machines """ return def setup(self): """ Prepare everything for the plugin """ self.process_templates() for a_file in self.required_files: src = os.path.join(os.path.dirname(self.plugin_path), a_file) self.vprint(src, 3) self.copy_to_machine(src) self.copy_to_attacker_and_defender() def set_machine_plugin(self, machine_plugin): """ Set the machine plugin class to communicate with @param machine_plugin: Machine plugin to communicate with """ self.machine_plugin = machine_plugin def set_sysconf(self, config): # pylint:disable=unused-argument """ Set system config @param config: A dict with system configuration relevant for all plugins """ # self.sysconf["abs_machinepath_internal"] = config["abs_machinepath_internal"] # self.sysconf["abs_machinepath_external"] = config["abs_machinepath_external"] self.load_default_config() def process_config(self, config: dict): """ process config and use defaults if stuff is missing @param config: The config dict """ # TODO: Move to python 3.9 syntax z = x | y self.conf = {**self.conf, **config} def copy_to_machine(self, filename: str): """ Copies a file shipped with the plugin to the machine share folder @param filename: File from the plugin folder to copy to the machine share. """ if self.machine_plugin is not None: self.machine_plugin.put(filename, self.machine_plugin.get_playground()) else: raise PluginError("Missing machine") def get_from_machine(self, src: str, dst: str): """ Get a file from the machine """ if self.machine_plugin is not None: self.machine_plugin.get(src, dst) # nosec else: raise PluginError("Missing machine") def run_cmd(self, command: str, disown: bool = False): """ Execute a command on the vm using the connection @param command: Command to execute @param disown: Run in background """ if self.machine_plugin is None: raise PluginError("machine to run command on is not registered") self.vprint(f" Plugin running command {command}", 3) res = self.machine_plugin.__call_remote_run__(command, disown=disown) return res def get_name(self): """ Returns the name of the plugin, please set in boilerplate """ if self.name: return self.name raise NotImplementedError def get_names(self) -> list[str]: """ Adds the name of the plugin to the alternative names and returns the list """ res = set() if self.name: res.add(self.name) for i in self.alternative_names: res.add(i) if len(res) > 0: return list(res) raise NotImplementedError def get_description(self): """ Returns the description of the plugin, please set in boilerplate """ if self.description: return self.description raise NotImplementedError def get_plugin_path(self): """ Returns the path the plugin file(s) are stored in """ return os.path.join(os.path.dirname(self.plugin_path)) def get_default_config_filename(self): """ Generate the default filename of the default configuration file """ return os.path.join(self.get_plugin_path(), self.default_config_name) def get_raw_default_config(self): """ Returns the default config as string. Usable as an example and for documentation """ if os.path.isfile(self.get_default_config_filename()): with open(self.get_default_config_filename(), "rt") as fh: return fh.read() else: return f"# The plugin {self.get_name()} does not support configuration" def load_default_config(self): """ Reads and returns the default config as dict """ filename = self.get_default_config_filename() if not os.path.isfile(filename): self.vprint(f"Did not find default config {filename}", 3) self.conf = {} else: with open(filename) as fh: self.vprint(f"Loading default config {filename}", 3) self.conf = yaml.safe_load(fh) if self.conf is None: self.conf = {} def get_config_section_name(self) -> str: """ Returns the name for the config sub-section to use for this plugin. Defaults to the name of the plugin. This method should be overwritten if it gets more complicated """ return self.get_name() def main_path(self) -> str: # pylint:disable=no-self-use """ Returns the main path of the Purple Dome installation """ app_dir = os.path.dirname(app.exceptions.__file__) return os.path.split(app_dir)[0] def vprint(self, text: str, verbosity: int): """ verbosity based stdout printing 0: Errors only 1: Main colored information 2: Detailed progress information 3: Debug logs, data dumps, everything @param text: The text to print @param verbosity: the verbosity level the text has. """ if self.attack_logger is not None: self.attack_logger.vprint(text, verbosity)
0.764364
0.209247
# windows sdk data file can download here: 'https://github.com/ohjeongwook/windows_sdk_data.git' import json import os result_dict = {} def parse_winsdk(dir): def PtrDecl_detect(dic): param_dict = {} if dic['data_type'] in ['PtrDecl', 'ArrayDecl']: return PtrDecl_detect(dic['type']) elif dic['data_type'] == 'TypeDecl': if 'name' in dic.keys(): param_dict['name'] = dic['name'] else: param_dict['name'] = 'VOID' param_dict['type'] = dic['type'] elif dic['data_type'] == 'FuncDecl': param_dict['name'] = dic['func']['name'] param_dict['type'] = dic['func']['type']['type'] else: print(dic['data_type']) exit(0) return param_dict if dir != '.DS_Store': with open("../data/" + dir, 'r') as f: winsdk = json.loads(f.read()) f.close() else: return entry = 'funcdefs' for func in winsdk[entry]: # read function dict if 'name' in func.keys(): func_name = func['name'] elif func['type']['data_type'] == 'TypeDecl': func_name = func['type']['name'] else: func_name = func['type']['type']['name'] if 'api_locations' in func.keys(): func_dll = func['api_locations'][0].lower() else: continue func_dict = {} param_list = [] argument = func['arguments'] for argu in argument: param = PtrDecl_detect(argu) param_list.append(param) func_dict[func_name] = param_list if func_dll in result_dict.keys(): old_func_dict = result_dict[func_dll].copy() result_dict[func_dll] = {} result_dict[func_dll] = dict(old_func_dict, **func_dict) else: result_dict[func_dll] = func_dict def save2json(): print("begin to save ...") for dllname in result_dict: result_json = json.dumps(result_dict[dllname], sort_keys=False, indent=4, separators=(',', ': ')) print(dllname) if dllname[0].isupper(): dllname = '_'+dllname with open(f'./windows_sdk/{dllname.replace(".", "_")}.json', 'w+') as fo: fo.write(result_json) if __name__ == '__main__': dir = '../data' result_dict = {} for parent, dirnames, filenames in os.walk(dir, followlinks=True): for filename in filenames: parse_winsdk(filename) save2json()
qiling/qiling/extensions/windows_sdk/winsdk_dump.py
# windows sdk data file can download here: 'https://github.com/ohjeongwook/windows_sdk_data.git' import json import os result_dict = {} def parse_winsdk(dir): def PtrDecl_detect(dic): param_dict = {} if dic['data_type'] in ['PtrDecl', 'ArrayDecl']: return PtrDecl_detect(dic['type']) elif dic['data_type'] == 'TypeDecl': if 'name' in dic.keys(): param_dict['name'] = dic['name'] else: param_dict['name'] = 'VOID' param_dict['type'] = dic['type'] elif dic['data_type'] == 'FuncDecl': param_dict['name'] = dic['func']['name'] param_dict['type'] = dic['func']['type']['type'] else: print(dic['data_type']) exit(0) return param_dict if dir != '.DS_Store': with open("../data/" + dir, 'r') as f: winsdk = json.loads(f.read()) f.close() else: return entry = 'funcdefs' for func in winsdk[entry]: # read function dict if 'name' in func.keys(): func_name = func['name'] elif func['type']['data_type'] == 'TypeDecl': func_name = func['type']['name'] else: func_name = func['type']['type']['name'] if 'api_locations' in func.keys(): func_dll = func['api_locations'][0].lower() else: continue func_dict = {} param_list = [] argument = func['arguments'] for argu in argument: param = PtrDecl_detect(argu) param_list.append(param) func_dict[func_name] = param_list if func_dll in result_dict.keys(): old_func_dict = result_dict[func_dll].copy() result_dict[func_dll] = {} result_dict[func_dll] = dict(old_func_dict, **func_dict) else: result_dict[func_dll] = func_dict def save2json(): print("begin to save ...") for dllname in result_dict: result_json = json.dumps(result_dict[dllname], sort_keys=False, indent=4, separators=(',', ': ')) print(dllname) if dllname[0].isupper(): dllname = '_'+dllname with open(f'./windows_sdk/{dllname.replace(".", "_")}.json', 'w+') as fo: fo.write(result_json) if __name__ == '__main__': dir = '../data' result_dict = {} for parent, dirnames, filenames in os.walk(dir, followlinks=True): for filename in filenames: parse_winsdk(filename) save2json()
0.278061
0.190009
class TrieNode(object): def __init__(self, is_word=False): # 是否是一个单词,默认为 False self.is_word = is_word; # key 是单个字符,value 是下一个节点 self.next = dict() class Trie: def __init__(self): self._root = TrieNode() # 初始化为 0 self._size = 0 def is_empty(self): # 判空 return self._size == 0 def get_size(self): # 获取树的 size return self._size def contains(self, word): """ 判断单词 word 是否存在于树中 非递归方法 :param word: 待查找单词 :return: """ # 从根节点开始 cur = self._root for character in word: # 查找下一个节点中的字典,没找到返回 None cur = cur.next.get(character, None) if cur is None: return False return cur.is_word is True def contains_recruit(self, node, word, index): """ 判断单词 word 是否存在于树中 递归方法 :param node: 当前节点 :param word: 待查找单词 :param index: 此时到达 word 的哪个 element,即 word[index] 是待考察的 element :return: """ # 递归到底的情况,注意最后一个元素的 is_word 是不是 True if index == len(word): if node.is_word: return True return False dst_element = word[index] # 如果当前节点的 next 的 dict 键中不包含 dst_element if node.next.get(dst_element, None) is None: return False # 否则去到 node 的 next 中以 dst_element 为键的 Node 是否包含 word[index + 1] return self.contains_recruit(node.next[dst_element], word, index+1) def add(self, word): """ 向 Trie 中添加一个 单词 word,注意不是单个字符 迭代方法 :param word: 待添加的单词 :return: """ # 先判断是否已经存在 if self.contains(word): return # 从根节点开始,Trie 的字符串全部是从根节点开始的 cur = self._root for character in word: # 如果 next node 中以 character 为键的值不存在 if cur.next.get(character, None) is None: # 则新建一个 Node 作为 character 的值 cur.next[character] = TrieNode() # 更新 cur 到下一个以 character 为边的 Node cur = cur.next.get(character) # 添加单词,单词尾部的 element 的is_word 一定为 True cur.is_word = True self._size += 1 def add_recruit(self, node, word, index): """ 向 Trie 树中添加一个单词 递归方法 :param node: 当前节点 :param word: 待添加的单词 :param index: 此时到达 word 的哪个 element,即 word[element] 是待考察的 element :return: """ # 递归到底的情况,可能涉及更新当前节点的 is_word if index == len(word): if not node.is_word: node.is_word = True self._size += 1 return dst_element = word[index] # 如果当前节点的 next 的 dict 键中不包含 dst_element if node.next.get(dst_element, Node) is None: # 就为这个键新建一个 Node node.next[dst_element] = TrieNode() return self.add_recruit(node.next[dst_element], word, index+1) def is_prefix(self, prefix): """ 查询是否在 Trie 中有单词以 prefix 为前缀,注意 'abc' 也是 'abc' 的前缀 非递归方法 :param prefix: 待查询字符串 :return: """ cur = self._root for character in prefix: cur = cur.next.get(character, None) if cur is None: return False return True if __name__ == "__main__": # 测试非递归版本 test = Trie() # 测试递归版本 test_recruit = Trie() record = ['你好', 'hello', 'こんにちは', 'pan', 'panda', '我是大哥大666'] print("初始化是否为空:%s" % test.is_empty()) print("此时的 size :%s" % test.get_size()) print("将 record 中的字符串全部添加进 test:") for elem in record: test.add(elem) print("判断 record 中元素是否都已经存在于 test 中:") for elem in record[::-1]: flag = test.contains(elem) if flag: print('"%s" 存在于 test 中' % elem) print("此时的 test 的 size:%s" % test.get_size()) print('"hel" 是否是 test 的前缀:%s' % test.is_prefix('hel'))
maths/L11Trie.py
class TrieNode(object): def __init__(self, is_word=False): # 是否是一个单词,默认为 False self.is_word = is_word; # key 是单个字符,value 是下一个节点 self.next = dict() class Trie: def __init__(self): self._root = TrieNode() # 初始化为 0 self._size = 0 def is_empty(self): # 判空 return self._size == 0 def get_size(self): # 获取树的 size return self._size def contains(self, word): """ 判断单词 word 是否存在于树中 非递归方法 :param word: 待查找单词 :return: """ # 从根节点开始 cur = self._root for character in word: # 查找下一个节点中的字典,没找到返回 None cur = cur.next.get(character, None) if cur is None: return False return cur.is_word is True def contains_recruit(self, node, word, index): """ 判断单词 word 是否存在于树中 递归方法 :param node: 当前节点 :param word: 待查找单词 :param index: 此时到达 word 的哪个 element,即 word[index] 是待考察的 element :return: """ # 递归到底的情况,注意最后一个元素的 is_word 是不是 True if index == len(word): if node.is_word: return True return False dst_element = word[index] # 如果当前节点的 next 的 dict 键中不包含 dst_element if node.next.get(dst_element, None) is None: return False # 否则去到 node 的 next 中以 dst_element 为键的 Node 是否包含 word[index + 1] return self.contains_recruit(node.next[dst_element], word, index+1) def add(self, word): """ 向 Trie 中添加一个 单词 word,注意不是单个字符 迭代方法 :param word: 待添加的单词 :return: """ # 先判断是否已经存在 if self.contains(word): return # 从根节点开始,Trie 的字符串全部是从根节点开始的 cur = self._root for character in word: # 如果 next node 中以 character 为键的值不存在 if cur.next.get(character, None) is None: # 则新建一个 Node 作为 character 的值 cur.next[character] = TrieNode() # 更新 cur 到下一个以 character 为边的 Node cur = cur.next.get(character) # 添加单词,单词尾部的 element 的is_word 一定为 True cur.is_word = True self._size += 1 def add_recruit(self, node, word, index): """ 向 Trie 树中添加一个单词 递归方法 :param node: 当前节点 :param word: 待添加的单词 :param index: 此时到达 word 的哪个 element,即 word[element] 是待考察的 element :return: """ # 递归到底的情况,可能涉及更新当前节点的 is_word if index == len(word): if not node.is_word: node.is_word = True self._size += 1 return dst_element = word[index] # 如果当前节点的 next 的 dict 键中不包含 dst_element if node.next.get(dst_element, Node) is None: # 就为这个键新建一个 Node node.next[dst_element] = TrieNode() return self.add_recruit(node.next[dst_element], word, index+1) def is_prefix(self, prefix): """ 查询是否在 Trie 中有单词以 prefix 为前缀,注意 'abc' 也是 'abc' 的前缀 非递归方法 :param prefix: 待查询字符串 :return: """ cur = self._root for character in prefix: cur = cur.next.get(character, None) if cur is None: return False return True if __name__ == "__main__": # 测试非递归版本 test = Trie() # 测试递归版本 test_recruit = Trie() record = ['你好', 'hello', 'こんにちは', 'pan', 'panda', '我是大哥大666'] print("初始化是否为空:%s" % test.is_empty()) print("此时的 size :%s" % test.get_size()) print("将 record 中的字符串全部添加进 test:") for elem in record: test.add(elem) print("判断 record 中元素是否都已经存在于 test 中:") for elem in record[::-1]: flag = test.contains(elem) if flag: print('"%s" 存在于 test 中' % elem) print("此时的 test 的 size:%s" % test.get_size()) print('"hel" 是否是 test 的前缀:%s' % test.is_prefix('hel'))
0.335242
0.345712
import pytest from mock import Mock from model_mommy import mommy from bpp.models.zrodlo import Zrodlo, Punktacja_Zrodla from integrator2.models.lista_ministerialna import ListaMinisterialnaElement def test_models_lista_ministerialna_input_file_to_dict_stream(lmi): gen = lmi.input_file_to_dict_stream() next(gen) res = next(gen) assert res['nazwa'] == "AAPG BULLETIN" def test_models_lista_ministerialna_b(lmi_b): gen = lmi_b.input_file_to_dict_stream() next(gen) res = next(gen) assert res['nazwa'] == '„Studia Etnologiczne i Antropologiczne”' def test_models_lista_ministerialna_b(lmi_b): gen = lmi_b.input_file_to_dict_stream() next(gen) res = next(gen) assert res['nazwa'] == '„Studia Etnologiczne i Antropologiczne”' def test_models_lista_ministerialna_c(lmi_c): gen = lmi_c.input_file_to_dict_stream() next(gen) res = next(gen) assert res['nazwa'] == '19th Century music' @pytest.mark.django_db def test_models_lista_ministerialna_dict_stream_to_db(lmi): lmi.dict_stream_to_db(limit=20) assert ListaMinisterialnaElement.objects.all().count() == 20 @pytest.mark.django_db def test_models_lista_ministerialna_match_single_record(lmi): z = mommy.make(Zrodlo, nazwa="<NAME>", issn="1111-1111", e_issn="1234-1234") elem = Mock(issn="1111-1111", e_issn=None, nazwa=None) lmi.match_single_record(elem) assert elem.zrodlo == z elem = Mock(issn=None, e_issn="1234-1234", nazwa=None) lmi.match_single_record(elem) assert elem.zrodlo == z elem = Mock(issn=None, e_issn=None, nazwa="<NAME>") lmi.match_single_record(elem) assert elem.zrodlo == z @pytest.mark.django_db def test_models_integrate_single_record(lmi): z = mommy.make(Zrodlo, nazwa="<NAME>", issn="1111-1111", e_issn="1234-1234") elem = Mock(issn="1111-1111", e_issn=None, nazwa=None, zrodlo=z, punkty_kbn=999) elem.parent = Mock(year=2005) lmi.integrate_single_record(elem) pz = Punktacja_Zrodla.objects.get(zrodlo=z) assert pz.punkty_kbn == 999
src/integrator2/tests/test_models_lista_ministerialna.py
import pytest from mock import Mock from model_mommy import mommy from bpp.models.zrodlo import Zrodlo, Punktacja_Zrodla from integrator2.models.lista_ministerialna import ListaMinisterialnaElement def test_models_lista_ministerialna_input_file_to_dict_stream(lmi): gen = lmi.input_file_to_dict_stream() next(gen) res = next(gen) assert res['nazwa'] == "AAPG BULLETIN" def test_models_lista_ministerialna_b(lmi_b): gen = lmi_b.input_file_to_dict_stream() next(gen) res = next(gen) assert res['nazwa'] == '„Studia Etnologiczne i Antropologiczne”' def test_models_lista_ministerialna_b(lmi_b): gen = lmi_b.input_file_to_dict_stream() next(gen) res = next(gen) assert res['nazwa'] == '„Studia Etnologiczne i Antropologiczne”' def test_models_lista_ministerialna_c(lmi_c): gen = lmi_c.input_file_to_dict_stream() next(gen) res = next(gen) assert res['nazwa'] == '19th Century music' @pytest.mark.django_db def test_models_lista_ministerialna_dict_stream_to_db(lmi): lmi.dict_stream_to_db(limit=20) assert ListaMinisterialnaElement.objects.all().count() == 20 @pytest.mark.django_db def test_models_lista_ministerialna_match_single_record(lmi): z = mommy.make(Zrodlo, nazwa="<NAME>", issn="1111-1111", e_issn="1234-1234") elem = Mock(issn="1111-1111", e_issn=None, nazwa=None) lmi.match_single_record(elem) assert elem.zrodlo == z elem = Mock(issn=None, e_issn="1234-1234", nazwa=None) lmi.match_single_record(elem) assert elem.zrodlo == z elem = Mock(issn=None, e_issn=None, nazwa="<NAME>") lmi.match_single_record(elem) assert elem.zrodlo == z @pytest.mark.django_db def test_models_integrate_single_record(lmi): z = mommy.make(Zrodlo, nazwa="<NAME>", issn="1111-1111", e_issn="1234-1234") elem = Mock(issn="1111-1111", e_issn=None, nazwa=None, zrodlo=z, punkty_kbn=999) elem.parent = Mock(year=2005) lmi.integrate_single_record(elem) pz = Punktacja_Zrodla.objects.get(zrodlo=z) assert pz.punkty_kbn == 999
0.473657
0.475423
import curses import sys import time import pyfmodex from pyfmodex.enums import RESULT, SPEAKERMODE, TIMEUNIT from pyfmodex.exceptions import FmodError from pyfmodex.flags import MODE MIN_FMOD_VERSION = 0x00020108 CHOICES = ( "Mono from front left speaker", "Mono from front right speaker", "Mono from center speaker", "Mono from surround left speaker", "Mono from surround right speaker", "Mono from rear left speaker", "Mono from rear right speaker", "Stereo from front speakers", "Stereo from front speakers (channels swapped)", "Stereo (right only) from center speaker", ) # Create a System object and initialize system = pyfmodex.System() VERSION = system.version if VERSION < MIN_FMOD_VERSION: print( f"FMOD lib version {VERSION:#08x} doesn't meet " f"minimum requirement of version {MIN_FMOD_VERSION:#08x}" ) sys.exit(1) system.init(maxchannels=len(CHOICES)) speaker_mode = SPEAKERMODE(system.software_format.speaker_mode) sound_mono = system.create_sound("media/drumloop.wav", mode=MODE.TWOD | MODE.LOOP_OFF) sound_stereo = system.create_sound("media/stereo.ogg", mode=MODE.TWOD | MODE.LOOP_OFF) def is_choice_available(choice_idx): """Is the given configuration choice available in the current speakermode?""" if speaker_mode in (SPEAKERMODE.MONO, SPEAKERMODE.STEREO): return choice_idx not in (2, 3, 4, 5, 6, 9) if speaker_mode == SPEAKERMODE.QUAD: return choice_idx not in (2, 5, 6, 9) if speaker_mode in (SPEAKERMODE.SURROUND, SPEAKERMODE.FIVEPOINTONE): return choice_idx not in (5, 6) return True def play_sound(choice_idx): """Play a sound in the given configuration choice. Returns the created channel. """ channel = None if choice_idx == 0: # Mono front left channel = system.play_sound(sound_mono, paused=True) channel.set_mix_levels_output(1, 0, 0, 0, 0, 0, 0, 0) channel.paused = False elif choice_idx == 1: # Mono front right channel = system.play_sound(sound_mono, paused=True) channel.set_mix_levels_output(0, 1, 0, 0, 0, 0, 0, 0) channel.paused = False elif choice_idx == 2: # Mono centre channel = system.play_sound(sound_mono, paused=True) channel.set_mix_levels_output(0, 0, 1, 0, 0, 0, 0, 0) channel.paused = False elif choice_idx == 3: # Mono surround left channel = system.play_sound(sound_mono, paused=True) channel.set_mix_levels_output(0, 0, 0, 0, 1, 0, 0, 0) channel.paused = False elif choice_idx == 4: # Mono surround right channel = system.play_sound(sound_mono, paused=True) channel.set_mix_levels_output(0, 0, 0, 0, 0, 1, 0, 0) channel.paused = False elif choice_idx == 5: # Mono read left channel = system.play_sound(sound_mono, paused=True) channel.set_mix_levels_output(0, 0, 0, 0, 0, 0, 1, 0) channel.paused = False elif choice_idx == 6: # Mono read right channel = system.play_sound(sound_mono, paused=True) channel.set_mix_levels_output(0, 0, 0, 0, 0, 0, 0, 1) channel.paused = False elif choice_idx == 7: # Stereo format channel = system.play_sound(sound_stereo) elif choice_idx == 8: # Stereo front channel swapped matrix = [0, 1, 1, 0] channel = system.play_sound(sound_stereo, paused=True) channel.set_mix_matrix(matrix, 2, 2) channel.paused = False elif choice_idx == 8: # Stereo (right only) center matrix = [0, 0, 0, 0, 0, 1] channel = system.play_sound(sound_stereo, paused=True) channel.set_mix_matrix(matrix, 3, 2) channel.paused = False return channel # Main loop def main(stdscr): """Draw a simple TUI, grab keypresses and let the user play the sounds.""" stdscr.clear() stdscr.nodelay(True) # Create small visual display all_opts = speaker_mode.value >= SPEAKERMODE.SEVENPOINTONE.value stdscr.addstr( "=========================\n" "Multiple Speaker Example.\n" "=========================\n" "\n" "Press j or k to select mode\n" "Press SPACE to play the sound\n" "Press q to quit\n" "\n" f"Speaker mode is set to {speaker_mode.name}" " causing some speaker options to be unavailale" if not all_opts else "" ) channel = None currentsound = None choice_idx = 0 while True: stdscr.move(10, 0) for idx, choice in enumerate(CHOICES): available = is_choice_available(idx) sel = "-" if not available else "X" if choice_idx == idx else " " stdscr.addstr(f"[{sel}] {choice}\n") is_playing = False position = 0 length = 0 if channel: try: is_playing = channel.is_playing position = channel.get_position(TIMEUNIT.MS) currentsound = channel.current_sound if currentsound: length = currentsound.get_length(TIMEUNIT.MS) except FmodError as fmoderror: if fmoderror.result not in ( RESULT.INVALID_HANDLE, RESULT.CHANNEL_STOLEN, ): raise fmoderror stdscr.move(11 + len(CHOICES), 0) stdscr.clrtoeol() stdscr.addstr( "Time %02d:%02d:%02d/%02d:%02d:%02d : %s\n" % ( position / 1000 / 60, position / 1000 % 60, position / 10 % 100, length / 1000 / 60, length / 1000 % 60, length / 10 % 100, "Playing" if is_playing else "Stopped", ), ) stdscr.addstr(f"Channels playing: {system.channels_playing.channels:-2d}") # Listen to the user try: keypress = stdscr.getkey() if keypress == "k": old_idx = choice_idx while True: choice_idx = max(choice_idx - 1, 0) if is_choice_available(choice_idx): break if choice_idx == 0: choice_idx = old_idx break elif keypress == "j": old_idx = choice_idx while True: choice_idx = min(choice_idx + 1, len(CHOICES) - 1) if is_choice_available(choice_idx): break if choice_idx == len(CHOICES) - 1: choice_idx = old_idx break elif keypress == " ": channel = play_sound(choice_idx) elif keypress == "q": break except curses.error as cerr: if cerr.args[0] != "no input": raise cerr system.update() time.sleep(50 / 1000) curses.wrapper(main) # Shut down sound_mono.release() sound_stereo.release() system.release()
docs/sample_code/multiple_speaker.py
import curses import sys import time import pyfmodex from pyfmodex.enums import RESULT, SPEAKERMODE, TIMEUNIT from pyfmodex.exceptions import FmodError from pyfmodex.flags import MODE MIN_FMOD_VERSION = 0x00020108 CHOICES = ( "Mono from front left speaker", "Mono from front right speaker", "Mono from center speaker", "Mono from surround left speaker", "Mono from surround right speaker", "Mono from rear left speaker", "Mono from rear right speaker", "Stereo from front speakers", "Stereo from front speakers (channels swapped)", "Stereo (right only) from center speaker", ) # Create a System object and initialize system = pyfmodex.System() VERSION = system.version if VERSION < MIN_FMOD_VERSION: print( f"FMOD lib version {VERSION:#08x} doesn't meet " f"minimum requirement of version {MIN_FMOD_VERSION:#08x}" ) sys.exit(1) system.init(maxchannels=len(CHOICES)) speaker_mode = SPEAKERMODE(system.software_format.speaker_mode) sound_mono = system.create_sound("media/drumloop.wav", mode=MODE.TWOD | MODE.LOOP_OFF) sound_stereo = system.create_sound("media/stereo.ogg", mode=MODE.TWOD | MODE.LOOP_OFF) def is_choice_available(choice_idx): """Is the given configuration choice available in the current speakermode?""" if speaker_mode in (SPEAKERMODE.MONO, SPEAKERMODE.STEREO): return choice_idx not in (2, 3, 4, 5, 6, 9) if speaker_mode == SPEAKERMODE.QUAD: return choice_idx not in (2, 5, 6, 9) if speaker_mode in (SPEAKERMODE.SURROUND, SPEAKERMODE.FIVEPOINTONE): return choice_idx not in (5, 6) return True def play_sound(choice_idx): """Play a sound in the given configuration choice. Returns the created channel. """ channel = None if choice_idx == 0: # Mono front left channel = system.play_sound(sound_mono, paused=True) channel.set_mix_levels_output(1, 0, 0, 0, 0, 0, 0, 0) channel.paused = False elif choice_idx == 1: # Mono front right channel = system.play_sound(sound_mono, paused=True) channel.set_mix_levels_output(0, 1, 0, 0, 0, 0, 0, 0) channel.paused = False elif choice_idx == 2: # Mono centre channel = system.play_sound(sound_mono, paused=True) channel.set_mix_levels_output(0, 0, 1, 0, 0, 0, 0, 0) channel.paused = False elif choice_idx == 3: # Mono surround left channel = system.play_sound(sound_mono, paused=True) channel.set_mix_levels_output(0, 0, 0, 0, 1, 0, 0, 0) channel.paused = False elif choice_idx == 4: # Mono surround right channel = system.play_sound(sound_mono, paused=True) channel.set_mix_levels_output(0, 0, 0, 0, 0, 1, 0, 0) channel.paused = False elif choice_idx == 5: # Mono read left channel = system.play_sound(sound_mono, paused=True) channel.set_mix_levels_output(0, 0, 0, 0, 0, 0, 1, 0) channel.paused = False elif choice_idx == 6: # Mono read right channel = system.play_sound(sound_mono, paused=True) channel.set_mix_levels_output(0, 0, 0, 0, 0, 0, 0, 1) channel.paused = False elif choice_idx == 7: # Stereo format channel = system.play_sound(sound_stereo) elif choice_idx == 8: # Stereo front channel swapped matrix = [0, 1, 1, 0] channel = system.play_sound(sound_stereo, paused=True) channel.set_mix_matrix(matrix, 2, 2) channel.paused = False elif choice_idx == 8: # Stereo (right only) center matrix = [0, 0, 0, 0, 0, 1] channel = system.play_sound(sound_stereo, paused=True) channel.set_mix_matrix(matrix, 3, 2) channel.paused = False return channel # Main loop def main(stdscr): """Draw a simple TUI, grab keypresses and let the user play the sounds.""" stdscr.clear() stdscr.nodelay(True) # Create small visual display all_opts = speaker_mode.value >= SPEAKERMODE.SEVENPOINTONE.value stdscr.addstr( "=========================\n" "Multiple Speaker Example.\n" "=========================\n" "\n" "Press j or k to select mode\n" "Press SPACE to play the sound\n" "Press q to quit\n" "\n" f"Speaker mode is set to {speaker_mode.name}" " causing some speaker options to be unavailale" if not all_opts else "" ) channel = None currentsound = None choice_idx = 0 while True: stdscr.move(10, 0) for idx, choice in enumerate(CHOICES): available = is_choice_available(idx) sel = "-" if not available else "X" if choice_idx == idx else " " stdscr.addstr(f"[{sel}] {choice}\n") is_playing = False position = 0 length = 0 if channel: try: is_playing = channel.is_playing position = channel.get_position(TIMEUNIT.MS) currentsound = channel.current_sound if currentsound: length = currentsound.get_length(TIMEUNIT.MS) except FmodError as fmoderror: if fmoderror.result not in ( RESULT.INVALID_HANDLE, RESULT.CHANNEL_STOLEN, ): raise fmoderror stdscr.move(11 + len(CHOICES), 0) stdscr.clrtoeol() stdscr.addstr( "Time %02d:%02d:%02d/%02d:%02d:%02d : %s\n" % ( position / 1000 / 60, position / 1000 % 60, position / 10 % 100, length / 1000 / 60, length / 1000 % 60, length / 10 % 100, "Playing" if is_playing else "Stopped", ), ) stdscr.addstr(f"Channels playing: {system.channels_playing.channels:-2d}") # Listen to the user try: keypress = stdscr.getkey() if keypress == "k": old_idx = choice_idx while True: choice_idx = max(choice_idx - 1, 0) if is_choice_available(choice_idx): break if choice_idx == 0: choice_idx = old_idx break elif keypress == "j": old_idx = choice_idx while True: choice_idx = min(choice_idx + 1, len(CHOICES) - 1) if is_choice_available(choice_idx): break if choice_idx == len(CHOICES) - 1: choice_idx = old_idx break elif keypress == " ": channel = play_sound(choice_idx) elif keypress == "q": break except curses.error as cerr: if cerr.args[0] != "no input": raise cerr system.update() time.sleep(50 / 1000) curses.wrapper(main) # Shut down sound_mono.release() sound_stereo.release() system.release()
0.443118
0.140484
import logging import socket import asyncio import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.const import ( CONF_USERNAME, CONF_PASSWORD, CONF_SCAN_INTERVAL) from homeassistant.helpers import discovery _LOGGER = logging.getLogger(__name__) CONF_CLIENT_ID = 'client_id' CONF_CLIENT_SECRET = 'client_secret' DOMAIN = 'mind' DATA_MIND = 'mind' TOKEN_FILE = 'mind.conf' CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=270): cv.positive_int, vol.Optional(CONF_CLIENT_ID, default='f531922867194c7197b8df82da18042e'): cv.string, vol.Optional(CONF_CLIENT_SECRET, default='eB7ecfF84ed94CBDA825AC6dee503Fca'): cv.string, }) }, extra=vol.ALLOW_EXTRA) def setup(hass, config): """Set up the Mind component.""" conf = config.get(DOMAIN) hass.data[DATA_MIND] = Mind(hass, conf) _LOGGER.debug("Setup Mind") discovery.load_platform(hass, 'device_tracker', DOMAIN, {}, config) discovery.load_platform(hass, 'sensor', DOMAIN, {}, config) discovery.load_platform(hass, 'binary_sensor', DOMAIN, {}, config) return True class Mind(object): """Structure Mind functions for hass.""" def __init__(self, hass, conf): """Init Mind devices.""" import mind access_token_cache_file = hass.config.path(TOKEN_FILE) #_LOGGER.debug("conf: %s" % conf) self.mind = mind.Mind( token_cache_file=access_token_cache_file, client_id=conf.get(CONF_CLIENT_ID), client_secret=conf.get(CONF_CLIENT_SECRET), username=conf.get(CONF_USERNAME), password=conf.get(CONF_PASSWORD), cache_ttl=conf.get(CONF_SCAN_INTERVAL)) @property def data(self): return self.mind def drivers(self): """Generate a list of drivers.""" for driver in self.mind.drivers: yield driver def vehicles(self): """Generate a list of vehicles and their location.""" for vehicle in self.mind.vehicles: yield vehicle
custom_components/mind/__init__.py
import logging import socket import asyncio import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.const import ( CONF_USERNAME, CONF_PASSWORD, CONF_SCAN_INTERVAL) from homeassistant.helpers import discovery _LOGGER = logging.getLogger(__name__) CONF_CLIENT_ID = 'client_id' CONF_CLIENT_SECRET = 'client_secret' DOMAIN = 'mind' DATA_MIND = 'mind' TOKEN_FILE = 'mind.conf' CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=270): cv.positive_int, vol.Optional(CONF_CLIENT_ID, default='f531922867194c7197b8df82da18042e'): cv.string, vol.Optional(CONF_CLIENT_SECRET, default='eB7ecfF84ed94CBDA825AC6dee503Fca'): cv.string, }) }, extra=vol.ALLOW_EXTRA) def setup(hass, config): """Set up the Mind component.""" conf = config.get(DOMAIN) hass.data[DATA_MIND] = Mind(hass, conf) _LOGGER.debug("Setup Mind") discovery.load_platform(hass, 'device_tracker', DOMAIN, {}, config) discovery.load_platform(hass, 'sensor', DOMAIN, {}, config) discovery.load_platform(hass, 'binary_sensor', DOMAIN, {}, config) return True class Mind(object): """Structure Mind functions for hass.""" def __init__(self, hass, conf): """Init Mind devices.""" import mind access_token_cache_file = hass.config.path(TOKEN_FILE) #_LOGGER.debug("conf: %s" % conf) self.mind = mind.Mind( token_cache_file=access_token_cache_file, client_id=conf.get(CONF_CLIENT_ID), client_secret=conf.get(CONF_CLIENT_SECRET), username=conf.get(CONF_USERNAME), password=conf.get(CONF_PASSWORD), cache_ttl=conf.get(CONF_SCAN_INTERVAL)) @property def data(self): return self.mind def drivers(self): """Generate a list of drivers.""" for driver in self.mind.drivers: yield driver def vehicles(self): """Generate a list of vehicles and their location.""" for vehicle in self.mind.vehicles: yield vehicle
0.433502
0.055618
import re import requests from bs4 import BeautifulSoup class AnavNet: __url = "http://anavnet.hidrografico.pt/AvisosLocais/AvisosLocais.aspx?Porto=" __keys = { 'num_aviso': 'LabelNoAviso', 'dt_promulgacao': 'DATAPROMULGACAOLabel', 'dt_inicio': 'DATAINICIOLabel', 'dt_fim': 'DATAFIMLabel', 'ent_promulgacao': 'ENTPROMULGACAOLabel', 'local': 'DESCPORTOLOCALLabel', 'assunto': 'ASSUNTOLabel', 'descricao': 'DESCRICAOLabel', 'dt_cancelamento': 'LabelDataCancelar' } __ports = { 37: u"Angra do Heroismo", 10: u"Aveiro", 1: u"Caminha", 14: u"Cascais", 8: u"Douro", 27: u"Faro", 11: u"Figueira da Foz", 32: u"Funchal", 40: u"Horta", 23: u"Lagos", 7: u"Leixões", 16: u"Lisboa", 12: u"Nazaré", 29: u"Olhão", 44: u"Peniche", 34: u"Ponta Delgada", 25: u"Portimão", 33: u"Porto Santo", 5: u"Pov<NAME>", 36: u"Praia da Vitória", 43: u"Santa Cruz das Flores", 20: u"Setúbal", 22: u"Sines", 45: u"Tavira", 3: u"Viana do Castelo", 30: u"Vila Real de Santo António", 6: u"Vila do Conde", 35: u"Vila do Porto", } __current_index = None __current_port = None __current_total = None __soup = None __values = {} def set_port(self, port): if port not in self.__ports: raise KeyError('Invalid port') self.__current_port = port r = requests.get(self.__url + str(self.__current_port)) self.__soup = BeautifulSoup(r.text, features="html.parser") self.__count_total() def get_port_name(self): if self.__current_port is None: raise RuntimeError("Run set_port() first") return self.__ports[self.__current_port] def get_ports(self): return self.__ports def get_message(self, index): if self.__current_port is None: raise RuntimeError("Run set_port() first") self.__current_index = "{:0>2d}".format(index) # Add a zero to the left if index > self.__current_total or index < 1: raise IndexError("Invalid index") else: self.__parse_message() return self.__values def get_total_messages(self): if self.__current_port is None: raise RuntimeError("Run set_port() first") return self.__current_total def __count_total(self): self.__current_total = len(self.__soup.findAll("span", {"id": re.compile('.*LabelIDAviso$')})) def __parse_message(self): self.__values = {} for k in self.__keys: self.__values[k] = self.__get_item_value(self.__keys[k]) def __get_item_value(self, name): f = self.__soup.find( "span", {"id": "ctl00_ContentPlaceHolder1_DataListAvisosLocais_ctl" + self.__current_index + "_" + name} ) if f is None: return f if f.string is None: out = "" for s in f.stripped_strings: out += s + "\n" return out.rstrip() else: return f.string
anavnet/anavnet.py
import re import requests from bs4 import BeautifulSoup class AnavNet: __url = "http://anavnet.hidrografico.pt/AvisosLocais/AvisosLocais.aspx?Porto=" __keys = { 'num_aviso': 'LabelNoAviso', 'dt_promulgacao': 'DATAPROMULGACAOLabel', 'dt_inicio': 'DATAINICIOLabel', 'dt_fim': 'DATAFIMLabel', 'ent_promulgacao': 'ENTPROMULGACAOLabel', 'local': 'DESCPORTOLOCALLabel', 'assunto': 'ASSUNTOLabel', 'descricao': 'DESCRICAOLabel', 'dt_cancelamento': 'LabelDataCancelar' } __ports = { 37: u"Angra do Heroismo", 10: u"Aveiro", 1: u"Caminha", 14: u"Cascais", 8: u"Douro", 27: u"Faro", 11: u"Figueira da Foz", 32: u"Funchal", 40: u"Horta", 23: u"Lagos", 7: u"Leixões", 16: u"Lisboa", 12: u"Nazaré", 29: u"Olhão", 44: u"Peniche", 34: u"Ponta Delgada", 25: u"Portimão", 33: u"Porto Santo", 5: u"Pov<NAME>", 36: u"Praia da Vitória", 43: u"Santa Cruz das Flores", 20: u"Setúbal", 22: u"Sines", 45: u"Tavira", 3: u"Viana do Castelo", 30: u"Vila Real de Santo António", 6: u"Vila do Conde", 35: u"Vila do Porto", } __current_index = None __current_port = None __current_total = None __soup = None __values = {} def set_port(self, port): if port not in self.__ports: raise KeyError('Invalid port') self.__current_port = port r = requests.get(self.__url + str(self.__current_port)) self.__soup = BeautifulSoup(r.text, features="html.parser") self.__count_total() def get_port_name(self): if self.__current_port is None: raise RuntimeError("Run set_port() first") return self.__ports[self.__current_port] def get_ports(self): return self.__ports def get_message(self, index): if self.__current_port is None: raise RuntimeError("Run set_port() first") self.__current_index = "{:0>2d}".format(index) # Add a zero to the left if index > self.__current_total or index < 1: raise IndexError("Invalid index") else: self.__parse_message() return self.__values def get_total_messages(self): if self.__current_port is None: raise RuntimeError("Run set_port() first") return self.__current_total def __count_total(self): self.__current_total = len(self.__soup.findAll("span", {"id": re.compile('.*LabelIDAviso$')})) def __parse_message(self): self.__values = {} for k in self.__keys: self.__values[k] = self.__get_item_value(self.__keys[k]) def __get_item_value(self, name): f = self.__soup.find( "span", {"id": "ctl00_ContentPlaceHolder1_DataListAvisosLocais_ctl" + self.__current_index + "_" + name} ) if f is None: return f if f.string is None: out = "" for s in f.stripped_strings: out += s + "\n" return out.rstrip() else: return f.string
0.417746
0.149252
from __future__ import unicode_literals import frappe from frappe import _ import io import openpyxl from frappe.utils import cint, get_site_url, get_url from art_collections.controllers.excel import write_xlsx, attach_file def on_submit_request_for_quotation(doc, method=None): _make_excel_attachment(doc.doctype, doc.name) @frappe.whitelist() def _make_excel_attachment(doctype, docname): from art_collections.controllers.excel import write_xlsx data = frappe.db.sql( """ select i.item_code, trfqi.supplier_part_no , tib.barcode, i.customs_tariff_number , trfqi.qty, trfqi.stock_uom , 0 base_net_rate , 0 base_net_amount , case when i.image is null then '' when SUBSTR(i.image,1,4) = 'http' then i.image else concat('{}/',i.image) end image from `tabRequest for Quotation` trfq inner join `tabRequest for Quotation Item` trfqi on trfqi.parent = trfq.name inner join tabItem i on i.name = trfqi.item_code left outer join `tabItem Barcode` tib on tib.parent = i.name and tib.idx = ( select min(idx) from `tabItem Barcode` tib2 where parent = i.name ) where trfq.name = %s """.format( get_url() ), (docname,), as_dict=True, # debug=True, ) columns = [ _("Item Code"), _("Supplier items"), _("Barcode"), _("HSCode"), _("Quantity"), _("Stock UOM"), _("Rate (EUR)"), _("Amount (EUR)"), _("Photo"), ] fields = [ "item_code", "supplier_part_no", "barcode", "customs_tariff_number", "qty", "stock_uom", "base_net_rate", "base_net_amount", "image", ] wb = openpyxl.Workbook() excel_rows = [columns] for d in data: excel_rows.append([d.get(f) for f in fields]) write_xlsx(excel_rows, "RFQ Items", wb, [20] * len(columns)) # make attachment out = io.BytesIO() wb.save(out) attach_file( out.getvalue(), doctype=doctype, docname=docname, )
art_collections/controllers/excel/request_for_quotation_excel.py
from __future__ import unicode_literals import frappe from frappe import _ import io import openpyxl from frappe.utils import cint, get_site_url, get_url from art_collections.controllers.excel import write_xlsx, attach_file def on_submit_request_for_quotation(doc, method=None): _make_excel_attachment(doc.doctype, doc.name) @frappe.whitelist() def _make_excel_attachment(doctype, docname): from art_collections.controllers.excel import write_xlsx data = frappe.db.sql( """ select i.item_code, trfqi.supplier_part_no , tib.barcode, i.customs_tariff_number , trfqi.qty, trfqi.stock_uom , 0 base_net_rate , 0 base_net_amount , case when i.image is null then '' when SUBSTR(i.image,1,4) = 'http' then i.image else concat('{}/',i.image) end image from `tabRequest for Quotation` trfq inner join `tabRequest for Quotation Item` trfqi on trfqi.parent = trfq.name inner join tabItem i on i.name = trfqi.item_code left outer join `tabItem Barcode` tib on tib.parent = i.name and tib.idx = ( select min(idx) from `tabItem Barcode` tib2 where parent = i.name ) where trfq.name = %s """.format( get_url() ), (docname,), as_dict=True, # debug=True, ) columns = [ _("Item Code"), _("Supplier items"), _("Barcode"), _("HSCode"), _("Quantity"), _("Stock UOM"), _("Rate (EUR)"), _("Amount (EUR)"), _("Photo"), ] fields = [ "item_code", "supplier_part_no", "barcode", "customs_tariff_number", "qty", "stock_uom", "base_net_rate", "base_net_amount", "image", ] wb = openpyxl.Workbook() excel_rows = [columns] for d in data: excel_rows.append([d.get(f) for f in fields]) write_xlsx(excel_rows, "RFQ Items", wb, [20] * len(columns)) # make attachment out = io.BytesIO() wb.save(out) attach_file( out.getvalue(), doctype=doctype, docname=docname, )
0.371935
0.182991
import lxml.objectify import http.client import urllib.parse from .utils.dates import * from .feeds import InvalidFeed __all__ = ('ParseError', 'InvalidFeed', 'from_string', 'from_url', 'from_file', 'parse_date') # TODO: change the feeds to a registration model from .feeds.atom10 import Atom10Feed from .feeds.rss20 import RSS20Feed feeds = (RSS20Feed, Atom10Feed) ACCEPT_HEADER = "application/atom+xml,application/rdf+xml,application/rss+xml,application/x-netcdf,application/xml;q=0.9,text/xml;q=0.2,*/*;q=0.1" USER_AGENT = 'py-feedreader' class ParseError(Exception): pass def _from_parsed(parsed): for feed in feeds: try: result = feed(parsed) except InvalidFeed: pass else: return result raise InvalidFeed(parsed.tag) def from_string(data, *args, **kwargs): parsed = lxml.objectify.fromstring(data, *args, **kwargs) return _from_parsed(parsed) def from_file(fp, *args, **kwargs): parsed = lxml.objectify.parse(fp, **kwargs).getroot() return _from_parsed(parsed) def from_url(url, **kwargs): url = urllib.parse.urlparse(url) if url.scheme == 'https': conn = http.client.HTTPSConnection elif url.scheme == 'http': conn = http.client.HTTPConnection else: raise NotImplementedError base_url = '%s://%s' % (url.scheme, url.hostname) headers = { 'User-Agent': USER_AGENT, 'Accept': ACCEPT_HEADER, } connection = conn(url.hostname) method = kwargs.pop('method', 'GET').upper() if method == 'GET': path, query = url.path, '' if url.query: path += '?' + url.query else: path, query = url.path, url.query connection.request(method, path, query, headers) try: response = connection.getresponse() except http.client.BadStatusLine as exc: raise ParseError('Bad status line: %s' % (exc,)) if response.status != 200: if response.status in (301, 302): return from_url(response.getheader('location'), **kwargs) raise ParseError('%s %s' % (response.status, response.reason)) return from_file(response, base_url=base_url)
feedreader/parser.py
import lxml.objectify import http.client import urllib.parse from .utils.dates import * from .feeds import InvalidFeed __all__ = ('ParseError', 'InvalidFeed', 'from_string', 'from_url', 'from_file', 'parse_date') # TODO: change the feeds to a registration model from .feeds.atom10 import Atom10Feed from .feeds.rss20 import RSS20Feed feeds = (RSS20Feed, Atom10Feed) ACCEPT_HEADER = "application/atom+xml,application/rdf+xml,application/rss+xml,application/x-netcdf,application/xml;q=0.9,text/xml;q=0.2,*/*;q=0.1" USER_AGENT = 'py-feedreader' class ParseError(Exception): pass def _from_parsed(parsed): for feed in feeds: try: result = feed(parsed) except InvalidFeed: pass else: return result raise InvalidFeed(parsed.tag) def from_string(data, *args, **kwargs): parsed = lxml.objectify.fromstring(data, *args, **kwargs) return _from_parsed(parsed) def from_file(fp, *args, **kwargs): parsed = lxml.objectify.parse(fp, **kwargs).getroot() return _from_parsed(parsed) def from_url(url, **kwargs): url = urllib.parse.urlparse(url) if url.scheme == 'https': conn = http.client.HTTPSConnection elif url.scheme == 'http': conn = http.client.HTTPConnection else: raise NotImplementedError base_url = '%s://%s' % (url.scheme, url.hostname) headers = { 'User-Agent': USER_AGENT, 'Accept': ACCEPT_HEADER, } connection = conn(url.hostname) method = kwargs.pop('method', 'GET').upper() if method == 'GET': path, query = url.path, '' if url.query: path += '?' + url.query else: path, query = url.path, url.query connection.request(method, path, query, headers) try: response = connection.getresponse() except http.client.BadStatusLine as exc: raise ParseError('Bad status line: %s' % (exc,)) if response.status != 200: if response.status in (301, 302): return from_url(response.getheader('location'), **kwargs) raise ParseError('%s %s' % (response.status, response.reason)) return from_file(response, base_url=base_url)
0.195748
0.075448
from pyspark import SparkContext, SparkConf, SparkFiles from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils from msgParser import * import msgParser import json import happybase import sys import os import pika import time from influxdb import InfluxDBClient SPARK_PERIOD_SEC = int(os.environ["SPARK_PERIOD_SEC"]) # 5 ZKQUORUM = os.environ['ZKQUORUM'] #"zk-cs.datacenter.svc.cluster.local:2181" QUEUE_NAME = os.environ["QUEUE_NAME"] QUEUE_TOPIC = os.environ["QUEUE_TOPIC"] RABITMQ = os.environ["RABITMQ"] sensorList_table = "_SensorList" data_table = "_Data" version_table = "_Version" INFLUXDB = os.environ["INFLUXDB_SERVICE"] def saveInfluxDBData(data_dict) : client = InfluxDBClient(INFLUXDB, 8086) try: client.create_database('mydb') except Exception as e: print(e) pass try: client.switch_database('mydb') except Exception as e: print(e) pass data_dict = json.loads(data_dict) CraneFullName = data_dict['CraneFullName'] input_value = [] for key , value in data_dict.items() : dict_put = { 'measurement' : CraneFullName + data_table, 'tags' : { 'SensorName' : key }, 'fields' : { 'Value' : value } } input_value.append(dict_put) client.write_points(input_value) def streaming_set() : sc = SparkContext(appName="PythonStreamingPreprocessing") ssc = StreamingContext(sc, SPARK_PERIOD_SEC) # 1 second window zkQuorum = ZKQUORUM #Dict of (topic_name -> numPartitions) to consume. Each partition is consumed in its own thread. topics = {'http': 1, 'mqtt' : 1, 'coap' : 1} stream = KafkaUtils.createStream(ssc, zkQuorum, "raw-event-streaming-consumer", topics, {"auto.offset.reset": "largest"}) return ssc, stream def msg_parse(data) : data_list = data.split("|") CraneFullName = data_list[0] Time = data_list[1] OBD_DataList = data_list[2:-1] Crane_Data = data_list[-1] getDataFromInfluxDB(INFLUXDB, CraneFullName) OBD_II_data_dict = {} sensor_data_dict = {} if Crane_Data == None: pass else: sensor_data_encoded_hex = Crane_Data sensor_data_dict = sensor_data_parser(sensor_data_encoded_hex) if sensor_data_dict == 'ignore' : error_dict = {} error_dict["FormatError"] = "Crane" error_dict["CraneFullName"] = CraneFullName jsonString = makeJson(error_dict) return jsonString data_dict = make_dict(Time, CraneFullName, OBD_II_data_dict , sensor_data_dict) jsonString = makeJson(data_dict) return jsonString credentials = pika.PlainCredentials('dtuser01', '<PASSWORD>') params = pika.ConnectionParameters(RABITMQ, 5672, '/', credentials) #queue_connection = pika.BlockingConnection(params) #channel = queue_connection.channel() #channel.queue_declare(queue=QUEUE_NAME) def transfer_list(json_list) : global channel global queue_connection for json_data in json_list: check_dict = json.loads(json_data) if not "FormatError" in check_dict: try: channel.basic_publish(exchange='',routing_key=QUEUE_TOPIC, body=json_data) except Exception as e: print("AMQP publish Exception.." +str(e)) print("recreate connection...") print("JsonData : "+str(json_data)) queue_connection = pika.BlockingConnection(params) channel = queue_connection.channel() channel.queue_declare(queue=QUEUE_NAME) channel.basic_publish(exchange='',routing_key=QUEUE_TOPIC, body=json_data) saveInfluxDBData(json_data) else: print("ERROR") def parse_function(rdd) : json_format_rdd = rdd.map(lambda data : msg_parse(data)) json_format_list = json_format_rdd.take(int(json_format_rdd.count())) if len(json_format_list) != 0: transfer_list(json_format_list) def main() : ssc, stream = streaming_set() raw_data = stream.map(lambda value: value[1]) raw_data.foreachRDD(lambda rdd : parse_function(rdd) ) ssc.start() ssc.awaitTermination() if __name__ == "__main__": main() # test_msg = "SHINHAN_Crane_1|2020-11-06 11:09:20|H 135.2000.0-07.6000.0364.9000.001030101999.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9000.000000000.00000000000000000010000000000" # test_msg = "SHINHAN_Crane_1|3|2019-12-19 10:38:14|+287.724852+20.527328+22.54130544.3022.4277.4003266909840113017505822271-07.89-2.28+1.61+0.00-07.27+0.4001112209N" # jsonString = msg_parse(test_msg) # saveInfluxDBData(jsonString)
example/dt/7.preprocessor/docker/build/KETI_Preprocessor.py
from pyspark import SparkContext, SparkConf, SparkFiles from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils from msgParser import * import msgParser import json import happybase import sys import os import pika import time from influxdb import InfluxDBClient SPARK_PERIOD_SEC = int(os.environ["SPARK_PERIOD_SEC"]) # 5 ZKQUORUM = os.environ['ZKQUORUM'] #"zk-cs.datacenter.svc.cluster.local:2181" QUEUE_NAME = os.environ["QUEUE_NAME"] QUEUE_TOPIC = os.environ["QUEUE_TOPIC"] RABITMQ = os.environ["RABITMQ"] sensorList_table = "_SensorList" data_table = "_Data" version_table = "_Version" INFLUXDB = os.environ["INFLUXDB_SERVICE"] def saveInfluxDBData(data_dict) : client = InfluxDBClient(INFLUXDB, 8086) try: client.create_database('mydb') except Exception as e: print(e) pass try: client.switch_database('mydb') except Exception as e: print(e) pass data_dict = json.loads(data_dict) CraneFullName = data_dict['CraneFullName'] input_value = [] for key , value in data_dict.items() : dict_put = { 'measurement' : CraneFullName + data_table, 'tags' : { 'SensorName' : key }, 'fields' : { 'Value' : value } } input_value.append(dict_put) client.write_points(input_value) def streaming_set() : sc = SparkContext(appName="PythonStreamingPreprocessing") ssc = StreamingContext(sc, SPARK_PERIOD_SEC) # 1 second window zkQuorum = ZKQUORUM #Dict of (topic_name -> numPartitions) to consume. Each partition is consumed in its own thread. topics = {'http': 1, 'mqtt' : 1, 'coap' : 1} stream = KafkaUtils.createStream(ssc, zkQuorum, "raw-event-streaming-consumer", topics, {"auto.offset.reset": "largest"}) return ssc, stream def msg_parse(data) : data_list = data.split("|") CraneFullName = data_list[0] Time = data_list[1] OBD_DataList = data_list[2:-1] Crane_Data = data_list[-1] getDataFromInfluxDB(INFLUXDB, CraneFullName) OBD_II_data_dict = {} sensor_data_dict = {} if Crane_Data == None: pass else: sensor_data_encoded_hex = Crane_Data sensor_data_dict = sensor_data_parser(sensor_data_encoded_hex) if sensor_data_dict == 'ignore' : error_dict = {} error_dict["FormatError"] = "Crane" error_dict["CraneFullName"] = CraneFullName jsonString = makeJson(error_dict) return jsonString data_dict = make_dict(Time, CraneFullName, OBD_II_data_dict , sensor_data_dict) jsonString = makeJson(data_dict) return jsonString credentials = pika.PlainCredentials('dtuser01', '<PASSWORD>') params = pika.ConnectionParameters(RABITMQ, 5672, '/', credentials) #queue_connection = pika.BlockingConnection(params) #channel = queue_connection.channel() #channel.queue_declare(queue=QUEUE_NAME) def transfer_list(json_list) : global channel global queue_connection for json_data in json_list: check_dict = json.loads(json_data) if not "FormatError" in check_dict: try: channel.basic_publish(exchange='',routing_key=QUEUE_TOPIC, body=json_data) except Exception as e: print("AMQP publish Exception.." +str(e)) print("recreate connection...") print("JsonData : "+str(json_data)) queue_connection = pika.BlockingConnection(params) channel = queue_connection.channel() channel.queue_declare(queue=QUEUE_NAME) channel.basic_publish(exchange='',routing_key=QUEUE_TOPIC, body=json_data) saveInfluxDBData(json_data) else: print("ERROR") def parse_function(rdd) : json_format_rdd = rdd.map(lambda data : msg_parse(data)) json_format_list = json_format_rdd.take(int(json_format_rdd.count())) if len(json_format_list) != 0: transfer_list(json_format_list) def main() : ssc, stream = streaming_set() raw_data = stream.map(lambda value: value[1]) raw_data.foreachRDD(lambda rdd : parse_function(rdd) ) ssc.start() ssc.awaitTermination() if __name__ == "__main__": main() # test_msg = "SHINHAN_Crane_1|2020-11-06 11:09:20|H 135.2000.0-07.6000.0364.9000.001030101999.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9 99.9000.000000000.00000000000000000010000000000" # test_msg = "SHINHAN_Crane_1|3|2019-12-19 10:38:14|+287.724852+20.527328+22.54130544.3022.4277.4003266909840113017505822271-07.89-2.28+1.61+0.00-07.27+0.4001112209N" # jsonString = msg_parse(test_msg) # saveInfluxDBData(jsonString)
0.212477
0.125279
from pymongo import ASCENDING, DESCENDING ENTRIES = 20 def validate(revision, revisions_count): if revision < 0 or revision >= revisions_count: raise ValueError("revision index out of bound! " + str(revision)) return revision class ArticlesParams(object): def __init__(self, from_revision, to_revision): self.from_revision = int(from_revision) if from_revision else None self.to_revision = int(to_revision) if to_revision else None def from_version(self, revisions_count): from_revision = max(0, revisions_count - 2) if self.from_revision is None else self.from_revision return validate(from_revision, revisions_count) def to_version(self, revisions_count): to_revision = max(0, revisions_count - 1) if self.to_revision is None else self.to_revision return validate(to_revision, revisions_count) @classmethod def from_req(cls, req): from_revision = req.params.get('from_revision', None) to_revision = req.params.get('to_revision', None) return cls(from_revision, to_revision) class NewsParams(object): def __init__(self, page, sort_by, order, lang, publisher): self.page = page self.sort_by = sort_by self.order = order self.lang = lang self.publisher = publisher def query(self): query_string = {'$where': 'this.created_at<this.updated_at'} if self.lang != 'all': query_string['lang'] = self.lang if self.publisher: query_string['publisher'] = self.publisher return query_string def skipped_pages(self): return ENTRIES * (self.page - 1) def by_order(self): order = ASCENDING if self.order == 'asc' else DESCENDING sort_by_field = 'comments_no' if self.sort_by == 'popular' \ else 'updated_at' if self.sort_by == 'time' else 'changes' return [(sort_by_field, order)] def get_from(self, db): return db.find(self.query()).sort(self.by_order()).skip(self.skipped_pages()).limit(ENTRIES) def get_meta(self, cursor): count = cursor.count() prefix = ''.join(['/api/publisher/', self.publisher, '/news']) if self.publisher else '/api/news' next_url = ''.join([prefix, '?page=', str(self.page + 1), '&sort_by=', self.sort_by, '&order=', self.order, '&lang=', self.lang]) if count > self.page * ENTRIES else None return {"count": ENTRIES, "total_count": count, "next": next_url} @classmethod def from_req(cls, req, publisher_code): page = int(req.params.get('page', '1')) sort_by = req.params.get('sort_by', 'changes') if sort_by not in ['popular', 'time', 'changes']: raise ValueError() order = req.params.get('order', 'desc') if order not in ['asc', 'desc']: raise ValueError() lang = req.params.get('lang', 'all') return cls(page, sort_by, order, lang, publisher_code) class SearchParams(object): def __init__(self, page, sort_by, order, lang, keyword, publisher=None): self.keyword = keyword self.page = page self.sort_by = sort_by self.order = order self.lang = lang self.publisher = publisher def query(self): query_string = {'$where': 'this.created_at<this.updated_at'} if self.lang != 'all': query_string['lang'] = self.lang if self.publisher: query_string['publisher'] = self.publisher query_string['title'] = {'$regex': '.*'+self.keyword+'.*'} return query_string def skipped_pages(self): return ENTRIES * (self.page - 1) def by_order(self): order = ASCENDING if self.order == 'asc' else DESCENDING sort_by_field = 'comments_no' if self.sort_by == 'popular' \ else 'updated_at' if self.sort_by == 'time' else 'changes' return [(sort_by_field, order)] def get_from(self, db): return db.find(self.query()).sort(self.by_order()).skip(self.skipped_pages()).limit(ENTRIES) def get_meta(self, cursor): count = cursor.count() next_url = ''.join(['/api/search/news?keyword',self.keyword, 'page=', str(self.page + 1), '&sort_by=', self.sort_by, '&order=', self.order, '&lang=', self.lang ]) if count > self.page * ENTRIES else None return {"count": ENTRIES, "total_count": count, "next": next_url} @classmethod def from_req(cls, req): page = int(req.params.get('page', '1')) sort_by = req.params.get('sort_by', 'changes') if sort_by not in ['popular', 'time', 'changes']: raise ValueError() order = req.params.get('order', 'desc') if order not in ['asc', 'desc']: raise ValueError() lang = req.params.get('lang', 'all') keyword = req.params.get('keyword') return cls(page, sort_by, order, lang, keyword)
model/params.py
from pymongo import ASCENDING, DESCENDING ENTRIES = 20 def validate(revision, revisions_count): if revision < 0 or revision >= revisions_count: raise ValueError("revision index out of bound! " + str(revision)) return revision class ArticlesParams(object): def __init__(self, from_revision, to_revision): self.from_revision = int(from_revision) if from_revision else None self.to_revision = int(to_revision) if to_revision else None def from_version(self, revisions_count): from_revision = max(0, revisions_count - 2) if self.from_revision is None else self.from_revision return validate(from_revision, revisions_count) def to_version(self, revisions_count): to_revision = max(0, revisions_count - 1) if self.to_revision is None else self.to_revision return validate(to_revision, revisions_count) @classmethod def from_req(cls, req): from_revision = req.params.get('from_revision', None) to_revision = req.params.get('to_revision', None) return cls(from_revision, to_revision) class NewsParams(object): def __init__(self, page, sort_by, order, lang, publisher): self.page = page self.sort_by = sort_by self.order = order self.lang = lang self.publisher = publisher def query(self): query_string = {'$where': 'this.created_at<this.updated_at'} if self.lang != 'all': query_string['lang'] = self.lang if self.publisher: query_string['publisher'] = self.publisher return query_string def skipped_pages(self): return ENTRIES * (self.page - 1) def by_order(self): order = ASCENDING if self.order == 'asc' else DESCENDING sort_by_field = 'comments_no' if self.sort_by == 'popular' \ else 'updated_at' if self.sort_by == 'time' else 'changes' return [(sort_by_field, order)] def get_from(self, db): return db.find(self.query()).sort(self.by_order()).skip(self.skipped_pages()).limit(ENTRIES) def get_meta(self, cursor): count = cursor.count() prefix = ''.join(['/api/publisher/', self.publisher, '/news']) if self.publisher else '/api/news' next_url = ''.join([prefix, '?page=', str(self.page + 1), '&sort_by=', self.sort_by, '&order=', self.order, '&lang=', self.lang]) if count > self.page * ENTRIES else None return {"count": ENTRIES, "total_count": count, "next": next_url} @classmethod def from_req(cls, req, publisher_code): page = int(req.params.get('page', '1')) sort_by = req.params.get('sort_by', 'changes') if sort_by not in ['popular', 'time', 'changes']: raise ValueError() order = req.params.get('order', 'desc') if order not in ['asc', 'desc']: raise ValueError() lang = req.params.get('lang', 'all') return cls(page, sort_by, order, lang, publisher_code) class SearchParams(object): def __init__(self, page, sort_by, order, lang, keyword, publisher=None): self.keyword = keyword self.page = page self.sort_by = sort_by self.order = order self.lang = lang self.publisher = publisher def query(self): query_string = {'$where': 'this.created_at<this.updated_at'} if self.lang != 'all': query_string['lang'] = self.lang if self.publisher: query_string['publisher'] = self.publisher query_string['title'] = {'$regex': '.*'+self.keyword+'.*'} return query_string def skipped_pages(self): return ENTRIES * (self.page - 1) def by_order(self): order = ASCENDING if self.order == 'asc' else DESCENDING sort_by_field = 'comments_no' if self.sort_by == 'popular' \ else 'updated_at' if self.sort_by == 'time' else 'changes' return [(sort_by_field, order)] def get_from(self, db): return db.find(self.query()).sort(self.by_order()).skip(self.skipped_pages()).limit(ENTRIES) def get_meta(self, cursor): count = cursor.count() next_url = ''.join(['/api/search/news?keyword',self.keyword, 'page=', str(self.page + 1), '&sort_by=', self.sort_by, '&order=', self.order, '&lang=', self.lang ]) if count > self.page * ENTRIES else None return {"count": ENTRIES, "total_count": count, "next": next_url} @classmethod def from_req(cls, req): page = int(req.params.get('page', '1')) sort_by = req.params.get('sort_by', 'changes') if sort_by not in ['popular', 'time', 'changes']: raise ValueError() order = req.params.get('order', 'desc') if order not in ['asc', 'desc']: raise ValueError() lang = req.params.get('lang', 'all') keyword = req.params.get('keyword') return cls(page, sort_by, order, lang, keyword)
0.619356
0.221751
import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from keras.callbacks import Callback class AccHistoryPlot(Callback): def __init__(self, stage_infos, test_data, data_name, result_save_path, validate=0, plot_epoch_gap=30, verbose=1): super(AccHistoryPlot, self).__init__() self.stage, self.fold = stage_infos self.X_test, self.y_test = test_data self.data_name = data_name self.result_save_path = result_save_path self.plot_epoch_gap = plot_epoch_gap self.validate = validate self.verbose = verbose self.close_plt_on_train_end = True fig = plt.figure() self.ax = fig.add_subplot(1, 1, 1) plt.xlabel('Training epochs', fontsize=13) plt.ylabel('Accuracy and loss values', fontsize=13) plt.title('$Acc$ and loss of {} on {}'.format(self.stage, self.data_name), fontsize=15) plt.ion() self.train_accs = [] self.train_loss = [] self.val_accs = [] self.val_loss = [] self.test_accs = [] self.test_loss = [] self.line_train_acc = None self.line_val_acc = None self.line_test_acc = None self.line_train_loss = None self.line_val_loss = None self.line_test_loss = None def plot(self): if self.line_train_acc: self.ax.lines.remove(self.line_train_acc[0]) self.ax.lines.remove(self.line_test_acc[0]) self.ax.lines.remove(self.line_train_loss[0]) self.ax.lines.remove(self.line_test_loss[0]) if self.validate: self.ax.lines.remove(self.line_val_acc[0]) self.ax.lines.remove(self.line_val_acc[0]) self.line_train_acc = self.ax.plot(self.train_accs, lw=1.8, color='deepskyblue', label='Train $Acc$') if self.validate: self.line_val_acc = self.ax.plot(self.val_accs, lw=1.8, color='gold', label='Val $Acc$') self.line_test_acc = self.ax.plot(self.test_accs, lw=1.8, color='limegreen', label = 'Test $Acc$') self.line_train_loss = self.ax.plot(self.train_loss, lw=1.8, color='coral', label='Train Loss') if self.validate: self.line_val_acc = self.ax.plot(self.val_accs, lw=1.8, color='darkred', label='Val Loss') self.line_test_loss = self.ax.plot(self.test_loss, lw=1.8, color='darkorange', label = 'Test Loss') self.ax.legend(loc='center right' if not self.validate else 'best', fontsize=10) plt.pause(0.1) def on_epoch_end(self, epoch, logs=None): test_loss, test_acc = self.model.evaluate(x=self.X_test, y=self.y_test, batch_size=200, verbose=0) if self.verbose: print("Current loss: {}, acc: {}".format(test_loss, test_acc)) self.test_accs.append(test_acc) self.train_accs.append(logs.get('acc')) self.test_loss.append(test_loss) self.train_loss.append(logs.get('loss')) if self.validate: self.val_accs.append(logs.get('val_acc')) self.val_loss.append(logs.get('val_loss')) if epoch % self.plot_epoch_gap == 0: self.plot() def on_train_end(self, logs=None): self.plot() if self.fold!=None: plot_file_name = 'fold {} of {} stage.pdf'.format(self.fold, self.stage) else: plot_file_name = '{} stage.pdf'.format(self.stage) plt.savefig(self.result_save_path + plot_file_name) if self.close_plt_on_train_end: plt.close()
sample/utils/acc_history_plot.py
import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from keras.callbacks import Callback class AccHistoryPlot(Callback): def __init__(self, stage_infos, test_data, data_name, result_save_path, validate=0, plot_epoch_gap=30, verbose=1): super(AccHistoryPlot, self).__init__() self.stage, self.fold = stage_infos self.X_test, self.y_test = test_data self.data_name = data_name self.result_save_path = result_save_path self.plot_epoch_gap = plot_epoch_gap self.validate = validate self.verbose = verbose self.close_plt_on_train_end = True fig = plt.figure() self.ax = fig.add_subplot(1, 1, 1) plt.xlabel('Training epochs', fontsize=13) plt.ylabel('Accuracy and loss values', fontsize=13) plt.title('$Acc$ and loss of {} on {}'.format(self.stage, self.data_name), fontsize=15) plt.ion() self.train_accs = [] self.train_loss = [] self.val_accs = [] self.val_loss = [] self.test_accs = [] self.test_loss = [] self.line_train_acc = None self.line_val_acc = None self.line_test_acc = None self.line_train_loss = None self.line_val_loss = None self.line_test_loss = None def plot(self): if self.line_train_acc: self.ax.lines.remove(self.line_train_acc[0]) self.ax.lines.remove(self.line_test_acc[0]) self.ax.lines.remove(self.line_train_loss[0]) self.ax.lines.remove(self.line_test_loss[0]) if self.validate: self.ax.lines.remove(self.line_val_acc[0]) self.ax.lines.remove(self.line_val_acc[0]) self.line_train_acc = self.ax.plot(self.train_accs, lw=1.8, color='deepskyblue', label='Train $Acc$') if self.validate: self.line_val_acc = self.ax.plot(self.val_accs, lw=1.8, color='gold', label='Val $Acc$') self.line_test_acc = self.ax.plot(self.test_accs, lw=1.8, color='limegreen', label = 'Test $Acc$') self.line_train_loss = self.ax.plot(self.train_loss, lw=1.8, color='coral', label='Train Loss') if self.validate: self.line_val_acc = self.ax.plot(self.val_accs, lw=1.8, color='darkred', label='Val Loss') self.line_test_loss = self.ax.plot(self.test_loss, lw=1.8, color='darkorange', label = 'Test Loss') self.ax.legend(loc='center right' if not self.validate else 'best', fontsize=10) plt.pause(0.1) def on_epoch_end(self, epoch, logs=None): test_loss, test_acc = self.model.evaluate(x=self.X_test, y=self.y_test, batch_size=200, verbose=0) if self.verbose: print("Current loss: {}, acc: {}".format(test_loss, test_acc)) self.test_accs.append(test_acc) self.train_accs.append(logs.get('acc')) self.test_loss.append(test_loss) self.train_loss.append(logs.get('loss')) if self.validate: self.val_accs.append(logs.get('val_acc')) self.val_loss.append(logs.get('val_loss')) if epoch % self.plot_epoch_gap == 0: self.plot() def on_train_end(self, logs=None): self.plot() if self.fold!=None: plot_file_name = 'fold {} of {} stage.pdf'.format(self.fold, self.stage) else: plot_file_name = '{} stage.pdf'.format(self.stage) plt.savefig(self.result_save_path + plot_file_name) if self.close_plt_on_train_end: plt.close()
0.614163
0.405684
# Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest from mock import ANY from ansible.module_utils.network.fortios.fortios import FortiOSHandler try: from ansible.modules.network.fortios import fortios_vpn_ssl_settings except ImportError: pytest.skip("Could not load required modules for testing", allow_module_level=True) @pytest.fixture(autouse=True) def connection_mock(mocker): connection_class_mock = mocker.patch('ansible.modules.network.fortios.fortios_vpn_ssl_settings.Connection') return connection_class_mock fos_instance = FortiOSHandler(connection_mock) def test_vpn_ssl_settings_creation(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'vpn_ssl_settings': { 'auth_timeout': '3', 'auto_tunnel_static_route': 'enable', 'banned_cipher': 'RSA', 'check_referer': 'enable', 'default_portal': 'test_value_7', 'deflate_compression_level': '8', 'deflate_min_data_size': '9', 'dns_server1': 'test_value_10', 'dns_server2': 'test_value_11', 'dns_suffix': 'test_value_12', 'dtls_hello_timeout': '13', 'dtls_tunnel': 'enable', 'force_two_factor_auth': 'enable', 'header_x_forwarded_for': 'pass', 'http_compression': 'enable', 'http_only_cookie': 'enable', 'http_request_body_timeout': '19', 'http_request_header_timeout': '20', 'https_redirect': 'enable', 'idle_timeout': '22', 'ipv6_dns_server1': 'test_value_23', 'ipv6_dns_server2': 'test_value_24', 'ipv6_wins_server1': 'test_value_25', 'ipv6_wins_server2': 'test_value_26', 'login_attempt_limit': '27', 'login_block_time': '28', 'login_timeout': '29', 'port': '30', 'port_precedence': 'enable', 'reqclientcert': 'enable', 'route_source_interface': 'enable', 'servercert': 'test_value_34', 'source_address_negate': 'enable', 'source_address6_negate': 'enable', 'ssl_client_renegotiation': 'disable', 'ssl_insert_empty_fragment': 'enable', 'tlsv1_0': 'enable', 'tlsv1_1': 'enable', 'tlsv1_2': 'enable', 'unsafe_legacy_renegotiation': 'enable', 'url_obscuration': 'enable', 'wins_server1': 'test_value_44', 'wins_server2': 'test_value_45', 'x_content_type_options': 'enable' }, 'vdom': 'root'} is_error, changed, response = fortios_vpn_ssl_settings.fortios_vpn_ssl(input_data, fos_instance) expected_data = { 'auth-timeout': '3', 'auto-tunnel-static-route': 'enable', 'banned-cipher': 'RSA', 'check-referer': 'enable', 'default-portal': 'test_value_7', 'deflate-compression-level': '8', 'deflate-min-data-size': '9', 'dns-server1': 'test_value_10', 'dns-server2': 'test_value_11', 'dns-suffix': 'test_value_12', 'dtls-hello-timeout': '13', 'dtls-tunnel': 'enable', 'force-two-factor-auth': 'enable', 'header-x-forwarded-for': 'pass', 'http-compression': 'enable', 'http-only-cookie': 'enable', 'http-request-body-timeout': '19', 'http-request-header-timeout': '20', 'https-redirect': 'enable', 'idle-timeout': '22', 'ipv6-dns-server1': 'test_value_23', 'ipv6-dns-server2': 'test_value_24', 'ipv6-wins-server1': 'test_value_25', 'ipv6-wins-server2': 'test_value_26', 'login-attempt-limit': '27', 'login-block-time': '28', 'login-timeout': '29', 'port': '30', 'port-precedence': 'enable', 'reqclientcert': 'enable', 'route-source-interface': 'enable', 'servercert': 'test_value_34', 'source-address-negate': 'enable', 'source-address6-negate': 'enable', 'ssl-client-renegotiation': 'disable', 'ssl-insert-empty-fragment': 'enable', 'tlsv1-0': 'enable', 'tlsv1-1': 'enable', 'tlsv1-2': 'enable', 'unsafe-legacy-renegotiation': 'enable', 'url-obscuration': 'enable', 'wins-server1': 'test_value_44', 'wins-server2': 'test_value_45', 'x-content-type-options': 'enable' } set_method_mock.assert_called_with('vpn.ssl', 'settings', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200 def test_vpn_ssl_settings_creation_fails(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'POST', 'http_status': 500} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'vpn_ssl_settings': { 'auth_timeout': '3', 'auto_tunnel_static_route': 'enable', 'banned_cipher': 'RSA', 'check_referer': 'enable', 'default_portal': 'test_value_7', 'deflate_compression_level': '8', 'deflate_min_data_size': '9', 'dns_server1': 'test_value_10', 'dns_server2': 'test_value_11', 'dns_suffix': 'test_value_12', 'dtls_hello_timeout': '13', 'dtls_tunnel': 'enable', 'force_two_factor_auth': 'enable', 'header_x_forwarded_for': 'pass', 'http_compression': 'enable', 'http_only_cookie': 'enable', 'http_request_body_timeout': '19', 'http_request_header_timeout': '20', 'https_redirect': 'enable', 'idle_timeout': '22', 'ipv6_dns_server1': 'test_value_23', 'ipv6_dns_server2': 'test_value_24', 'ipv6_wins_server1': 'test_value_25', 'ipv6_wins_server2': 'test_value_26', 'login_attempt_limit': '27', 'login_block_time': '28', 'login_timeout': '29', 'port': '30', 'port_precedence': 'enable', 'reqclientcert': 'enable', 'route_source_interface': 'enable', 'servercert': 'test_value_34', 'source_address_negate': 'enable', 'source_address6_negate': 'enable', 'ssl_client_renegotiation': 'disable', 'ssl_insert_empty_fragment': 'enable', 'tlsv1_0': 'enable', 'tlsv1_1': 'enable', 'tlsv1_2': 'enable', 'unsafe_legacy_renegotiation': 'enable', 'url_obscuration': 'enable', 'wins_server1': 'test_value_44', 'wins_server2': 'test_value_45', 'x_content_type_options': 'enable' }, 'vdom': 'root'} is_error, changed, response = fortios_vpn_ssl_settings.fortios_vpn_ssl(input_data, fos_instance) expected_data = { 'auth-timeout': '3', 'auto-tunnel-static-route': 'enable', 'banned-cipher': 'RSA', 'check-referer': 'enable', 'default-portal': 'test_value_7', 'deflate-compression-level': '8', 'deflate-min-data-size': '9', 'dns-server1': 'test_value_10', 'dns-server2': 'test_value_11', 'dns-suffix': 'test_value_12', 'dtls-hello-timeout': '13', 'dtls-tunnel': 'enable', 'force-two-factor-auth': 'enable', 'header-x-forwarded-for': 'pass', 'http-compression': 'enable', 'http-only-cookie': 'enable', 'http-request-body-timeout': '19', 'http-request-header-timeout': '20', 'https-redirect': 'enable', 'idle-timeout': '22', 'ipv6-dns-server1': 'test_value_23', 'ipv6-dns-server2': 'test_value_24', 'ipv6-wins-server1': 'test_value_25', 'ipv6-wins-server2': 'test_value_26', 'login-attempt-limit': '27', 'login-block-time': '28', 'login-timeout': '29', 'port': '30', 'port-precedence': 'enable', 'reqclientcert': 'enable', 'route-source-interface': 'enable', 'servercert': 'test_value_34', 'source-address-negate': 'enable', 'source-address6-negate': 'enable', 'ssl-client-renegotiation': 'disable', 'ssl-insert-empty-fragment': 'enable', 'tlsv1-0': 'enable', 'tlsv1-1': 'enable', 'tlsv1-2': 'enable', 'unsafe-legacy-renegotiation': 'enable', 'url-obscuration': 'enable', 'wins-server1': 'test_value_44', 'wins-server2': 'test_value_45', 'x-content-type-options': 'enable' } set_method_mock.assert_called_with('vpn.ssl', 'settings', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 500 def test_vpn_ssl_settings_idempotent(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'DELETE', 'http_status': 404} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'vpn_ssl_settings': { 'auth_timeout': '3', 'auto_tunnel_static_route': 'enable', 'banned_cipher': 'RSA', 'check_referer': 'enable', 'default_portal': 'test_value_7', 'deflate_compression_level': '8', 'deflate_min_data_size': '9', 'dns_server1': 'test_value_10', 'dns_server2': 'test_value_11', 'dns_suffix': 'test_value_12', 'dtls_hello_timeout': '13', 'dtls_tunnel': 'enable', 'force_two_factor_auth': 'enable', 'header_x_forwarded_for': 'pass', 'http_compression': 'enable', 'http_only_cookie': 'enable', 'http_request_body_timeout': '19', 'http_request_header_timeout': '20', 'https_redirect': 'enable', 'idle_timeout': '22', 'ipv6_dns_server1': 'test_value_23', 'ipv6_dns_server2': 'test_value_24', 'ipv6_wins_server1': 'test_value_25', 'ipv6_wins_server2': 'test_value_26', 'login_attempt_limit': '27', 'login_block_time': '28', 'login_timeout': '29', 'port': '30', 'port_precedence': 'enable', 'reqclientcert': 'enable', 'route_source_interface': 'enable', 'servercert': 'test_value_34', 'source_address_negate': 'enable', 'source_address6_negate': 'enable', 'ssl_client_renegotiation': 'disable', 'ssl_insert_empty_fragment': 'enable', 'tlsv1_0': 'enable', 'tlsv1_1': 'enable', 'tlsv1_2': 'enable', 'unsafe_legacy_renegotiation': 'enable', 'url_obscuration': 'enable', 'wins_server1': 'test_value_44', 'wins_server2': 'test_value_45', 'x_content_type_options': 'enable' }, 'vdom': 'root'} is_error, changed, response = fortios_vpn_ssl_settings.fortios_vpn_ssl(input_data, fos_instance) expected_data = { 'auth-timeout': '3', 'auto-tunnel-static-route': 'enable', 'banned-cipher': 'RSA', 'check-referer': 'enable', 'default-portal': 'test_value_7', 'deflate-compression-level': '8', 'deflate-min-data-size': '9', 'dns-server1': 'test_value_10', 'dns-server2': 'test_value_11', 'dns-suffix': 'test_value_12', 'dtls-hello-timeout': '13', 'dtls-tunnel': 'enable', 'force-two-factor-auth': 'enable', 'header-x-forwarded-for': 'pass', 'http-compression': 'enable', 'http-only-cookie': 'enable', 'http-request-body-timeout': '19', 'http-request-header-timeout': '20', 'https-redirect': 'enable', 'idle-timeout': '22', 'ipv6-dns-server1': 'test_value_23', 'ipv6-dns-server2': 'test_value_24', 'ipv6-wins-server1': 'test_value_25', 'ipv6-wins-server2': 'test_value_26', 'login-attempt-limit': '27', 'login-block-time': '28', 'login-timeout': '29', 'port': '30', 'port-precedence': 'enable', 'reqclientcert': 'enable', 'route-source-interface': 'enable', 'servercert': 'test_value_34', 'source-address-negate': 'enable', 'source-address6-negate': 'enable', 'ssl-client-renegotiation': 'disable', 'ssl-insert-empty-fragment': 'enable', 'tlsv1-0': 'enable', 'tlsv1-1': 'enable', 'tlsv1-2': 'enable', 'unsafe-legacy-renegotiation': 'enable', 'url-obscuration': 'enable', 'wins-server1': 'test_value_44', 'wins-server2': 'test_value_45', 'x-content-type-options': 'enable' } set_method_mock.assert_called_with('vpn.ssl', 'settings', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 404 def test_vpn_ssl_settings_filter_foreign_attributes(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'vpn_ssl_settings': { 'random_attribute_not_valid': 'tag', 'auth_timeout': '3', 'auto_tunnel_static_route': 'enable', 'banned_cipher': 'RSA', 'check_referer': 'enable', 'default_portal': 'test_value_7', 'deflate_compression_level': '8', 'deflate_min_data_size': '9', 'dns_server1': 'test_value_10', 'dns_server2': 'test_value_11', 'dns_suffix': 'test_value_12', 'dtls_hello_timeout': '13', 'dtls_tunnel': 'enable', 'force_two_factor_auth': 'enable', 'header_x_forwarded_for': 'pass', 'http_compression': 'enable', 'http_only_cookie': 'enable', 'http_request_body_timeout': '19', 'http_request_header_timeout': '20', 'https_redirect': 'enable', 'idle_timeout': '22', 'ipv6_dns_server1': 'test_value_23', 'ipv6_dns_server2': 'test_value_24', 'ipv6_wins_server1': 'test_value_25', 'ipv6_wins_server2': 'test_value_26', 'login_attempt_limit': '27', 'login_block_time': '28', 'login_timeout': '29', 'port': '30', 'port_precedence': 'enable', 'reqclientcert': 'enable', 'route_source_interface': 'enable', 'servercert': 'test_value_34', 'source_address_negate': 'enable', 'source_address6_negate': 'enable', 'ssl_client_renegotiation': 'disable', 'ssl_insert_empty_fragment': 'enable', 'tlsv1_0': 'enable', 'tlsv1_1': 'enable', 'tlsv1_2': 'enable', 'unsafe_legacy_renegotiation': 'enable', 'url_obscuration': 'enable', 'wins_server1': 'test_value_44', 'wins_server2': 'test_value_45', 'x_content_type_options': 'enable' }, 'vdom': 'root'} is_error, changed, response = fortios_vpn_ssl_settings.fortios_vpn_ssl(input_data, fos_instance) expected_data = { 'auth-timeout': '3', 'auto-tunnel-static-route': 'enable', 'banned-cipher': 'RSA', 'check-referer': 'enable', 'default-portal': 'test_value_7', 'deflate-compression-level': '8', 'deflate-min-data-size': '9', 'dns-server1': 'test_value_10', 'dns-server2': 'test_value_11', 'dns-suffix': 'test_value_12', 'dtls-hello-timeout': '13', 'dtls-tunnel': 'enable', 'force-two-factor-auth': 'enable', 'header-x-forwarded-for': 'pass', 'http-compression': 'enable', 'http-only-cookie': 'enable', 'http-request-body-timeout': '19', 'http-request-header-timeout': '20', 'https-redirect': 'enable', 'idle-timeout': '22', 'ipv6-dns-server1': 'test_value_23', 'ipv6-dns-server2': 'test_value_24', 'ipv6-wins-server1': 'test_value_25', 'ipv6-wins-server2': 'test_value_26', 'login-attempt-limit': '27', 'login-block-time': '28', 'login-timeout': '29', 'port': '30', 'port-precedence': 'enable', 'reqclientcert': 'enable', 'route-source-interface': 'enable', 'servercert': 'test_value_34', 'source-address-negate': 'enable', 'source-address6-negate': 'enable', 'ssl-client-renegotiation': 'disable', 'ssl-insert-empty-fragment': 'enable', 'tlsv1-0': 'enable', 'tlsv1-1': 'enable', 'tlsv1-2': 'enable', 'unsafe-legacy-renegotiation': 'enable', 'url-obscuration': 'enable', 'wins-server1': 'test_value_44', 'wins-server2': 'test_value_45', 'x-content-type-options': 'enable' } set_method_mock.assert_called_with('vpn.ssl', 'settings', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200
v6.0.5/vpn_ssl/test_fortios_vpn_ssl_settings.py
# Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest from mock import ANY from ansible.module_utils.network.fortios.fortios import FortiOSHandler try: from ansible.modules.network.fortios import fortios_vpn_ssl_settings except ImportError: pytest.skip("Could not load required modules for testing", allow_module_level=True) @pytest.fixture(autouse=True) def connection_mock(mocker): connection_class_mock = mocker.patch('ansible.modules.network.fortios.fortios_vpn_ssl_settings.Connection') return connection_class_mock fos_instance = FortiOSHandler(connection_mock) def test_vpn_ssl_settings_creation(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'vpn_ssl_settings': { 'auth_timeout': '3', 'auto_tunnel_static_route': 'enable', 'banned_cipher': 'RSA', 'check_referer': 'enable', 'default_portal': 'test_value_7', 'deflate_compression_level': '8', 'deflate_min_data_size': '9', 'dns_server1': 'test_value_10', 'dns_server2': 'test_value_11', 'dns_suffix': 'test_value_12', 'dtls_hello_timeout': '13', 'dtls_tunnel': 'enable', 'force_two_factor_auth': 'enable', 'header_x_forwarded_for': 'pass', 'http_compression': 'enable', 'http_only_cookie': 'enable', 'http_request_body_timeout': '19', 'http_request_header_timeout': '20', 'https_redirect': 'enable', 'idle_timeout': '22', 'ipv6_dns_server1': 'test_value_23', 'ipv6_dns_server2': 'test_value_24', 'ipv6_wins_server1': 'test_value_25', 'ipv6_wins_server2': 'test_value_26', 'login_attempt_limit': '27', 'login_block_time': '28', 'login_timeout': '29', 'port': '30', 'port_precedence': 'enable', 'reqclientcert': 'enable', 'route_source_interface': 'enable', 'servercert': 'test_value_34', 'source_address_negate': 'enable', 'source_address6_negate': 'enable', 'ssl_client_renegotiation': 'disable', 'ssl_insert_empty_fragment': 'enable', 'tlsv1_0': 'enable', 'tlsv1_1': 'enable', 'tlsv1_2': 'enable', 'unsafe_legacy_renegotiation': 'enable', 'url_obscuration': 'enable', 'wins_server1': 'test_value_44', 'wins_server2': 'test_value_45', 'x_content_type_options': 'enable' }, 'vdom': 'root'} is_error, changed, response = fortios_vpn_ssl_settings.fortios_vpn_ssl(input_data, fos_instance) expected_data = { 'auth-timeout': '3', 'auto-tunnel-static-route': 'enable', 'banned-cipher': 'RSA', 'check-referer': 'enable', 'default-portal': 'test_value_7', 'deflate-compression-level': '8', 'deflate-min-data-size': '9', 'dns-server1': 'test_value_10', 'dns-server2': 'test_value_11', 'dns-suffix': 'test_value_12', 'dtls-hello-timeout': '13', 'dtls-tunnel': 'enable', 'force-two-factor-auth': 'enable', 'header-x-forwarded-for': 'pass', 'http-compression': 'enable', 'http-only-cookie': 'enable', 'http-request-body-timeout': '19', 'http-request-header-timeout': '20', 'https-redirect': 'enable', 'idle-timeout': '22', 'ipv6-dns-server1': 'test_value_23', 'ipv6-dns-server2': 'test_value_24', 'ipv6-wins-server1': 'test_value_25', 'ipv6-wins-server2': 'test_value_26', 'login-attempt-limit': '27', 'login-block-time': '28', 'login-timeout': '29', 'port': '30', 'port-precedence': 'enable', 'reqclientcert': 'enable', 'route-source-interface': 'enable', 'servercert': 'test_value_34', 'source-address-negate': 'enable', 'source-address6-negate': 'enable', 'ssl-client-renegotiation': 'disable', 'ssl-insert-empty-fragment': 'enable', 'tlsv1-0': 'enable', 'tlsv1-1': 'enable', 'tlsv1-2': 'enable', 'unsafe-legacy-renegotiation': 'enable', 'url-obscuration': 'enable', 'wins-server1': 'test_value_44', 'wins-server2': 'test_value_45', 'x-content-type-options': 'enable' } set_method_mock.assert_called_with('vpn.ssl', 'settings', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200 def test_vpn_ssl_settings_creation_fails(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'POST', 'http_status': 500} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'vpn_ssl_settings': { 'auth_timeout': '3', 'auto_tunnel_static_route': 'enable', 'banned_cipher': 'RSA', 'check_referer': 'enable', 'default_portal': 'test_value_7', 'deflate_compression_level': '8', 'deflate_min_data_size': '9', 'dns_server1': 'test_value_10', 'dns_server2': 'test_value_11', 'dns_suffix': 'test_value_12', 'dtls_hello_timeout': '13', 'dtls_tunnel': 'enable', 'force_two_factor_auth': 'enable', 'header_x_forwarded_for': 'pass', 'http_compression': 'enable', 'http_only_cookie': 'enable', 'http_request_body_timeout': '19', 'http_request_header_timeout': '20', 'https_redirect': 'enable', 'idle_timeout': '22', 'ipv6_dns_server1': 'test_value_23', 'ipv6_dns_server2': 'test_value_24', 'ipv6_wins_server1': 'test_value_25', 'ipv6_wins_server2': 'test_value_26', 'login_attempt_limit': '27', 'login_block_time': '28', 'login_timeout': '29', 'port': '30', 'port_precedence': 'enable', 'reqclientcert': 'enable', 'route_source_interface': 'enable', 'servercert': 'test_value_34', 'source_address_negate': 'enable', 'source_address6_negate': 'enable', 'ssl_client_renegotiation': 'disable', 'ssl_insert_empty_fragment': 'enable', 'tlsv1_0': 'enable', 'tlsv1_1': 'enable', 'tlsv1_2': 'enable', 'unsafe_legacy_renegotiation': 'enable', 'url_obscuration': 'enable', 'wins_server1': 'test_value_44', 'wins_server2': 'test_value_45', 'x_content_type_options': 'enable' }, 'vdom': 'root'} is_error, changed, response = fortios_vpn_ssl_settings.fortios_vpn_ssl(input_data, fos_instance) expected_data = { 'auth-timeout': '3', 'auto-tunnel-static-route': 'enable', 'banned-cipher': 'RSA', 'check-referer': 'enable', 'default-portal': 'test_value_7', 'deflate-compression-level': '8', 'deflate-min-data-size': '9', 'dns-server1': 'test_value_10', 'dns-server2': 'test_value_11', 'dns-suffix': 'test_value_12', 'dtls-hello-timeout': '13', 'dtls-tunnel': 'enable', 'force-two-factor-auth': 'enable', 'header-x-forwarded-for': 'pass', 'http-compression': 'enable', 'http-only-cookie': 'enable', 'http-request-body-timeout': '19', 'http-request-header-timeout': '20', 'https-redirect': 'enable', 'idle-timeout': '22', 'ipv6-dns-server1': 'test_value_23', 'ipv6-dns-server2': 'test_value_24', 'ipv6-wins-server1': 'test_value_25', 'ipv6-wins-server2': 'test_value_26', 'login-attempt-limit': '27', 'login-block-time': '28', 'login-timeout': '29', 'port': '30', 'port-precedence': 'enable', 'reqclientcert': 'enable', 'route-source-interface': 'enable', 'servercert': 'test_value_34', 'source-address-negate': 'enable', 'source-address6-negate': 'enable', 'ssl-client-renegotiation': 'disable', 'ssl-insert-empty-fragment': 'enable', 'tlsv1-0': 'enable', 'tlsv1-1': 'enable', 'tlsv1-2': 'enable', 'unsafe-legacy-renegotiation': 'enable', 'url-obscuration': 'enable', 'wins-server1': 'test_value_44', 'wins-server2': 'test_value_45', 'x-content-type-options': 'enable' } set_method_mock.assert_called_with('vpn.ssl', 'settings', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 500 def test_vpn_ssl_settings_idempotent(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'DELETE', 'http_status': 404} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'vpn_ssl_settings': { 'auth_timeout': '3', 'auto_tunnel_static_route': 'enable', 'banned_cipher': 'RSA', 'check_referer': 'enable', 'default_portal': 'test_value_7', 'deflate_compression_level': '8', 'deflate_min_data_size': '9', 'dns_server1': 'test_value_10', 'dns_server2': 'test_value_11', 'dns_suffix': 'test_value_12', 'dtls_hello_timeout': '13', 'dtls_tunnel': 'enable', 'force_two_factor_auth': 'enable', 'header_x_forwarded_for': 'pass', 'http_compression': 'enable', 'http_only_cookie': 'enable', 'http_request_body_timeout': '19', 'http_request_header_timeout': '20', 'https_redirect': 'enable', 'idle_timeout': '22', 'ipv6_dns_server1': 'test_value_23', 'ipv6_dns_server2': 'test_value_24', 'ipv6_wins_server1': 'test_value_25', 'ipv6_wins_server2': 'test_value_26', 'login_attempt_limit': '27', 'login_block_time': '28', 'login_timeout': '29', 'port': '30', 'port_precedence': 'enable', 'reqclientcert': 'enable', 'route_source_interface': 'enable', 'servercert': 'test_value_34', 'source_address_negate': 'enable', 'source_address6_negate': 'enable', 'ssl_client_renegotiation': 'disable', 'ssl_insert_empty_fragment': 'enable', 'tlsv1_0': 'enable', 'tlsv1_1': 'enable', 'tlsv1_2': 'enable', 'unsafe_legacy_renegotiation': 'enable', 'url_obscuration': 'enable', 'wins_server1': 'test_value_44', 'wins_server2': 'test_value_45', 'x_content_type_options': 'enable' }, 'vdom': 'root'} is_error, changed, response = fortios_vpn_ssl_settings.fortios_vpn_ssl(input_data, fos_instance) expected_data = { 'auth-timeout': '3', 'auto-tunnel-static-route': 'enable', 'banned-cipher': 'RSA', 'check-referer': 'enable', 'default-portal': 'test_value_7', 'deflate-compression-level': '8', 'deflate-min-data-size': '9', 'dns-server1': 'test_value_10', 'dns-server2': 'test_value_11', 'dns-suffix': 'test_value_12', 'dtls-hello-timeout': '13', 'dtls-tunnel': 'enable', 'force-two-factor-auth': 'enable', 'header-x-forwarded-for': 'pass', 'http-compression': 'enable', 'http-only-cookie': 'enable', 'http-request-body-timeout': '19', 'http-request-header-timeout': '20', 'https-redirect': 'enable', 'idle-timeout': '22', 'ipv6-dns-server1': 'test_value_23', 'ipv6-dns-server2': 'test_value_24', 'ipv6-wins-server1': 'test_value_25', 'ipv6-wins-server2': 'test_value_26', 'login-attempt-limit': '27', 'login-block-time': '28', 'login-timeout': '29', 'port': '30', 'port-precedence': 'enable', 'reqclientcert': 'enable', 'route-source-interface': 'enable', 'servercert': 'test_value_34', 'source-address-negate': 'enable', 'source-address6-negate': 'enable', 'ssl-client-renegotiation': 'disable', 'ssl-insert-empty-fragment': 'enable', 'tlsv1-0': 'enable', 'tlsv1-1': 'enable', 'tlsv1-2': 'enable', 'unsafe-legacy-renegotiation': 'enable', 'url-obscuration': 'enable', 'wins-server1': 'test_value_44', 'wins-server2': 'test_value_45', 'x-content-type-options': 'enable' } set_method_mock.assert_called_with('vpn.ssl', 'settings', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 404 def test_vpn_ssl_settings_filter_foreign_attributes(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'vpn_ssl_settings': { 'random_attribute_not_valid': 'tag', 'auth_timeout': '3', 'auto_tunnel_static_route': 'enable', 'banned_cipher': 'RSA', 'check_referer': 'enable', 'default_portal': 'test_value_7', 'deflate_compression_level': '8', 'deflate_min_data_size': '9', 'dns_server1': 'test_value_10', 'dns_server2': 'test_value_11', 'dns_suffix': 'test_value_12', 'dtls_hello_timeout': '13', 'dtls_tunnel': 'enable', 'force_two_factor_auth': 'enable', 'header_x_forwarded_for': 'pass', 'http_compression': 'enable', 'http_only_cookie': 'enable', 'http_request_body_timeout': '19', 'http_request_header_timeout': '20', 'https_redirect': 'enable', 'idle_timeout': '22', 'ipv6_dns_server1': 'test_value_23', 'ipv6_dns_server2': 'test_value_24', 'ipv6_wins_server1': 'test_value_25', 'ipv6_wins_server2': 'test_value_26', 'login_attempt_limit': '27', 'login_block_time': '28', 'login_timeout': '29', 'port': '30', 'port_precedence': 'enable', 'reqclientcert': 'enable', 'route_source_interface': 'enable', 'servercert': 'test_value_34', 'source_address_negate': 'enable', 'source_address6_negate': 'enable', 'ssl_client_renegotiation': 'disable', 'ssl_insert_empty_fragment': 'enable', 'tlsv1_0': 'enable', 'tlsv1_1': 'enable', 'tlsv1_2': 'enable', 'unsafe_legacy_renegotiation': 'enable', 'url_obscuration': 'enable', 'wins_server1': 'test_value_44', 'wins_server2': 'test_value_45', 'x_content_type_options': 'enable' }, 'vdom': 'root'} is_error, changed, response = fortios_vpn_ssl_settings.fortios_vpn_ssl(input_data, fos_instance) expected_data = { 'auth-timeout': '3', 'auto-tunnel-static-route': 'enable', 'banned-cipher': 'RSA', 'check-referer': 'enable', 'default-portal': 'test_value_7', 'deflate-compression-level': '8', 'deflate-min-data-size': '9', 'dns-server1': 'test_value_10', 'dns-server2': 'test_value_11', 'dns-suffix': 'test_value_12', 'dtls-hello-timeout': '13', 'dtls-tunnel': 'enable', 'force-two-factor-auth': 'enable', 'header-x-forwarded-for': 'pass', 'http-compression': 'enable', 'http-only-cookie': 'enable', 'http-request-body-timeout': '19', 'http-request-header-timeout': '20', 'https-redirect': 'enable', 'idle-timeout': '22', 'ipv6-dns-server1': 'test_value_23', 'ipv6-dns-server2': 'test_value_24', 'ipv6-wins-server1': 'test_value_25', 'ipv6-wins-server2': 'test_value_26', 'login-attempt-limit': '27', 'login-block-time': '28', 'login-timeout': '29', 'port': '30', 'port-precedence': 'enable', 'reqclientcert': 'enable', 'route-source-interface': 'enable', 'servercert': 'test_value_34', 'source-address-negate': 'enable', 'source-address6-negate': 'enable', 'ssl-client-renegotiation': 'disable', 'ssl-insert-empty-fragment': 'enable', 'tlsv1-0': 'enable', 'tlsv1-1': 'enable', 'tlsv1-2': 'enable', 'unsafe-legacy-renegotiation': 'enable', 'url-obscuration': 'enable', 'wins-server1': 'test_value_44', 'wins-server2': 'test_value_45', 'x-content-type-options': 'enable' } set_method_mock.assert_called_with('vpn.ssl', 'settings', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200
0.562417
0.148664
import os import shutil from bbdata.download.download import VideoDownloader import tensorflow as tf tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.WARN) import tensorflow_io as tfio from utils import ( call_bash, force_update, freeze_cfg, get_data_dir, get_frozen_params, get_params, is_dir, ) SEEN_EVERY = 25 MIN_NUM_TS = 0 class DataGenerator(): def __init__(self, setup=False): params = get_params('Ingestion') if params['switch']: self.params = get_frozen_params( 'Ingestion', version=params['version'], ) else: self.params = params self.dataset_dir = get_data_dir(self.params['dataset']) if self.params['toy_set']: self.data_dir = self.dataset_dir + 'data/toy/' self.logs_dir = self.dataset_dir + 'logs/toy/' self.tfds_dir = self.dataset_dir + 'tfds/toy/' self.records_dir = self.dataset_dir + 'records/toy/' self.vid_dir = ( self.params['vid_dir'] + self.params['dataset'] + '/toy/' ) else: self.data_dir = self.dataset_dir + 'data/full/' self.logs_dir = self.dataset_dir + 'logs/full/' self.tfds_dir = self.dataset_dir + 'tfds/full/' self.records_dir = self.dataset_dir + 'records/full/' self.vid_dir = ( self.params['vid_dir'] + self.params['dataset'] + '/full/' ) self.count = tf.zeros([], dtype=tf.int64) self.train_unusable = tf.cast( self.params['train_unusable'], tf.int64, ) self.validate_unusable = tf.cast( self.params['validate_unusable'], tf.int64, ) tf.debugging.assert_less_equal( self.params['val_clips_per_vid'], self.params['test_clips_per_vid'] , message=( "'val_clips_per_vid' should be less than or equal to " "'test_clips_per_vid'" ) ) tf.debugging.assert_less_equal( self.params['fps'], self.params['download_fps'], message="'fps' should be less than or equal to 'download_fps'" ) self.downloader = VideoDownloader({ 'params':params, 'dataset_dir':self.dataset_dir, }) if setup: self.downloader.get_data() self.downloader.setup() def generate(self): self.generate_datasets() freeze_cfg(version=self.params['version']) if self.params['use_records']: shutil.rmtree(self.dataset_dir + 'tfds/') else: shutil.rmtree( self.dataset_dir + 'records/', ignore_errors=True, ) self.generate_test_dataset() def generate_datasets(self): self._set_labels() self._set_num_cols() i = self.params['loop_it'] for split in ['train', 'validate']: print(f"Generating '{split}' dataset...") wc_file = self.data_dir + split + 'WC.csv' csv_file = self.data_dir + split + '.csv' if not os.path.isfile(wc_file): continue ts_file = self.data_dir + 'timestamps.csv' if self.params['use_records']: is_dir(self.records_dir + split) total = call_bash( command = f"wc -l < {csv_file}", ) total = int(total.decode('utf-8').strip("\n")) - 1 while os.path.isfile(wc_file): self.downloader.get_videos(split) temp_ds = self._csv_to_tfds(ts_file) temp_ds = self._map_dataset(temp_ds) i += 1 force_update({'loop_it':i}) if i == 1: tf.data.experimental.save( temp_ds, self.tfds_dir + f"{split}_{i}", ) if self.params['use_records']: self._create_records(temp_ds, split) else: ds = tf.data.experimental.load( path=self.tfds_dir + f"{split}_{i-1}", element_spec=DataGenerator._get_element_spec( self.num_ts_cols, ), ) ds = ds.concatenate(temp_ds) tf.data.experimental.save( ds, self.tfds_dir + f"{split}_{i}" ) if self.params['use_records']: self._create_records(ds, split) shutil.rmtree(self.tfds_dir + f"{split}_{i-1}") os.remove(ts_file) seen = self.params['download_batch'] * i if seen % SEEN_EVERY == 0 and seen <= total: print(f"{seen}/{total}") if self.params['use_records']: ds = tf.data.experimental.load( path=self.tfds_dir + f"{split}_{i}", element_spec=DataGenerator._get_element_spec( self.num_ts_cols, ), ) self._create_records(ds, split, last_record=True) self._set_split_size(split) if os.path.isdir(self.tfds_dir + f"{split}_{i}"): os.rename( self.tfds_dir + f"{split}_{i}", self.tfds_dir + f"{split}" ) i = 0 force_update({'loop_it':i}) print( f"Dataset saved to: {self.tfds_dir}{split}\n" ) if self.params['use_records']: if self.params['delete_videos']: shutil.rmtree(self.params['vid_dir'] + self.params['dataset']) def generate_test_dataset(self): val_tables = self._load_dataset('validate').enumerate() print("Generating 'test' dataset...") test_tables = self._map_test_dataset(val_tables) tf.data.experimental.save( test_tables, self.tfds_dir + 'test', ) print(f"Dataset saved to: {self.tfds_dir}test\n") def _set_labels(self): labels = tf.TensorArray( tf.string, size=0, dynamic_size=True, ) with open(self.data_dir + 'labels.txt', 'r') as f: for e, l in enumerate(f): labels = labels.write(e, l.rstrip('\n')) force_update({'num_labels':e + 1}) self.labels = labels.stack() def _set_num_cols(self): num_cols = call_bash( command = ( f"awk -F, '{{ print NF; exit }}' {self.data_dir + 'train.csv'}" ) ) self.num_cols = int(num_cols.decode('utf-8').strip("\n")) self.num_ts_cols = ( self.params['download_fps'] * self.params['time_interval'] ) def _set_split_size(self, split): records = self._get_record_names(split) records = sorted( records, key=lambda r: int(r.split(f'{split}_')[1].split('.tf')[0]), ) total_records = len(records) for enum_0, _ in tf.data.TFRecordDataset(records[0]).enumerate(): pass if total_records > 1: for enum_N, _ in tf.data.TFRecordDataset(records[-1]).enumerate(): pass size = ((total_records - 1) * (enum_0 + 1)) + (enum_N + 1) else: size = enum_0 + 1 if split == 'train': size -= self.train_unusable else: size -= self.validate_unusable force_update({f"{split}_size":size.numpy()}) def _csv_to_tfds(self, ts_file): field_dtypes = [tf.string for _ in range(self.num_cols)] ts_dtypes = [tf.int32 for _ in range(self.num_ts_cols)] return tf.data.experimental.CsvDataset( ts_file, field_dtypes + ts_dtypes, exclude_cols=[self.num_cols + self.num_ts_cols], ) def _map_dataset(self, dataset): return dataset.map( self._get_components, num_parallel_calls=tf.data.experimental.AUTOTUNE, deterministic=True, ) def _map_test_dataset(self, dataset): return dataset.map( self._get_test_components, num_parallel_calls=tf.data.experimental.AUTOTUNE, deterministic=True, ) def _get_components(self, *element): path = tf.strings.join([ element[0], '/', element[4], '_', element[1], '.mp4' ]) label = tf.squeeze( tf.cast(tf.where(element[0] == self.labels), tf.int32) ) timestamps = tf.stack(element[self.num_cols:]) identifier = tf.cast(-1, tf.int32) return path, label, timestamps, identifier def _get_test_components(self, enum, elements): return self._get_identifier(enum, elements) def _create_records( self, dataset, split, last_record=False, ): downloaded = call_bash( command = f"wc -l < {self.logs_dir + split + '/downloaded.txt'}" ) downloaded = int(downloaded.decode('utf-8').strip("\n")) record_num = call_bash( command = ( f"ls {self.records_dir + split} " f"| grep '^{split}' " f"| wc -l" ), ) record_num = int(record_num.decode('utf-8').strip("\n")) videos_per_record = self._get_videos_per_record(split) skip = videos_per_record * record_num take = videos_per_record if last_record and downloaded % videos_per_record != 0: threshold = videos_per_record * record_num else: threshold = videos_per_record * (record_num + 1) if downloaded >= threshold: self._write_to_record( dataset.skip(skip).take(take), split, record_num, ) def _write_to_record( self, dataset, split, record_num, ): clips_per_vid = self._get_clips_per_vid(split) dataset = self._generate_element( dataset, clips_per_vid, element='frames' ) paths = [] record = self.records_dir + split + f'/{split}_{record_num}.tfrecord' with tf.io.TFRecordWriter(record) as writer: starting_id = record_num * self._get_videos_per_record(split) for frames, path, label, timestamp, identifier in dataset: paths.append(path.numpy().decode('utf-8')) identifier = identifier + starting_id example = self._serialize_example( frames, label, timestamp, identifier, ) writer.write(example) if timestamp < 0: if split == 'train': self.train_unusable += 1 unusable = self.train_unusable.numpy() elif split == 'validate': self.validate_unusable += 1 unusable = self.validate_unusable.numpy() force_update({ f'{split}_unusable':unusable, }) paths = list(set(paths)) if self.params['delete_videos']: for p in paths: os.remove(self.vid_dir + p) def _serialize_example( self, frames, label, timestamp, identifier, ): feature = { 'frames':DataGenerator._bytes_list_feature(frames), 'label':DataGenerator._int64_feature(label), 'timestamp':DataGenerator._int64_feature(timestamp), 'identifier':DataGenerator._int64_feature(identifier), } example = tf.train.Example( features=tf.train.Features(feature=feature) ) return example.SerializeToString() @staticmethod def _bytes_list_feature(value): value = [v.numpy() for v in value] return tf.train.Feature( bytes_list=tf.train.BytesList(value=value), ) @staticmethod def _int64_feature(value): return tf.train.Feature( int64_list=tf.train.Int64List(value=[value]), ) def _get_videos_per_record(self, split): if split == 'train': videos_per_record = self.params['videos_per_record'] else: videos_per_record = self.params['videos_per_test_record'] return videos_per_record def _get_clips_per_vid(self, split): if split == 'train': clips_per_vid = tf.cast( self.params['train_clips_per_vid'], tf.int64, ) elif split == 'validate': clips_per_vid = tf.cast( tf.math.maximum( self.params['val_clips_per_vid'], self.params['test_clips_per_vid'], ), tf.int64, ) return clips_per_vid def _generate_element( self, dataset, clips_per_vid, element="frames" ): if element == "frames": ds = self._map_frames(dataset) elif element == "timestamp": ds = self._map_timestamps(dataset) self.count += 1 if self.count < clips_per_vid: ds = ds.concatenate( self._generate_element( dataset, clips_per_vid, element=element, ), ) else: ds = ds self.count -= self.count return ds def _map_frames(self, dataset): ds = dataset.enumerate() ds = ds.map( self._get_identifier, num_parallel_calls=tf.data.experimental.AUTOTUNE, deterministic=True, ) ds = self._map_timestamps(ds) ds = ds.map( self._get_video, num_parallel_calls=tf.data.experimental.AUTOTUNE, deterministic=True, ) ds = ds.map( self._get_frames, num_parallel_calls=tf.data.experimental.AUTOTUNE, deterministic=True, ) return ds def _map_timestamps(self, dataset): return dataset.map( self._get_timestamp, num_parallel_calls=tf.data.experimental.AUTOTUNE, deterministic=True, ) def _get_identifier(self, enum, elements): path, label, timestamp, identifier = elements identifier = tf.cast(enum, tf.int32) return path, label, timestamp, identifier def _get_timestamp( self, path, label, timestamps, identifier, ): step = self.params['download_fps'] // self.params['fps'] last_idx = tf.where(timestamps != -1)[-1][0] last_idx = last_idx - ((self.params['frames_per_clip'] * step) - 1) if last_idx < 0: total = -tf.ones([], tf.int64) else: timestamps = timestamps[:last_idx+step:step] tf.debugging.assert_non_negative( timestamps, message="Negative values found.", ) total = tf.shape(timestamps, tf.int64)[0] if total < 0: timestamp = tf.cast(total, tf.int32) else: timestamp = -tf.ones([], tf.int32) if tf.strings.regex_full_match(path, ".*/train_.*"): clips_per_vid = self._get_clips_per_vid('train') if total >= clips_per_vid: idx_range = total // clips_per_vid idx_start = idx_range * self.count indices = tf.range( start=idx_start, limit=idx_start+idx_range, ) else: indices = tf.range( start=0, limit=total, ) timestamp = tf.cast( tf.random.shuffle(indices)[0], tf.int32, ) elif tf.strings.regex_full_match(path, ".*/validate_.*"): clips_per_vid = self._get_clips_per_vid('validate') if total >= clips_per_vid: idx_range = total // clips_per_vid timestamp = tf.cast( idx_range * self.count, tf.int32, ) else: idx_range = total / clips_per_vid timestamp = tf.cast( tf.math.round( idx_range * tf.cast(self.count, tf.float64) ), tf.int32, ) return path, label, timestamp, identifier def _get_video( self, path, label, timestamp, identifier, ): raw = tf.io.read_file(self.vid_dir + path) video = tfio.experimental.ffmpeg.decode_video(raw) return video, path, label, timestamp, identifier def _get_frames( self, video, path, label, timestamp, identifier, ): frames = tf.TensorArray( tf.string, size=self.params['frames_per_clip'], dynamic_size=False, ) for f in tf.range(self.params['frames_per_clip']): if timestamp < 0: frames = frames.write( f, value=tf.io.encode_jpeg( tf.zeros([1,1,1], tf.uint8), ) ) else: frames = frames.write( f, value=tf.io.encode_jpeg( video[timestamp+f,...], format='rgb', ) ) frames = frames.stack() return frames, path, label, timestamp, identifier def load_datasets(self): train_dataset = self._load_dataset('train') train_dataset = self._generate_element( train_dataset, self.params['train_clips_per_vid'], element='timestamp' ) val_dataset = self._load_dataset('validate') val_dataset = self._generate_element( val_dataset, self.params['val_clips_per_vid'], element='timestamp' ) return train_dataset, val_dataset def load_test_dataset(self): test_dataset = self._load_dataset('test') return self._generate_element( test_dataset, self.params['test_clips_per_vid'], element='timestamp' ) def _load_dataset(self, split): num_ts_cols = self.params['download_fps'] * self.params['time_interval'] return tf.data.experimental.load( path=self.tfds_dir + split, element_spec=DataGenerator._get_element_spec(num_ts_cols), ) @staticmethod def _get_element_spec(num_ts_cols): return ( tf.TensorSpec(shape=(), dtype=tf.string), tf.TensorSpec(shape=(), dtype=tf.int32), tf.TensorSpec(shape=(num_ts_cols,), dtype=tf.int32), tf.TensorSpec(shape=(), dtype=tf.int32), ) def load_records(self): train_records = self._load_records('train') val_records = self._load_records('validate') return train_records, val_records def load_test_records(self): return self._load_records('test') def _load_records(self, split): records = self._get_record_names(split) ds = tf.data.Dataset.from_tensor_slices(records) if split == 'validate': ds = ds.interleave( tf.data.TFRecordDataset, cycle_length=self.params['validate_size'], block_length=1, num_parallel_calls=tf.data.experimental.AUTOTUNE, deterministic=True, ) return ds.take(( self.params['validate_size'] // self.params['test_clips_per_vid'] * self.params['val_clips_per_vid'] )) else: ds = ds.shuffle( buffer_size=tf.cast( tf.shape(records)[0], tf.int64, ), ) ds = ds.repeat() return ds.interleave( tf.data.TFRecordDataset, cycle_length=self.params['interleave_num'], block_length=self.params['interleave_block'], num_parallel_calls=tf.data.experimental.AUTOTUNE, deterministic=False, ) def _get_record_names(self, split): if split == 'test': split = 'validate' if self.params['use_cloud']: records = tf.io.gfile.glob(( self.params['gcs_data'].rstrip('/') + '/' + split + f'/{split}_*.tfrecord' )) else: records = tf.io.gfile.glob( self.records_dir + split + f'/{split}*.tfrecord' ) return records
bbaction/ingestion/ingest.py
import os import shutil from bbdata.download.download import VideoDownloader import tensorflow as tf tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.WARN) import tensorflow_io as tfio from utils import ( call_bash, force_update, freeze_cfg, get_data_dir, get_frozen_params, get_params, is_dir, ) SEEN_EVERY = 25 MIN_NUM_TS = 0 class DataGenerator(): def __init__(self, setup=False): params = get_params('Ingestion') if params['switch']: self.params = get_frozen_params( 'Ingestion', version=params['version'], ) else: self.params = params self.dataset_dir = get_data_dir(self.params['dataset']) if self.params['toy_set']: self.data_dir = self.dataset_dir + 'data/toy/' self.logs_dir = self.dataset_dir + 'logs/toy/' self.tfds_dir = self.dataset_dir + 'tfds/toy/' self.records_dir = self.dataset_dir + 'records/toy/' self.vid_dir = ( self.params['vid_dir'] + self.params['dataset'] + '/toy/' ) else: self.data_dir = self.dataset_dir + 'data/full/' self.logs_dir = self.dataset_dir + 'logs/full/' self.tfds_dir = self.dataset_dir + 'tfds/full/' self.records_dir = self.dataset_dir + 'records/full/' self.vid_dir = ( self.params['vid_dir'] + self.params['dataset'] + '/full/' ) self.count = tf.zeros([], dtype=tf.int64) self.train_unusable = tf.cast( self.params['train_unusable'], tf.int64, ) self.validate_unusable = tf.cast( self.params['validate_unusable'], tf.int64, ) tf.debugging.assert_less_equal( self.params['val_clips_per_vid'], self.params['test_clips_per_vid'] , message=( "'val_clips_per_vid' should be less than or equal to " "'test_clips_per_vid'" ) ) tf.debugging.assert_less_equal( self.params['fps'], self.params['download_fps'], message="'fps' should be less than or equal to 'download_fps'" ) self.downloader = VideoDownloader({ 'params':params, 'dataset_dir':self.dataset_dir, }) if setup: self.downloader.get_data() self.downloader.setup() def generate(self): self.generate_datasets() freeze_cfg(version=self.params['version']) if self.params['use_records']: shutil.rmtree(self.dataset_dir + 'tfds/') else: shutil.rmtree( self.dataset_dir + 'records/', ignore_errors=True, ) self.generate_test_dataset() def generate_datasets(self): self._set_labels() self._set_num_cols() i = self.params['loop_it'] for split in ['train', 'validate']: print(f"Generating '{split}' dataset...") wc_file = self.data_dir + split + 'WC.csv' csv_file = self.data_dir + split + '.csv' if not os.path.isfile(wc_file): continue ts_file = self.data_dir + 'timestamps.csv' if self.params['use_records']: is_dir(self.records_dir + split) total = call_bash( command = f"wc -l < {csv_file}", ) total = int(total.decode('utf-8').strip("\n")) - 1 while os.path.isfile(wc_file): self.downloader.get_videos(split) temp_ds = self._csv_to_tfds(ts_file) temp_ds = self._map_dataset(temp_ds) i += 1 force_update({'loop_it':i}) if i == 1: tf.data.experimental.save( temp_ds, self.tfds_dir + f"{split}_{i}", ) if self.params['use_records']: self._create_records(temp_ds, split) else: ds = tf.data.experimental.load( path=self.tfds_dir + f"{split}_{i-1}", element_spec=DataGenerator._get_element_spec( self.num_ts_cols, ), ) ds = ds.concatenate(temp_ds) tf.data.experimental.save( ds, self.tfds_dir + f"{split}_{i}" ) if self.params['use_records']: self._create_records(ds, split) shutil.rmtree(self.tfds_dir + f"{split}_{i-1}") os.remove(ts_file) seen = self.params['download_batch'] * i if seen % SEEN_EVERY == 0 and seen <= total: print(f"{seen}/{total}") if self.params['use_records']: ds = tf.data.experimental.load( path=self.tfds_dir + f"{split}_{i}", element_spec=DataGenerator._get_element_spec( self.num_ts_cols, ), ) self._create_records(ds, split, last_record=True) self._set_split_size(split) if os.path.isdir(self.tfds_dir + f"{split}_{i}"): os.rename( self.tfds_dir + f"{split}_{i}", self.tfds_dir + f"{split}" ) i = 0 force_update({'loop_it':i}) print( f"Dataset saved to: {self.tfds_dir}{split}\n" ) if self.params['use_records']: if self.params['delete_videos']: shutil.rmtree(self.params['vid_dir'] + self.params['dataset']) def generate_test_dataset(self): val_tables = self._load_dataset('validate').enumerate() print("Generating 'test' dataset...") test_tables = self._map_test_dataset(val_tables) tf.data.experimental.save( test_tables, self.tfds_dir + 'test', ) print(f"Dataset saved to: {self.tfds_dir}test\n") def _set_labels(self): labels = tf.TensorArray( tf.string, size=0, dynamic_size=True, ) with open(self.data_dir + 'labels.txt', 'r') as f: for e, l in enumerate(f): labels = labels.write(e, l.rstrip('\n')) force_update({'num_labels':e + 1}) self.labels = labels.stack() def _set_num_cols(self): num_cols = call_bash( command = ( f"awk -F, '{{ print NF; exit }}' {self.data_dir + 'train.csv'}" ) ) self.num_cols = int(num_cols.decode('utf-8').strip("\n")) self.num_ts_cols = ( self.params['download_fps'] * self.params['time_interval'] ) def _set_split_size(self, split): records = self._get_record_names(split) records = sorted( records, key=lambda r: int(r.split(f'{split}_')[1].split('.tf')[0]), ) total_records = len(records) for enum_0, _ in tf.data.TFRecordDataset(records[0]).enumerate(): pass if total_records > 1: for enum_N, _ in tf.data.TFRecordDataset(records[-1]).enumerate(): pass size = ((total_records - 1) * (enum_0 + 1)) + (enum_N + 1) else: size = enum_0 + 1 if split == 'train': size -= self.train_unusable else: size -= self.validate_unusable force_update({f"{split}_size":size.numpy()}) def _csv_to_tfds(self, ts_file): field_dtypes = [tf.string for _ in range(self.num_cols)] ts_dtypes = [tf.int32 for _ in range(self.num_ts_cols)] return tf.data.experimental.CsvDataset( ts_file, field_dtypes + ts_dtypes, exclude_cols=[self.num_cols + self.num_ts_cols], ) def _map_dataset(self, dataset): return dataset.map( self._get_components, num_parallel_calls=tf.data.experimental.AUTOTUNE, deterministic=True, ) def _map_test_dataset(self, dataset): return dataset.map( self._get_test_components, num_parallel_calls=tf.data.experimental.AUTOTUNE, deterministic=True, ) def _get_components(self, *element): path = tf.strings.join([ element[0], '/', element[4], '_', element[1], '.mp4' ]) label = tf.squeeze( tf.cast(tf.where(element[0] == self.labels), tf.int32) ) timestamps = tf.stack(element[self.num_cols:]) identifier = tf.cast(-1, tf.int32) return path, label, timestamps, identifier def _get_test_components(self, enum, elements): return self._get_identifier(enum, elements) def _create_records( self, dataset, split, last_record=False, ): downloaded = call_bash( command = f"wc -l < {self.logs_dir + split + '/downloaded.txt'}" ) downloaded = int(downloaded.decode('utf-8').strip("\n")) record_num = call_bash( command = ( f"ls {self.records_dir + split} " f"| grep '^{split}' " f"| wc -l" ), ) record_num = int(record_num.decode('utf-8').strip("\n")) videos_per_record = self._get_videos_per_record(split) skip = videos_per_record * record_num take = videos_per_record if last_record and downloaded % videos_per_record != 0: threshold = videos_per_record * record_num else: threshold = videos_per_record * (record_num + 1) if downloaded >= threshold: self._write_to_record( dataset.skip(skip).take(take), split, record_num, ) def _write_to_record( self, dataset, split, record_num, ): clips_per_vid = self._get_clips_per_vid(split) dataset = self._generate_element( dataset, clips_per_vid, element='frames' ) paths = [] record = self.records_dir + split + f'/{split}_{record_num}.tfrecord' with tf.io.TFRecordWriter(record) as writer: starting_id = record_num * self._get_videos_per_record(split) for frames, path, label, timestamp, identifier in dataset: paths.append(path.numpy().decode('utf-8')) identifier = identifier + starting_id example = self._serialize_example( frames, label, timestamp, identifier, ) writer.write(example) if timestamp < 0: if split == 'train': self.train_unusable += 1 unusable = self.train_unusable.numpy() elif split == 'validate': self.validate_unusable += 1 unusable = self.validate_unusable.numpy() force_update({ f'{split}_unusable':unusable, }) paths = list(set(paths)) if self.params['delete_videos']: for p in paths: os.remove(self.vid_dir + p) def _serialize_example( self, frames, label, timestamp, identifier, ): feature = { 'frames':DataGenerator._bytes_list_feature(frames), 'label':DataGenerator._int64_feature(label), 'timestamp':DataGenerator._int64_feature(timestamp), 'identifier':DataGenerator._int64_feature(identifier), } example = tf.train.Example( features=tf.train.Features(feature=feature) ) return example.SerializeToString() @staticmethod def _bytes_list_feature(value): value = [v.numpy() for v in value] return tf.train.Feature( bytes_list=tf.train.BytesList(value=value), ) @staticmethod def _int64_feature(value): return tf.train.Feature( int64_list=tf.train.Int64List(value=[value]), ) def _get_videos_per_record(self, split): if split == 'train': videos_per_record = self.params['videos_per_record'] else: videos_per_record = self.params['videos_per_test_record'] return videos_per_record def _get_clips_per_vid(self, split): if split == 'train': clips_per_vid = tf.cast( self.params['train_clips_per_vid'], tf.int64, ) elif split == 'validate': clips_per_vid = tf.cast( tf.math.maximum( self.params['val_clips_per_vid'], self.params['test_clips_per_vid'], ), tf.int64, ) return clips_per_vid def _generate_element( self, dataset, clips_per_vid, element="frames" ): if element == "frames": ds = self._map_frames(dataset) elif element == "timestamp": ds = self._map_timestamps(dataset) self.count += 1 if self.count < clips_per_vid: ds = ds.concatenate( self._generate_element( dataset, clips_per_vid, element=element, ), ) else: ds = ds self.count -= self.count return ds def _map_frames(self, dataset): ds = dataset.enumerate() ds = ds.map( self._get_identifier, num_parallel_calls=tf.data.experimental.AUTOTUNE, deterministic=True, ) ds = self._map_timestamps(ds) ds = ds.map( self._get_video, num_parallel_calls=tf.data.experimental.AUTOTUNE, deterministic=True, ) ds = ds.map( self._get_frames, num_parallel_calls=tf.data.experimental.AUTOTUNE, deterministic=True, ) return ds def _map_timestamps(self, dataset): return dataset.map( self._get_timestamp, num_parallel_calls=tf.data.experimental.AUTOTUNE, deterministic=True, ) def _get_identifier(self, enum, elements): path, label, timestamp, identifier = elements identifier = tf.cast(enum, tf.int32) return path, label, timestamp, identifier def _get_timestamp( self, path, label, timestamps, identifier, ): step = self.params['download_fps'] // self.params['fps'] last_idx = tf.where(timestamps != -1)[-1][0] last_idx = last_idx - ((self.params['frames_per_clip'] * step) - 1) if last_idx < 0: total = -tf.ones([], tf.int64) else: timestamps = timestamps[:last_idx+step:step] tf.debugging.assert_non_negative( timestamps, message="Negative values found.", ) total = tf.shape(timestamps, tf.int64)[0] if total < 0: timestamp = tf.cast(total, tf.int32) else: timestamp = -tf.ones([], tf.int32) if tf.strings.regex_full_match(path, ".*/train_.*"): clips_per_vid = self._get_clips_per_vid('train') if total >= clips_per_vid: idx_range = total // clips_per_vid idx_start = idx_range * self.count indices = tf.range( start=idx_start, limit=idx_start+idx_range, ) else: indices = tf.range( start=0, limit=total, ) timestamp = tf.cast( tf.random.shuffle(indices)[0], tf.int32, ) elif tf.strings.regex_full_match(path, ".*/validate_.*"): clips_per_vid = self._get_clips_per_vid('validate') if total >= clips_per_vid: idx_range = total // clips_per_vid timestamp = tf.cast( idx_range * self.count, tf.int32, ) else: idx_range = total / clips_per_vid timestamp = tf.cast( tf.math.round( idx_range * tf.cast(self.count, tf.float64) ), tf.int32, ) return path, label, timestamp, identifier def _get_video( self, path, label, timestamp, identifier, ): raw = tf.io.read_file(self.vid_dir + path) video = tfio.experimental.ffmpeg.decode_video(raw) return video, path, label, timestamp, identifier def _get_frames( self, video, path, label, timestamp, identifier, ): frames = tf.TensorArray( tf.string, size=self.params['frames_per_clip'], dynamic_size=False, ) for f in tf.range(self.params['frames_per_clip']): if timestamp < 0: frames = frames.write( f, value=tf.io.encode_jpeg( tf.zeros([1,1,1], tf.uint8), ) ) else: frames = frames.write( f, value=tf.io.encode_jpeg( video[timestamp+f,...], format='rgb', ) ) frames = frames.stack() return frames, path, label, timestamp, identifier def load_datasets(self): train_dataset = self._load_dataset('train') train_dataset = self._generate_element( train_dataset, self.params['train_clips_per_vid'], element='timestamp' ) val_dataset = self._load_dataset('validate') val_dataset = self._generate_element( val_dataset, self.params['val_clips_per_vid'], element='timestamp' ) return train_dataset, val_dataset def load_test_dataset(self): test_dataset = self._load_dataset('test') return self._generate_element( test_dataset, self.params['test_clips_per_vid'], element='timestamp' ) def _load_dataset(self, split): num_ts_cols = self.params['download_fps'] * self.params['time_interval'] return tf.data.experimental.load( path=self.tfds_dir + split, element_spec=DataGenerator._get_element_spec(num_ts_cols), ) @staticmethod def _get_element_spec(num_ts_cols): return ( tf.TensorSpec(shape=(), dtype=tf.string), tf.TensorSpec(shape=(), dtype=tf.int32), tf.TensorSpec(shape=(num_ts_cols,), dtype=tf.int32), tf.TensorSpec(shape=(), dtype=tf.int32), ) def load_records(self): train_records = self._load_records('train') val_records = self._load_records('validate') return train_records, val_records def load_test_records(self): return self._load_records('test') def _load_records(self, split): records = self._get_record_names(split) ds = tf.data.Dataset.from_tensor_slices(records) if split == 'validate': ds = ds.interleave( tf.data.TFRecordDataset, cycle_length=self.params['validate_size'], block_length=1, num_parallel_calls=tf.data.experimental.AUTOTUNE, deterministic=True, ) return ds.take(( self.params['validate_size'] // self.params['test_clips_per_vid'] * self.params['val_clips_per_vid'] )) else: ds = ds.shuffle( buffer_size=tf.cast( tf.shape(records)[0], tf.int64, ), ) ds = ds.repeat() return ds.interleave( tf.data.TFRecordDataset, cycle_length=self.params['interleave_num'], block_length=self.params['interleave_block'], num_parallel_calls=tf.data.experimental.AUTOTUNE, deterministic=False, ) def _get_record_names(self, split): if split == 'test': split = 'validate' if self.params['use_cloud']: records = tf.io.gfile.glob(( self.params['gcs_data'].rstrip('/') + '/' + split + f'/{split}_*.tfrecord' )) else: records = tf.io.gfile.glob( self.records_dir + split + f'/{split}*.tfrecord' ) return records
0.304765
0.16807
import copy import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.distributions as dist from core.models.common_layers import get_nddr from core.utils import AttrDict from core.tasks import get_tasks from core.utils.losses import poly, entropy_loss, l1_loss class GeneralizedMTLNASNet(nn.Module): def __init__(self, cfg, net1, net2, net1_connectivity_matrix, net2_connectivity_matrix ): """ :param net1: task one network :param net2: task two network :param net1_connectivity_matrix: Adjacency list for the Single sided NDDR connections :param net2_connectivity_matrix: Adjacency list for the Single sided NDDR connections """ super(GeneralizedMTLNASNet, self).__init__() self.cfg = cfg self.net1 = net1 self.net2 = net2 assert len(net1.stages) == len(net2.stages) print("Model has %d stages" % len(net1.stages)) self.task1, self.task2 = get_tasks(cfg) self.num_stages = len(net1.stages) self.net1_connectivity_matrix = net1_connectivity_matrix self.net2_connectivity_matrix = net2_connectivity_matrix net1_in_degrees = net1_connectivity_matrix.sum(axis=1) net2_in_degrees = net2_connectivity_matrix.sum(axis=1) net1_fusion_ops = [] # used for incoming feature fusion net2_fusion_ops = [] # used for incoming feature fusion for stage_id in range(self.num_stages): n_channel = net1.stages[stage_id].out_channels net1_op = get_nddr(cfg, (net1_in_degrees[stage_id]+1)*n_channel, # +1 for original upstream input n_channel) net2_op = get_nddr(cfg, (net2_in_degrees[stage_id]+1)*n_channel, # +1 for original upstream input n_channel) net1_fusion_ops.append(net1_op) net2_fusion_ops.append(net2_op) net1_fusion_ops = nn.ModuleList(net1_fusion_ops) net2_fusion_ops = nn.ModuleList(net2_fusion_ops) self.net1_alphas = nn.Parameter(torch.zeros(net1_connectivity_matrix.shape)) self.net2_alphas = nn.Parameter(torch.zeros(net2_connectivity_matrix.shape)) self.paths = nn.ModuleDict({ 'net1_paths': net1_fusion_ops, 'net2_paths': net2_fusion_ops, }) path_cost = np.array([stage.out_channels for stage in net1.stages]) path_cost = path_cost[:, None] * net1_connectivity_matrix path_cost = path_cost * net1_connectivity_matrix.sum() / path_cost.sum() path_cost = path_cost[np.nonzero(path_cost)] self.register_buffer("path_costs", torch.tensor(path_cost).float()) self._step = 0 self._arch_parameters = dict() self._net_parameters = dict() for k, v in self.named_parameters(): if 'alpha' in k: self._arch_parameters[k] = v else: self._net_parameters[k] = v self.hard_weight_training = cfg.ARCH.HARD_WEIGHT_TRAINING self.hard_arch_training = cfg.ARCH.HARD_ARCH_TRAINING self.hard_evaluation = cfg.ARCH.HARD_EVAL self.stochastic_evaluation = cfg.ARCH.STOCHASTIC_EVAL self.arch_training = False self.retraining = False self.supernet = False if cfg.MODEL.SUPERNET: print("Running Supernet Baseline") self.supernet = True def loss(self, image, labels): label_1, label_2 = labels result = self.forward(image) result.loss1 = self.task1.loss(result.out1, label_1) result.loss2 = self.task2.loss(result.out2, label_2) result.loss = result.loss1 + self.cfg.TRAIN.TASK2_FACTOR * result.loss2 if self.arch_training: arch_parameters = [ self.net1_alphas[np.nonzero(self.net1_connectivity_matrix)], self.net2_alphas[np.nonzero(self.net2_connectivity_matrix)], ] if self.cfg.ARCH.ENTROPY_REGULARIZATION: result.entropy_loss = entropy_loss(arch_parameters) result.entropy_weight = poly(start=0., end=self.cfg.ARCH.ENTROPY_REGULARIZATION_WEIGHT, steps=self._step, total_steps=self.cfg.TRAIN.STEPS, period=self.cfg.ARCH.ENTROPY_PERIOD, power=1.) result.loss += result.entropy_weight * result.entropy_loss if self.cfg.ARCH.L1_REGULARIZATION: if self.cfg.ARCH.WEIGHTED_L1: result.l1_loss = l1_loss(arch_parameters, self.path_costs) else: result.l1_loss = l1_loss(arch_parameters) result.l1_weight = poly(start=0., end=self.cfg.ARCH.L1_REGULARIZATION_WEIGHT, steps=self._step, total_steps=self.cfg.TRAIN.STEPS, period=self.cfg.ARCH.L1_PERIOD, power=1.) if float(self._step) / self.cfg.TRAIN.STEPS > self.cfg.ARCH.L1_PERIOD[1] and self.cfg.ARCH.L1_OFF: result.l1_weight = 0. result.loss += result.l1_weight * result.l1_loss return result def new(self): return copy.deepcopy(self) def step(self): # update temperature self._step += 1 def get_temperature(self): return poly(start=self.cfg.ARCH.INIT_TEMP, end=0., steps=self._step, total_steps=self.cfg.TRAIN.STEPS, period=self.cfg.ARCH.TEMPERATURE_PERIOD, power=self.cfg.ARCH.TEMPERATURE_POWER) def arch_parameters(self): return self._arch_parameters.values() def named_arch_parameters(self): return self._arch_parameters.items() def net_parameters(self): return self._net_parameters.values() def named_net_parameters(self): return self._net_parameters.items() def arch_train(self): self.arch_training = True def arch_eval(self): self.arch_training = False def retrain(self): self.retraining = True def gumbel_connectivity(self, path_weights): temp = self.get_temperature() net_dist = dist.relaxed_bernoulli.RelaxedBernoulli(temp, logits=path_weights) path_connectivity = net_dist.rsample() return path_connectivity def bernoulli_connectivity(self, path_weights): net_dist = dist.bernoulli.Bernoulli(logits=path_weights) path_connectivity = net_dist.sample() return path_connectivity def sigmoid_connectivity(self, path_weights): return torch.sigmoid(path_weights) def onehot_connectivity(self, path_weights): path_connectivity = (path_weights > 0.).float() return path_connectivity def all_connectivity(self, path_weights): return torch.ones_like(path_weights) def forward(self, x): N, C, H, W = x.size() y = x.clone() x = self.net1.base(x) y = self.net2.base(y) xs, ys = [], [] for stage_id in range(self.num_stages): x = self.net1.stages[stage_id](x) y = self.net2.stages[stage_id](y) if isinstance(x, list): xs.append(x[0]) ys.append(y[0]) else: xs.append(x) ys.append(y) net1_path_ids = np.nonzero(self.net1_connectivity_matrix[stage_id])[0] net2_path_ids = np.nonzero(self.net2_connectivity_matrix[stage_id])[0] net1_path_weights = self.net1_alphas[stage_id][net1_path_ids] net2_path_weights = self.net2_alphas[stage_id][net2_path_ids] # Calculating path strength based on weights if self.training: if self.supernet: connectivity = 'all' elif self.retraining: connectivity = 'onehot' else: if self.arch_training: # Training architecture if self.hard_arch_training: connectivity = 'gumbel' else: connectivity = 'sigmoid' else: # Training weights if self.hard_weight_training: connectivity = 'gumbel' else: connectivity = 'sigmoid' else: if self.supernet: connectivity = 'all' elif self.retraining: connectivity = 'onehot' elif self.stochastic_evaluation: assert not self.hard_evaluation connectivity = 'bernoulli' elif self.hard_evaluation: connectivity = 'onehot' else: connectivity = 'sigmoid' if connectivity == 'gumbel': net1_path_connectivity = self.gumbel_connectivity(net1_path_weights) net2_path_connectivity = self.gumbel_connectivity(net2_path_weights) elif connectivity == 'sigmoid': net1_path_connectivity = self.sigmoid_connectivity(net1_path_weights) net2_path_connectivity = self.sigmoid_connectivity(net2_path_weights) elif connectivity == 'all': net1_path_connectivity = self.all_connectivity(net1_path_weights) net2_path_connectivity = self.all_connectivity(net2_path_weights) elif connectivity == 'bernoulli': net1_path_connectivity = self.bernoulli_connectivity(net1_path_weights) net2_path_connectivity = self.bernoulli_connectivity(net2_path_weights) else: assert connectivity == 'onehot' net1_path_connectivity = self.onehot_connectivity(net1_path_weights) net2_path_connectivity = self.onehot_connectivity(net2_path_weights) if isinstance(x, list): net1_fusion_input = [x[0]] net2_fusion_input = [y[0]] else: net1_fusion_input = [x] net2_fusion_input = [y] for idx, input_id in enumerate(net1_path_ids): net1_fusion_input.append(net1_path_connectivity[idx]*ys[input_id]) for idx, input_id in enumerate(net2_path_ids): net2_fusion_input.append(net2_path_connectivity[idx]*xs[input_id]) if isinstance(x, list): x[0] = self.paths['net1_paths'][stage_id](net1_fusion_input) y[0] = self.paths['net2_paths'][stage_id](net2_fusion_input) else: x = self.paths['net1_paths'][stage_id](net1_fusion_input) y = self.paths['net2_paths'][stage_id](net2_fusion_input) x = self.net1.head(x) y = self.net2.head(y) return AttrDict({'out1': x, 'out2': y})
core/models/supernet.py
import copy import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.distributions as dist from core.models.common_layers import get_nddr from core.utils import AttrDict from core.tasks import get_tasks from core.utils.losses import poly, entropy_loss, l1_loss class GeneralizedMTLNASNet(nn.Module): def __init__(self, cfg, net1, net2, net1_connectivity_matrix, net2_connectivity_matrix ): """ :param net1: task one network :param net2: task two network :param net1_connectivity_matrix: Adjacency list for the Single sided NDDR connections :param net2_connectivity_matrix: Adjacency list for the Single sided NDDR connections """ super(GeneralizedMTLNASNet, self).__init__() self.cfg = cfg self.net1 = net1 self.net2 = net2 assert len(net1.stages) == len(net2.stages) print("Model has %d stages" % len(net1.stages)) self.task1, self.task2 = get_tasks(cfg) self.num_stages = len(net1.stages) self.net1_connectivity_matrix = net1_connectivity_matrix self.net2_connectivity_matrix = net2_connectivity_matrix net1_in_degrees = net1_connectivity_matrix.sum(axis=1) net2_in_degrees = net2_connectivity_matrix.sum(axis=1) net1_fusion_ops = [] # used for incoming feature fusion net2_fusion_ops = [] # used for incoming feature fusion for stage_id in range(self.num_stages): n_channel = net1.stages[stage_id].out_channels net1_op = get_nddr(cfg, (net1_in_degrees[stage_id]+1)*n_channel, # +1 for original upstream input n_channel) net2_op = get_nddr(cfg, (net2_in_degrees[stage_id]+1)*n_channel, # +1 for original upstream input n_channel) net1_fusion_ops.append(net1_op) net2_fusion_ops.append(net2_op) net1_fusion_ops = nn.ModuleList(net1_fusion_ops) net2_fusion_ops = nn.ModuleList(net2_fusion_ops) self.net1_alphas = nn.Parameter(torch.zeros(net1_connectivity_matrix.shape)) self.net2_alphas = nn.Parameter(torch.zeros(net2_connectivity_matrix.shape)) self.paths = nn.ModuleDict({ 'net1_paths': net1_fusion_ops, 'net2_paths': net2_fusion_ops, }) path_cost = np.array([stage.out_channels for stage in net1.stages]) path_cost = path_cost[:, None] * net1_connectivity_matrix path_cost = path_cost * net1_connectivity_matrix.sum() / path_cost.sum() path_cost = path_cost[np.nonzero(path_cost)] self.register_buffer("path_costs", torch.tensor(path_cost).float()) self._step = 0 self._arch_parameters = dict() self._net_parameters = dict() for k, v in self.named_parameters(): if 'alpha' in k: self._arch_parameters[k] = v else: self._net_parameters[k] = v self.hard_weight_training = cfg.ARCH.HARD_WEIGHT_TRAINING self.hard_arch_training = cfg.ARCH.HARD_ARCH_TRAINING self.hard_evaluation = cfg.ARCH.HARD_EVAL self.stochastic_evaluation = cfg.ARCH.STOCHASTIC_EVAL self.arch_training = False self.retraining = False self.supernet = False if cfg.MODEL.SUPERNET: print("Running Supernet Baseline") self.supernet = True def loss(self, image, labels): label_1, label_2 = labels result = self.forward(image) result.loss1 = self.task1.loss(result.out1, label_1) result.loss2 = self.task2.loss(result.out2, label_2) result.loss = result.loss1 + self.cfg.TRAIN.TASK2_FACTOR * result.loss2 if self.arch_training: arch_parameters = [ self.net1_alphas[np.nonzero(self.net1_connectivity_matrix)], self.net2_alphas[np.nonzero(self.net2_connectivity_matrix)], ] if self.cfg.ARCH.ENTROPY_REGULARIZATION: result.entropy_loss = entropy_loss(arch_parameters) result.entropy_weight = poly(start=0., end=self.cfg.ARCH.ENTROPY_REGULARIZATION_WEIGHT, steps=self._step, total_steps=self.cfg.TRAIN.STEPS, period=self.cfg.ARCH.ENTROPY_PERIOD, power=1.) result.loss += result.entropy_weight * result.entropy_loss if self.cfg.ARCH.L1_REGULARIZATION: if self.cfg.ARCH.WEIGHTED_L1: result.l1_loss = l1_loss(arch_parameters, self.path_costs) else: result.l1_loss = l1_loss(arch_parameters) result.l1_weight = poly(start=0., end=self.cfg.ARCH.L1_REGULARIZATION_WEIGHT, steps=self._step, total_steps=self.cfg.TRAIN.STEPS, period=self.cfg.ARCH.L1_PERIOD, power=1.) if float(self._step) / self.cfg.TRAIN.STEPS > self.cfg.ARCH.L1_PERIOD[1] and self.cfg.ARCH.L1_OFF: result.l1_weight = 0. result.loss += result.l1_weight * result.l1_loss return result def new(self): return copy.deepcopy(self) def step(self): # update temperature self._step += 1 def get_temperature(self): return poly(start=self.cfg.ARCH.INIT_TEMP, end=0., steps=self._step, total_steps=self.cfg.TRAIN.STEPS, period=self.cfg.ARCH.TEMPERATURE_PERIOD, power=self.cfg.ARCH.TEMPERATURE_POWER) def arch_parameters(self): return self._arch_parameters.values() def named_arch_parameters(self): return self._arch_parameters.items() def net_parameters(self): return self._net_parameters.values() def named_net_parameters(self): return self._net_parameters.items() def arch_train(self): self.arch_training = True def arch_eval(self): self.arch_training = False def retrain(self): self.retraining = True def gumbel_connectivity(self, path_weights): temp = self.get_temperature() net_dist = dist.relaxed_bernoulli.RelaxedBernoulli(temp, logits=path_weights) path_connectivity = net_dist.rsample() return path_connectivity def bernoulli_connectivity(self, path_weights): net_dist = dist.bernoulli.Bernoulli(logits=path_weights) path_connectivity = net_dist.sample() return path_connectivity def sigmoid_connectivity(self, path_weights): return torch.sigmoid(path_weights) def onehot_connectivity(self, path_weights): path_connectivity = (path_weights > 0.).float() return path_connectivity def all_connectivity(self, path_weights): return torch.ones_like(path_weights) def forward(self, x): N, C, H, W = x.size() y = x.clone() x = self.net1.base(x) y = self.net2.base(y) xs, ys = [], [] for stage_id in range(self.num_stages): x = self.net1.stages[stage_id](x) y = self.net2.stages[stage_id](y) if isinstance(x, list): xs.append(x[0]) ys.append(y[0]) else: xs.append(x) ys.append(y) net1_path_ids = np.nonzero(self.net1_connectivity_matrix[stage_id])[0] net2_path_ids = np.nonzero(self.net2_connectivity_matrix[stage_id])[0] net1_path_weights = self.net1_alphas[stage_id][net1_path_ids] net2_path_weights = self.net2_alphas[stage_id][net2_path_ids] # Calculating path strength based on weights if self.training: if self.supernet: connectivity = 'all' elif self.retraining: connectivity = 'onehot' else: if self.arch_training: # Training architecture if self.hard_arch_training: connectivity = 'gumbel' else: connectivity = 'sigmoid' else: # Training weights if self.hard_weight_training: connectivity = 'gumbel' else: connectivity = 'sigmoid' else: if self.supernet: connectivity = 'all' elif self.retraining: connectivity = 'onehot' elif self.stochastic_evaluation: assert not self.hard_evaluation connectivity = 'bernoulli' elif self.hard_evaluation: connectivity = 'onehot' else: connectivity = 'sigmoid' if connectivity == 'gumbel': net1_path_connectivity = self.gumbel_connectivity(net1_path_weights) net2_path_connectivity = self.gumbel_connectivity(net2_path_weights) elif connectivity == 'sigmoid': net1_path_connectivity = self.sigmoid_connectivity(net1_path_weights) net2_path_connectivity = self.sigmoid_connectivity(net2_path_weights) elif connectivity == 'all': net1_path_connectivity = self.all_connectivity(net1_path_weights) net2_path_connectivity = self.all_connectivity(net2_path_weights) elif connectivity == 'bernoulli': net1_path_connectivity = self.bernoulli_connectivity(net1_path_weights) net2_path_connectivity = self.bernoulli_connectivity(net2_path_weights) else: assert connectivity == 'onehot' net1_path_connectivity = self.onehot_connectivity(net1_path_weights) net2_path_connectivity = self.onehot_connectivity(net2_path_weights) if isinstance(x, list): net1_fusion_input = [x[0]] net2_fusion_input = [y[0]] else: net1_fusion_input = [x] net2_fusion_input = [y] for idx, input_id in enumerate(net1_path_ids): net1_fusion_input.append(net1_path_connectivity[idx]*ys[input_id]) for idx, input_id in enumerate(net2_path_ids): net2_fusion_input.append(net2_path_connectivity[idx]*xs[input_id]) if isinstance(x, list): x[0] = self.paths['net1_paths'][stage_id](net1_fusion_input) y[0] = self.paths['net2_paths'][stage_id](net2_fusion_input) else: x = self.paths['net1_paths'][stage_id](net1_fusion_input) y = self.paths['net2_paths'][stage_id](net2_fusion_input) x = self.net1.head(x) y = self.net2.head(y) return AttrDict({'out1': x, 'out2': y})
0.890181
0.246567
import functools import time import torch import torch.autograd as autograd import torch.cuda.comm as comm import torch.nn as nn import torch.nn.functional as F from torch.autograd.function import once_differentiable class CA_Weight(autograd.Function): @staticmethod def forward(ctx, t, f): # Save context n, c, h, w = t.size() size = (n, h + w - 1, h, w) weight = torch.zeros(size, dtype=t.dtype, layout=t.layout, device=t.device) _ext.ca_forward_cuda(t, f, weight) # Output ctx.save_for_backward(t, f) return weight @staticmethod @once_differentiable def backward(ctx, dw): t, f = ctx.saved_tensors dt = torch.zeros_like(t) df = torch.zeros_like(f) _ext.ca_backward_cuda(dw.contiguous(), t, f, dt, df) _check_contiguous(dt, df) return dt, df class CA_Map(autograd.Function): @staticmethod def forward(ctx, weight, g): # Save context out = torch.zeros_like(g) _ext.ca_map_forward_cuda(weight, g, out) # Output ctx.save_for_backward(weight, g) return out @staticmethod @once_differentiable def backward(ctx, dout): weight, g = ctx.saved_tensors dw = torch.zeros_like(weight) dg = torch.zeros_like(g) _ext.ca_map_backward_cuda(dout.contiguous(), weight, g, dw, dg) _check_contiguous(dw, dg) return dw, dg ca_weight = CA_Weight.apply ca_map = CA_Map.apply class CrissCrossAttention(nn.Module): """ Criss-Cross Attention Module""" def __init__(self, in_dim): super(CrissCrossAttention, self).__init__() self.chanel_in = in_dim self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim // 8, kernel_size=1) self.key_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim // 8, kernel_size=1) self.value_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim, kernel_size=1) self.gamma = nn.Parameter(torch.zeros(1)) def forward(self, x): proj_query = self.query_conv(x) proj_key = self.key_conv(x) proj_value = self.value_conv(x) energy = ca_weight(proj_query, proj_key) attention = F.softmax(energy, 1) out = ca_map(attention, proj_value) out = self.gamma * out + x return out
Plug-and-play module/attention/CCNet/ccnet.py
import functools import time import torch import torch.autograd as autograd import torch.cuda.comm as comm import torch.nn as nn import torch.nn.functional as F from torch.autograd.function import once_differentiable class CA_Weight(autograd.Function): @staticmethod def forward(ctx, t, f): # Save context n, c, h, w = t.size() size = (n, h + w - 1, h, w) weight = torch.zeros(size, dtype=t.dtype, layout=t.layout, device=t.device) _ext.ca_forward_cuda(t, f, weight) # Output ctx.save_for_backward(t, f) return weight @staticmethod @once_differentiable def backward(ctx, dw): t, f = ctx.saved_tensors dt = torch.zeros_like(t) df = torch.zeros_like(f) _ext.ca_backward_cuda(dw.contiguous(), t, f, dt, df) _check_contiguous(dt, df) return dt, df class CA_Map(autograd.Function): @staticmethod def forward(ctx, weight, g): # Save context out = torch.zeros_like(g) _ext.ca_map_forward_cuda(weight, g, out) # Output ctx.save_for_backward(weight, g) return out @staticmethod @once_differentiable def backward(ctx, dout): weight, g = ctx.saved_tensors dw = torch.zeros_like(weight) dg = torch.zeros_like(g) _ext.ca_map_backward_cuda(dout.contiguous(), weight, g, dw, dg) _check_contiguous(dw, dg) return dw, dg ca_weight = CA_Weight.apply ca_map = CA_Map.apply class CrissCrossAttention(nn.Module): """ Criss-Cross Attention Module""" def __init__(self, in_dim): super(CrissCrossAttention, self).__init__() self.chanel_in = in_dim self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim // 8, kernel_size=1) self.key_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim // 8, kernel_size=1) self.value_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim, kernel_size=1) self.gamma = nn.Parameter(torch.zeros(1)) def forward(self, x): proj_query = self.query_conv(x) proj_key = self.key_conv(x) proj_value = self.value_conv(x) energy = ca_weight(proj_query, proj_key) attention = F.softmax(energy, 1) out = ca_map(attention, proj_value) out = self.gamma * out + x return out
0.940558
0.289692
import argparse import csv import json import os import logging import yaml def load_csv_logs(filename): logs = [] p_fields = set() with open(filename, 'r' ) as fi: reader = csv.DictReader(fi) # Get the full list of p_ fields in this particular log type p_fields = set([x for x in reader.fieldnames if x.startswith('p_')]) for line in reader: # Pop the p_any fields off the record so they are recalculated for p_field in p_fields: _ = line.pop(p_field) logs.append(line) return json.loads(json.dumps(logs)) def load_json_logs(filename): logs = [] with open(filename) as fi: for line_num, line in enumerate(fi): try: json_line = json.loads(line) except json.JSONDecodeError: logging.error("non-JSON line [%s] detected", line_num + 1) continue panther_keys = set(key for key in json_line.keys() if key.startswith('p_')) for key in panther_keys: del json_line[key] logs.append(json_line) return logs def main(cmdline_args): test_data = { "LogType": cmdline_args.log_type, "Format": cmdline_args.log_format, } extension = os.path.splitext(cmdline_args.input)[1] if extension == '.csv': test_data['Logs'] = load_csv_logs(cmdline_args.input) elif extension == '.json': test_data['Logs'] = load_json_logs(cmdline_args.input) else: logging.info('unsupported input type: %s', extension) return with open(cmdline_args.output, "w") as fo: yaml.dump(test_data, fo) logging.info("Wrote %d example logs to %s", len(test_data['Logs']), cmdline_args.output) if __name__ == "__main__": parser = argparse.ArgumentParser( description="Prepare scenario data from JSONL-formatted files." ) parser.add_argument( "--input", help="the filename", required=True) parser.add_argument( "--output", help="the YAML scenario filename", required=True) parser.add_argument( "--log-type", help="the test scenario log type (e.g. AWS.CloudTrail)", required=True ) parser.add_argument( "--log-format", help="the format to write test_data out to S3 (json, jsonl, raw)", required=True, ) args = parser.parse_args() logging.basicConfig( format="[%(asctime)s %(levelname)s] %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S", ) main(args)
test_scenarios/jsonl_to_testfile.py
import argparse import csv import json import os import logging import yaml def load_csv_logs(filename): logs = [] p_fields = set() with open(filename, 'r' ) as fi: reader = csv.DictReader(fi) # Get the full list of p_ fields in this particular log type p_fields = set([x for x in reader.fieldnames if x.startswith('p_')]) for line in reader: # Pop the p_any fields off the record so they are recalculated for p_field in p_fields: _ = line.pop(p_field) logs.append(line) return json.loads(json.dumps(logs)) def load_json_logs(filename): logs = [] with open(filename) as fi: for line_num, line in enumerate(fi): try: json_line = json.loads(line) except json.JSONDecodeError: logging.error("non-JSON line [%s] detected", line_num + 1) continue panther_keys = set(key for key in json_line.keys() if key.startswith('p_')) for key in panther_keys: del json_line[key] logs.append(json_line) return logs def main(cmdline_args): test_data = { "LogType": cmdline_args.log_type, "Format": cmdline_args.log_format, } extension = os.path.splitext(cmdline_args.input)[1] if extension == '.csv': test_data['Logs'] = load_csv_logs(cmdline_args.input) elif extension == '.json': test_data['Logs'] = load_json_logs(cmdline_args.input) else: logging.info('unsupported input type: %s', extension) return with open(cmdline_args.output, "w") as fo: yaml.dump(test_data, fo) logging.info("Wrote %d example logs to %s", len(test_data['Logs']), cmdline_args.output) if __name__ == "__main__": parser = argparse.ArgumentParser( description="Prepare scenario data from JSONL-formatted files." ) parser.add_argument( "--input", help="the filename", required=True) parser.add_argument( "--output", help="the YAML scenario filename", required=True) parser.add_argument( "--log-type", help="the test scenario log type (e.g. AWS.CloudTrail)", required=True ) parser.add_argument( "--log-format", help="the format to write test_data out to S3 (json, jsonl, raw)", required=True, ) args = parser.parse_args() logging.basicConfig( format="[%(asctime)s %(levelname)s] %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S", ) main(args)
0.27048
0.139104
import random as python_random from typing import Dict, List, Optional, Sequence, Tuple import numpy as np import pandas as pd from scipy import stats from sklearn import metrics as skm import tensorflow as tf import metrics import models import potts_model import sampling import solver import utils def get_fitness_df(sequences, fitness_fn, ref_seq): """Get a DataFrame with the fitness of the requested sequences. Args: sequences: A 2D NxL numpy array of integer encoded sequences. fitness_fn: A function, that when given a single integer encoded sequence, returns a fitness value. ref_seq: An integer encoded sequence. `num_mutations` is measured with respect to this sequence. Returns: A pd.DataFrame with the fields `sequence`, `num_mutations`, `fitness`. """ num_mutations = [utils.hamming_distance(ref_seq, s) for s in sequences] df = pd.DataFrame( dict( sequence=list(sequences), num_mutations=num_mutations, fitness=fitness_fn(sequences))) return df def get_random_split_df( df, train_fraction, random_state): """Returns two dfs, randomly split into `train_fraction` and 1-`train_fraction`.""" train_df = df.sample(frac=train_fraction, random_state=random_state) test_df = df[~df.index.isin(train_df.index)] return (train_df, test_df) def get_distance_split_df( df, reference_seq, distance_threshold): """Returns DataFrames split based on distance from `reference_seq`. The first df includes all sequences within `distance_threshold` (inclusive) of `reference_seq`, and the second df contains the rest. Args: df: A pd.DataFrame with a `sequence` column. reference_seq: A 1D integer-encoded sequence. distance_threshold: An integer threshold, sequences in `df` with hamming distance within `distance_threshold` (inclusive) of `reference_sequence` are included in the first returned df, while the second df contains the rest. Returns: Two pd.DataFrames with the sequences split according to distance. """ distance_from_reference = df.sequence.apply( utils.hamming_distance, y=reference_seq) train_df = df[distance_from_reference <= distance_threshold].copy() test_df = df[~df.index.isin(train_df.index)].copy() return (train_df, test_df) def fit_model(model, df, vocab_size, flatten_inputs): """Fit `model` to training data given by `df`.""" x_train, y_train = utils.get_x_y_from_df( df, vocab_size=vocab_size, flatten=flatten_inputs) model.fit(x_train, y_train) def get_regression_metrics(y_pred, y_true): """Returns a long-form dictionary of metrics.""" metrics_dict = {} metrics_dict['mse'] = skm.mean_squared_error(y_pred, y_true) metrics_dict['std_predicted'] = np.std(y_pred) metrics_dict['std_test'] = np.std(y_true) if np.std(y_pred) != 0.0 and np.std(y_true) != 0.0: # Correlation coefficients are undefined if the deviation of either array is 0. coef, _ = stats.spearmanr(y_pred, y_true) metrics_dict['spearman_r'] = coef coef, _ = stats.kendalltau(y_pred, y_true) metrics_dict['kendalltau'] = coef coef, _ = stats.pearsonr(y_pred, y_true) metrics_dict['pearson_r'] = coef metrics_dict['r_squared'] = skm.r2_score(y_pred, y_true) return metrics_dict def compute_regression_metrics_random_split( model, df, train_fraction, vocab_size, flatten_inputs, random_state): """Returns regression metrics for a random split of the data.""" train_df, test_df = get_random_split_df( df, train_fraction, random_state=random_state) fit_model(model, train_df, vocab_size, flatten_inputs) x_test, y_true = utils.get_x_y_from_df( test_df, vocab_size=vocab_size, flatten=flatten_inputs) y_pred = model.predict(x_test) size_dict = {'train_size': len(train_df), 'test_size': len(test_df)} metrics_dict = get_regression_metrics(y_pred, y_true) metrics_dict.update(size_dict) return metrics_dict def compute_regression_metrics_distance_split( model, df, reference_seq, distance_threshold, vocab_size, flatten_inputs): """Returns regression metrics for a distance-based split of the data.""" train_df, test_df = get_distance_split_df(df, reference_seq, distance_threshold) fit_model(model, train_df, vocab_size, flatten_inputs) size_dict = {'train_size': len(train_df), 'test_size': len(test_df)} if len(test_df) == 0: return size_dict else: x_test, y_true = utils.get_x_y_from_df( test_df, vocab_size=vocab_size, flatten=flatten_inputs) y_pred = model.predict(x_test) metrics_dict = get_regression_metrics(y_pred, y_true) metrics_dict.update(size_dict) return metrics_dict def get_samples_around_wildtype( landscape, num_samples, min_num_mutations, max_num_mutations, vocab_size, include_singles, random_state): """Return a DataFrame with a sample centered around the `landscape` wildtype. If `include_singles` is true, then L*A singles are added in addition to the `num_samples` random samples. Args: landscape: A landscape with a .evaluate() method. num_samples: The number of random samples to draw from the landscape. min_num_mutations: The minimum number of mutations to randomly sample. max_num_mutations: The maximum number of mutations to randomly sample. vocab_size: The number of amino acids in the vocabulary. include_singles: Whether to include all single mutants or not. random_state: np.random.RandomState which dictates the sampling. Returns: A DataFrame of samples with `sequence` and `fitness` keys. """ sample = sampling.sample_within_hamming_radius( landscape.wildtype_sequence, num_samples, vocab_size, min_mutations=min_num_mutations, max_mutations=max_num_mutations, random_state=random_state) if include_singles: all_singles = sampling.get_all_single_mutants( landscape.wildtype_sequence, vocab_size=vocab_size) sample = np.vstack([sample, all_singles]) random_state.shuffle(sample) sample_df = get_fitness_df(sample, landscape.evaluate, landscape.wildtype_sequence) sample_df['sequence_tuple'] = sample_df.sequence.apply(tuple) sample_df = sample_df.drop_duplicates('sequence_tuple') sample_df = sample_df.drop(labels='sequence_tuple', axis='columns') return sample_df def run_regression_experiment( mogwai_filepath, potts_coupling_scale, potts_field_scale, potts_single_mut_offset, potts_epi_offset, vocab_size, training_set_min_num_mutations, training_set_max_num_mutations, training_set_num_samples, training_set_include_singles, training_set_random_seed, model_name, model_random_seed, metrics_random_split_fraction, metrics_random_split_random_seed, metrics_distance_split_radii): """Returns metrics for a regression experiment.""" # Load Potts model landscape landscape = potts_model.load_from_mogwai_npz( mogwai_filepath, coupling_scale=potts_coupling_scale, field_scale=potts_field_scale, single_mut_offset=potts_single_mut_offset, epi_offset=potts_epi_offset) # Sample a training dataset. training_random_state = np.random.RandomState(training_set_random_seed) sample_df = get_samples_around_wildtype(landscape, training_set_num_samples, training_set_min_num_mutations, training_set_max_num_mutations, vocab_size, training_set_include_singles, training_random_state) # Keras reproducibility np.random.seed(model_random_seed) python_random.seed(model_random_seed) tf.random.set_seed(model_random_seed) # Compute regression metrics. sequence_length = len(landscape.wildtype_sequence) model, flatten_inputs = models.get_model(model_name, sequence_length, vocab_size) metrics_random_state = np.random.RandomState(metrics_random_split_random_seed) run_metrics = {} random_split_metrics = compute_regression_metrics_random_split( model, sample_df, metrics_random_split_fraction, vocab_size, flatten_inputs, metrics_random_state) run_metrics['random_split'] = random_split_metrics for distance_threshold in metrics_distance_split_radii: distance_metrics = compute_regression_metrics_distance_split( model, sample_df, landscape.wildtype_sequence, distance_threshold, vocab_size, flatten_inputs) run_metrics['distance_split_{}'.format( distance_threshold)] = distance_metrics return run_metrics def run_design_experiment( mogwai_filepath, potts_coupling_scale, potts_field_scale, potts_single_mut_offset, potts_epi_offset, vocab_size, training_set_min_num_mutations, training_set_max_num_mutations, training_set_num_samples, training_set_include_singles, training_set_random_seed, model_name, model_random_seed, mbo_num_designs, mbo_random_seed, inner_loop_solver_top_k, inner_loop_solver_min_mutations, inner_loop_solver_max_mutations, inner_loop_num_rounds, inner_loop_num_samples, design_metrics_hit_threshold, design_metrics_cluster_hamming_distance, design_metrics_fitness_percentiles, output_filepath = None, ): """Returns a tuple of (metrics, proposal DataFrame) for a design experiment.""" # Load Potts model landscape landscape = potts_model.load_from_mogwai_npz( mogwai_filepath, coupling_scale=potts_coupling_scale, field_scale=potts_field_scale, single_mut_offset=potts_single_mut_offset, epi_offset=potts_epi_offset) # Sample a training dataset. training_random_state = np.random.RandomState(training_set_random_seed) sample_df = get_samples_around_wildtype(landscape, training_set_num_samples, training_set_min_num_mutations, training_set_max_num_mutations, vocab_size, training_set_include_singles, training_random_state) # Keras reproducibility np.random.seed(model_random_seed) python_random.seed(model_random_seed) tf.random.set_seed(model_random_seed) # MBO sequence_length = len(landscape.wildtype_sequence) model, flatten_inputs = models.get_model(model_name, sequence_length, vocab_size) inner_loop_solver = solver.RandomMutationSolver( inner_loop_solver_min_mutations, inner_loop_solver_max_mutations, top_k=inner_loop_solver_top_k, vocab_size=vocab_size) mbo_random_state = np.random.RandomState(mbo_random_seed) mbo_solver = solver.ModelBasedSolver( model, vocab_size=vocab_size, flatten_inputs=flatten_inputs, inner_loop_num_rounds=inner_loop_num_rounds, inner_loop_num_samples=inner_loop_num_samples, inner_loop_solver=inner_loop_solver) proposals = mbo_solver.propose( sample_df, num_samples=mbo_num_designs, random_state=mbo_random_state) proposals_df = get_fitness_df(proposals, landscape.evaluate, landscape.wildtype_sequence) if output_filepath: _write_seq_df_to_path(proposals_df, output_filepath) # Metrics run_metrics = {} normalized_hit_rate = metrics.diversity_normalized_hit_rate( proposals_df, design_metrics_hit_threshold, design_metrics_cluster_hamming_distance) run_metrics['diversity_normalize_hit_rate'] = normalized_hit_rate for percentile in design_metrics_fitness_percentiles: percentile_fitness = np.percentile(proposals_df.fitness, q=percentile) run_metrics['{}_percentile_fitness'.format(percentile)] = percentile_fitness return run_metrics def _write_seq_df_to_path(df, output_filepath): with open(output_filepath) as f: df.to_csv(f)
experiment.py
import random as python_random from typing import Dict, List, Optional, Sequence, Tuple import numpy as np import pandas as pd from scipy import stats from sklearn import metrics as skm import tensorflow as tf import metrics import models import potts_model import sampling import solver import utils def get_fitness_df(sequences, fitness_fn, ref_seq): """Get a DataFrame with the fitness of the requested sequences. Args: sequences: A 2D NxL numpy array of integer encoded sequences. fitness_fn: A function, that when given a single integer encoded sequence, returns a fitness value. ref_seq: An integer encoded sequence. `num_mutations` is measured with respect to this sequence. Returns: A pd.DataFrame with the fields `sequence`, `num_mutations`, `fitness`. """ num_mutations = [utils.hamming_distance(ref_seq, s) for s in sequences] df = pd.DataFrame( dict( sequence=list(sequences), num_mutations=num_mutations, fitness=fitness_fn(sequences))) return df def get_random_split_df( df, train_fraction, random_state): """Returns two dfs, randomly split into `train_fraction` and 1-`train_fraction`.""" train_df = df.sample(frac=train_fraction, random_state=random_state) test_df = df[~df.index.isin(train_df.index)] return (train_df, test_df) def get_distance_split_df( df, reference_seq, distance_threshold): """Returns DataFrames split based on distance from `reference_seq`. The first df includes all sequences within `distance_threshold` (inclusive) of `reference_seq`, and the second df contains the rest. Args: df: A pd.DataFrame with a `sequence` column. reference_seq: A 1D integer-encoded sequence. distance_threshold: An integer threshold, sequences in `df` with hamming distance within `distance_threshold` (inclusive) of `reference_sequence` are included in the first returned df, while the second df contains the rest. Returns: Two pd.DataFrames with the sequences split according to distance. """ distance_from_reference = df.sequence.apply( utils.hamming_distance, y=reference_seq) train_df = df[distance_from_reference <= distance_threshold].copy() test_df = df[~df.index.isin(train_df.index)].copy() return (train_df, test_df) def fit_model(model, df, vocab_size, flatten_inputs): """Fit `model` to training data given by `df`.""" x_train, y_train = utils.get_x_y_from_df( df, vocab_size=vocab_size, flatten=flatten_inputs) model.fit(x_train, y_train) def get_regression_metrics(y_pred, y_true): """Returns a long-form dictionary of metrics.""" metrics_dict = {} metrics_dict['mse'] = skm.mean_squared_error(y_pred, y_true) metrics_dict['std_predicted'] = np.std(y_pred) metrics_dict['std_test'] = np.std(y_true) if np.std(y_pred) != 0.0 and np.std(y_true) != 0.0: # Correlation coefficients are undefined if the deviation of either array is 0. coef, _ = stats.spearmanr(y_pred, y_true) metrics_dict['spearman_r'] = coef coef, _ = stats.kendalltau(y_pred, y_true) metrics_dict['kendalltau'] = coef coef, _ = stats.pearsonr(y_pred, y_true) metrics_dict['pearson_r'] = coef metrics_dict['r_squared'] = skm.r2_score(y_pred, y_true) return metrics_dict def compute_regression_metrics_random_split( model, df, train_fraction, vocab_size, flatten_inputs, random_state): """Returns regression metrics for a random split of the data.""" train_df, test_df = get_random_split_df( df, train_fraction, random_state=random_state) fit_model(model, train_df, vocab_size, flatten_inputs) x_test, y_true = utils.get_x_y_from_df( test_df, vocab_size=vocab_size, flatten=flatten_inputs) y_pred = model.predict(x_test) size_dict = {'train_size': len(train_df), 'test_size': len(test_df)} metrics_dict = get_regression_metrics(y_pred, y_true) metrics_dict.update(size_dict) return metrics_dict def compute_regression_metrics_distance_split( model, df, reference_seq, distance_threshold, vocab_size, flatten_inputs): """Returns regression metrics for a distance-based split of the data.""" train_df, test_df = get_distance_split_df(df, reference_seq, distance_threshold) fit_model(model, train_df, vocab_size, flatten_inputs) size_dict = {'train_size': len(train_df), 'test_size': len(test_df)} if len(test_df) == 0: return size_dict else: x_test, y_true = utils.get_x_y_from_df( test_df, vocab_size=vocab_size, flatten=flatten_inputs) y_pred = model.predict(x_test) metrics_dict = get_regression_metrics(y_pred, y_true) metrics_dict.update(size_dict) return metrics_dict def get_samples_around_wildtype( landscape, num_samples, min_num_mutations, max_num_mutations, vocab_size, include_singles, random_state): """Return a DataFrame with a sample centered around the `landscape` wildtype. If `include_singles` is true, then L*A singles are added in addition to the `num_samples` random samples. Args: landscape: A landscape with a .evaluate() method. num_samples: The number of random samples to draw from the landscape. min_num_mutations: The minimum number of mutations to randomly sample. max_num_mutations: The maximum number of mutations to randomly sample. vocab_size: The number of amino acids in the vocabulary. include_singles: Whether to include all single mutants or not. random_state: np.random.RandomState which dictates the sampling. Returns: A DataFrame of samples with `sequence` and `fitness` keys. """ sample = sampling.sample_within_hamming_radius( landscape.wildtype_sequence, num_samples, vocab_size, min_mutations=min_num_mutations, max_mutations=max_num_mutations, random_state=random_state) if include_singles: all_singles = sampling.get_all_single_mutants( landscape.wildtype_sequence, vocab_size=vocab_size) sample = np.vstack([sample, all_singles]) random_state.shuffle(sample) sample_df = get_fitness_df(sample, landscape.evaluate, landscape.wildtype_sequence) sample_df['sequence_tuple'] = sample_df.sequence.apply(tuple) sample_df = sample_df.drop_duplicates('sequence_tuple') sample_df = sample_df.drop(labels='sequence_tuple', axis='columns') return sample_df def run_regression_experiment( mogwai_filepath, potts_coupling_scale, potts_field_scale, potts_single_mut_offset, potts_epi_offset, vocab_size, training_set_min_num_mutations, training_set_max_num_mutations, training_set_num_samples, training_set_include_singles, training_set_random_seed, model_name, model_random_seed, metrics_random_split_fraction, metrics_random_split_random_seed, metrics_distance_split_radii): """Returns metrics for a regression experiment.""" # Load Potts model landscape landscape = potts_model.load_from_mogwai_npz( mogwai_filepath, coupling_scale=potts_coupling_scale, field_scale=potts_field_scale, single_mut_offset=potts_single_mut_offset, epi_offset=potts_epi_offset) # Sample a training dataset. training_random_state = np.random.RandomState(training_set_random_seed) sample_df = get_samples_around_wildtype(landscape, training_set_num_samples, training_set_min_num_mutations, training_set_max_num_mutations, vocab_size, training_set_include_singles, training_random_state) # Keras reproducibility np.random.seed(model_random_seed) python_random.seed(model_random_seed) tf.random.set_seed(model_random_seed) # Compute regression metrics. sequence_length = len(landscape.wildtype_sequence) model, flatten_inputs = models.get_model(model_name, sequence_length, vocab_size) metrics_random_state = np.random.RandomState(metrics_random_split_random_seed) run_metrics = {} random_split_metrics = compute_regression_metrics_random_split( model, sample_df, metrics_random_split_fraction, vocab_size, flatten_inputs, metrics_random_state) run_metrics['random_split'] = random_split_metrics for distance_threshold in metrics_distance_split_radii: distance_metrics = compute_regression_metrics_distance_split( model, sample_df, landscape.wildtype_sequence, distance_threshold, vocab_size, flatten_inputs) run_metrics['distance_split_{}'.format( distance_threshold)] = distance_metrics return run_metrics def run_design_experiment( mogwai_filepath, potts_coupling_scale, potts_field_scale, potts_single_mut_offset, potts_epi_offset, vocab_size, training_set_min_num_mutations, training_set_max_num_mutations, training_set_num_samples, training_set_include_singles, training_set_random_seed, model_name, model_random_seed, mbo_num_designs, mbo_random_seed, inner_loop_solver_top_k, inner_loop_solver_min_mutations, inner_loop_solver_max_mutations, inner_loop_num_rounds, inner_loop_num_samples, design_metrics_hit_threshold, design_metrics_cluster_hamming_distance, design_metrics_fitness_percentiles, output_filepath = None, ): """Returns a tuple of (metrics, proposal DataFrame) for a design experiment.""" # Load Potts model landscape landscape = potts_model.load_from_mogwai_npz( mogwai_filepath, coupling_scale=potts_coupling_scale, field_scale=potts_field_scale, single_mut_offset=potts_single_mut_offset, epi_offset=potts_epi_offset) # Sample a training dataset. training_random_state = np.random.RandomState(training_set_random_seed) sample_df = get_samples_around_wildtype(landscape, training_set_num_samples, training_set_min_num_mutations, training_set_max_num_mutations, vocab_size, training_set_include_singles, training_random_state) # Keras reproducibility np.random.seed(model_random_seed) python_random.seed(model_random_seed) tf.random.set_seed(model_random_seed) # MBO sequence_length = len(landscape.wildtype_sequence) model, flatten_inputs = models.get_model(model_name, sequence_length, vocab_size) inner_loop_solver = solver.RandomMutationSolver( inner_loop_solver_min_mutations, inner_loop_solver_max_mutations, top_k=inner_loop_solver_top_k, vocab_size=vocab_size) mbo_random_state = np.random.RandomState(mbo_random_seed) mbo_solver = solver.ModelBasedSolver( model, vocab_size=vocab_size, flatten_inputs=flatten_inputs, inner_loop_num_rounds=inner_loop_num_rounds, inner_loop_num_samples=inner_loop_num_samples, inner_loop_solver=inner_loop_solver) proposals = mbo_solver.propose( sample_df, num_samples=mbo_num_designs, random_state=mbo_random_state) proposals_df = get_fitness_df(proposals, landscape.evaluate, landscape.wildtype_sequence) if output_filepath: _write_seq_df_to_path(proposals_df, output_filepath) # Metrics run_metrics = {} normalized_hit_rate = metrics.diversity_normalized_hit_rate( proposals_df, design_metrics_hit_threshold, design_metrics_cluster_hamming_distance) run_metrics['diversity_normalize_hit_rate'] = normalized_hit_rate for percentile in design_metrics_fitness_percentiles: percentile_fitness = np.percentile(proposals_df.fitness, q=percentile) run_metrics['{}_percentile_fitness'.format(percentile)] = percentile_fitness return run_metrics def _write_seq_df_to_path(df, output_filepath): with open(output_filepath) as f: df.to_csv(f)
0.938301
0.525978
import warnings from typing import List, Type from ..optimizers.base_optimizer import BaseOptimizer, BaseOptimizerWithEarlyStopping from ..parameter_tuning import ( CategoricalSuggestion, IntegerSuggestion, LogUniformSuggestion, Suggestion, UniformSuggestion, ) from ..recommenders import ( AsymmetricCosineKNNRecommender, AsymmetricCosineUserKNNRecommender, CosineKNNRecommender, CosineUserKNNRecommender, DenseSLIMRecommender, IALSRecommender, JaccardKNNRecommender, NMFRecommender, P3alphaRecommender, RP3betaRecommender, SLIMRecommender, TopPopRecommender, TruncatedSVDRecommender, TverskyIndexKNNRecommender, ) default_tune_range_knn = [ IntegerSuggestion("top_k", 4, 1000), UniformSuggestion("shrinkage", 0, 1000), ] default_tune_range_knn_with_weighting = [ IntegerSuggestion("top_k", 4, 1000), UniformSuggestion("shrinkage", 0, 1000), CategoricalSuggestion("feature_weighting", ["NONE", "TF_IDF", "BM_25"]), ] _BaseOptimizerArgsString = """Args: data (Union[scipy.sparse.csr_matrix, scipy.sparse.csc_matrix]): The train data. val_evaluator (Evaluator): The validation evaluator which measures the performance of the recommenders. logger (Optional[logging.Logger], optional) : The logger used during the optimization steps. Defaults to None. If ``None``, the default logger of irspack will be used. suggest_overwrite (List[Suggestion], optional) : Customizes (e.g. enlarging the parameter region or adding new parameters to be tuned) the default parameter search space defined by ``default_tune_range`` Defaults to list(). fixed_params (Dict[str, Any], optional): Fixed parameters passed to recommenders during the optimization procedure. If such a parameter exists in ``default_tune_range``, it will not be tuned. Defaults to dict(). """ _BaseOptimizerWithEarlyStoppingArgsString = """Args: data (Union[scipy.sparse.csr_matrix, scipy.sparse.csc_matrix]): The train data. val_evaluator (Evaluator): The validation evaluator which measures the performance of the recommenders. logger (Optional[logging.Logger], optional): The logger used during the optimization steps. Defaults to None. If ``None``, the default logger of irspack will be used. suggest_overwrite (List[Suggestion], optional): Customizes (e.g. enlarging the parameter region or adding new parameters to be tuned) the default parameter search space defined by ``default_tune_range`` Defaults to list(). fixed_params (Dict[str, Any], optional): Fixed parameters passed to recommenders during the optimization procedure. If such a parameter exists in ``default_tune_range``, it will not be tuned. Defaults to dict(). max_epoch (int, optional): The maximal number of epochs for the training. Defaults to 512. validate_epoch (int, optional): The frequency of validation score measurement. Defaults to 5. score_degradation_max (int, optional): Maximal number of allowed score degradation. Defaults to 5. Defaults to 5. """ def _add_docstring( cls: Type[BaseOptimizer], args: str = _BaseOptimizerArgsString ) -> None: if cls.default_tune_range: ranges = "" for suggest in cls.default_tune_range: ranges += f" - ``{suggest!r}``\n" ranges += "\n" tune_range = f"""The default tune range is {ranges}""" else: tune_range = " There is no tunable parameters." docs = f"""Optimizer class for :class:`irspack.recommenders.{cls.recommender_class.__name__}`. {tune_range} {args} """ cls.__doc__ = docs class TopPopOptimizer(BaseOptimizer): default_tune_range: List[Suggestion] = [] recommender_class = TopPopRecommender _add_docstring(TopPopOptimizer) class IALSOptimizer(BaseOptimizerWithEarlyStopping): default_tune_range = [ IntegerSuggestion("n_components", 4, 300), LogUniformSuggestion("alpha", 1, 100), LogUniformSuggestion("reg", 1e-10, 1e-2), ] recommender_class = IALSRecommender _add_docstring(IALSOptimizer, _BaseOptimizerWithEarlyStoppingArgsString) class P3alphaOptimizer(BaseOptimizer): default_tune_range = [ IntegerSuggestion("top_k", low=10, high=1000), CategoricalSuggestion("normalize_weight", [True, False]), ] recommender_class = P3alphaRecommender _add_docstring(P3alphaOptimizer) class DenseSLIMOptimizer(BaseOptimizer): default_tune_range = [LogUniformSuggestion("reg", 1, 1e4)] recommender_class = DenseSLIMRecommender _add_docstring(DenseSLIMOptimizer) class RP3betaOptimizer(BaseOptimizer): default_tune_range = [ IntegerSuggestion("top_k", 2, 1000), LogUniformSuggestion("beta", 1e-5, 5e-1), CategoricalSuggestion("normalize_weight", [True, False]), ] recommender_class = RP3betaRecommender _add_docstring(RP3betaOptimizer) class TruncatedSVDOptimizer(BaseOptimizer): default_tune_range = [IntegerSuggestion("n_components", 4, 512)] recommender_class = TruncatedSVDRecommender _add_docstring(TruncatedSVDOptimizer) class SLIMOptimizer(BaseOptimizer): default_tune_range = [ LogUniformSuggestion("alpha", 1e-5, 1), UniformSuggestion("l1_ratio", 0, 1), ] recommender_class = SLIMRecommender _add_docstring(SLIMOptimizer) class NMFOptimizer(BaseOptimizer): default_tune_range = [ IntegerSuggestion("n_components", 4, 512), LogUniformSuggestion("alpha", 1e-10, 1e-1), UniformSuggestion("l1_ratio", 0, 1), CategoricalSuggestion("beta_loss", ["frobenius", "kullback-leibler"]), ] recommender_class = NMFRecommender _add_docstring(NMFOptimizer) class CosineKNNOptimizer(BaseOptimizer): default_tune_range = default_tune_range_knn_with_weighting.copy() + [ CategoricalSuggestion("normalize", [False, True]) ] recommender_class = CosineKNNRecommender _add_docstring(CosineKNNOptimizer) class AsymmetricCosineKNNOptimizer(BaseOptimizer): default_tune_range = default_tune_range_knn_with_weighting + [ UniformSuggestion("alpha", 0, 1) ] recommender_class = AsymmetricCosineKNNRecommender _add_docstring(AsymmetricCosineKNNOptimizer) class JaccardKNNOptimizer(BaseOptimizer): default_tune_range = default_tune_range_knn.copy() recommender_class = JaccardKNNRecommender _add_docstring(JaccardKNNOptimizer) class TverskyIndexKNNOptimizer(BaseOptimizer): default_tune_range = default_tune_range_knn.copy() + [ UniformSuggestion("alpha", 0, 2), UniformSuggestion("beta", 0, 2), ] recommender_class = TverskyIndexKNNRecommender _add_docstring(TverskyIndexKNNOptimizer) class CosineUserKNNOptimizer(BaseOptimizer): default_tune_range = default_tune_range_knn_with_weighting.copy() + [ CategoricalSuggestion("normalize", [False, True]) ] recommender_class = CosineUserKNNRecommender _add_docstring(CosineUserKNNOptimizer) class AsymmetricCosineUserKNNOptimizer(BaseOptimizer): default_tune_range = default_tune_range_knn_with_weighting + [ UniformSuggestion("alpha", 0, 1) ] recommender_class = AsymmetricCosineUserKNNRecommender _add_docstring(AsymmetricCosineUserKNNOptimizer) try: from ..recommenders.bpr import BPRFMRecommender class BPRFMOptimizer(BaseOptimizerWithEarlyStopping): default_tune_range = [ IntegerSuggestion("n_components", 4, 256), LogUniformSuggestion("item_alpha", 1e-9, 1e-2), LogUniformSuggestion("user_alpha", 1e-9, 1e-2), CategoricalSuggestion("loss", ["bpr", "warp"]), ] recommender_class = BPRFMRecommender _add_docstring(BPRFMOptimizer, _BaseOptimizerWithEarlyStoppingArgsString) except: pass try: from ..recommenders.multvae import MultVAERecommender class MultVAEOptimizer(BaseOptimizerWithEarlyStopping): default_tune_range = [ CategoricalSuggestion("dim_z", [32, 64, 128, 256]), CategoricalSuggestion("enc_hidden_dims", [128, 256, 512]), CategoricalSuggestion("kl_anneal_goal", [0.1, 0.2, 0.4]), ] recommender_class = MultVAERecommender _add_docstring(MultVAEOptimizer, _BaseOptimizerWithEarlyStoppingArgsString) except: warnings.warn("MultVAEOptimizer is not available.") pass
irspack/optimizers/_optimizers.py
import warnings from typing import List, Type from ..optimizers.base_optimizer import BaseOptimizer, BaseOptimizerWithEarlyStopping from ..parameter_tuning import ( CategoricalSuggestion, IntegerSuggestion, LogUniformSuggestion, Suggestion, UniformSuggestion, ) from ..recommenders import ( AsymmetricCosineKNNRecommender, AsymmetricCosineUserKNNRecommender, CosineKNNRecommender, CosineUserKNNRecommender, DenseSLIMRecommender, IALSRecommender, JaccardKNNRecommender, NMFRecommender, P3alphaRecommender, RP3betaRecommender, SLIMRecommender, TopPopRecommender, TruncatedSVDRecommender, TverskyIndexKNNRecommender, ) default_tune_range_knn = [ IntegerSuggestion("top_k", 4, 1000), UniformSuggestion("shrinkage", 0, 1000), ] default_tune_range_knn_with_weighting = [ IntegerSuggestion("top_k", 4, 1000), UniformSuggestion("shrinkage", 0, 1000), CategoricalSuggestion("feature_weighting", ["NONE", "TF_IDF", "BM_25"]), ] _BaseOptimizerArgsString = """Args: data (Union[scipy.sparse.csr_matrix, scipy.sparse.csc_matrix]): The train data. val_evaluator (Evaluator): The validation evaluator which measures the performance of the recommenders. logger (Optional[logging.Logger], optional) : The logger used during the optimization steps. Defaults to None. If ``None``, the default logger of irspack will be used. suggest_overwrite (List[Suggestion], optional) : Customizes (e.g. enlarging the parameter region or adding new parameters to be tuned) the default parameter search space defined by ``default_tune_range`` Defaults to list(). fixed_params (Dict[str, Any], optional): Fixed parameters passed to recommenders during the optimization procedure. If such a parameter exists in ``default_tune_range``, it will not be tuned. Defaults to dict(). """ _BaseOptimizerWithEarlyStoppingArgsString = """Args: data (Union[scipy.sparse.csr_matrix, scipy.sparse.csc_matrix]): The train data. val_evaluator (Evaluator): The validation evaluator which measures the performance of the recommenders. logger (Optional[logging.Logger], optional): The logger used during the optimization steps. Defaults to None. If ``None``, the default logger of irspack will be used. suggest_overwrite (List[Suggestion], optional): Customizes (e.g. enlarging the parameter region or adding new parameters to be tuned) the default parameter search space defined by ``default_tune_range`` Defaults to list(). fixed_params (Dict[str, Any], optional): Fixed parameters passed to recommenders during the optimization procedure. If such a parameter exists in ``default_tune_range``, it will not be tuned. Defaults to dict(). max_epoch (int, optional): The maximal number of epochs for the training. Defaults to 512. validate_epoch (int, optional): The frequency of validation score measurement. Defaults to 5. score_degradation_max (int, optional): Maximal number of allowed score degradation. Defaults to 5. Defaults to 5. """ def _add_docstring( cls: Type[BaseOptimizer], args: str = _BaseOptimizerArgsString ) -> None: if cls.default_tune_range: ranges = "" for suggest in cls.default_tune_range: ranges += f" - ``{suggest!r}``\n" ranges += "\n" tune_range = f"""The default tune range is {ranges}""" else: tune_range = " There is no tunable parameters." docs = f"""Optimizer class for :class:`irspack.recommenders.{cls.recommender_class.__name__}`. {tune_range} {args} """ cls.__doc__ = docs class TopPopOptimizer(BaseOptimizer): default_tune_range: List[Suggestion] = [] recommender_class = TopPopRecommender _add_docstring(TopPopOptimizer) class IALSOptimizer(BaseOptimizerWithEarlyStopping): default_tune_range = [ IntegerSuggestion("n_components", 4, 300), LogUniformSuggestion("alpha", 1, 100), LogUniformSuggestion("reg", 1e-10, 1e-2), ] recommender_class = IALSRecommender _add_docstring(IALSOptimizer, _BaseOptimizerWithEarlyStoppingArgsString) class P3alphaOptimizer(BaseOptimizer): default_tune_range = [ IntegerSuggestion("top_k", low=10, high=1000), CategoricalSuggestion("normalize_weight", [True, False]), ] recommender_class = P3alphaRecommender _add_docstring(P3alphaOptimizer) class DenseSLIMOptimizer(BaseOptimizer): default_tune_range = [LogUniformSuggestion("reg", 1, 1e4)] recommender_class = DenseSLIMRecommender _add_docstring(DenseSLIMOptimizer) class RP3betaOptimizer(BaseOptimizer): default_tune_range = [ IntegerSuggestion("top_k", 2, 1000), LogUniformSuggestion("beta", 1e-5, 5e-1), CategoricalSuggestion("normalize_weight", [True, False]), ] recommender_class = RP3betaRecommender _add_docstring(RP3betaOptimizer) class TruncatedSVDOptimizer(BaseOptimizer): default_tune_range = [IntegerSuggestion("n_components", 4, 512)] recommender_class = TruncatedSVDRecommender _add_docstring(TruncatedSVDOptimizer) class SLIMOptimizer(BaseOptimizer): default_tune_range = [ LogUniformSuggestion("alpha", 1e-5, 1), UniformSuggestion("l1_ratio", 0, 1), ] recommender_class = SLIMRecommender _add_docstring(SLIMOptimizer) class NMFOptimizer(BaseOptimizer): default_tune_range = [ IntegerSuggestion("n_components", 4, 512), LogUniformSuggestion("alpha", 1e-10, 1e-1), UniformSuggestion("l1_ratio", 0, 1), CategoricalSuggestion("beta_loss", ["frobenius", "kullback-leibler"]), ] recommender_class = NMFRecommender _add_docstring(NMFOptimizer) class CosineKNNOptimizer(BaseOptimizer): default_tune_range = default_tune_range_knn_with_weighting.copy() + [ CategoricalSuggestion("normalize", [False, True]) ] recommender_class = CosineKNNRecommender _add_docstring(CosineKNNOptimizer) class AsymmetricCosineKNNOptimizer(BaseOptimizer): default_tune_range = default_tune_range_knn_with_weighting + [ UniformSuggestion("alpha", 0, 1) ] recommender_class = AsymmetricCosineKNNRecommender _add_docstring(AsymmetricCosineKNNOptimizer) class JaccardKNNOptimizer(BaseOptimizer): default_tune_range = default_tune_range_knn.copy() recommender_class = JaccardKNNRecommender _add_docstring(JaccardKNNOptimizer) class TverskyIndexKNNOptimizer(BaseOptimizer): default_tune_range = default_tune_range_knn.copy() + [ UniformSuggestion("alpha", 0, 2), UniformSuggestion("beta", 0, 2), ] recommender_class = TverskyIndexKNNRecommender _add_docstring(TverskyIndexKNNOptimizer) class CosineUserKNNOptimizer(BaseOptimizer): default_tune_range = default_tune_range_knn_with_weighting.copy() + [ CategoricalSuggestion("normalize", [False, True]) ] recommender_class = CosineUserKNNRecommender _add_docstring(CosineUserKNNOptimizer) class AsymmetricCosineUserKNNOptimizer(BaseOptimizer): default_tune_range = default_tune_range_knn_with_weighting + [ UniformSuggestion("alpha", 0, 1) ] recommender_class = AsymmetricCosineUserKNNRecommender _add_docstring(AsymmetricCosineUserKNNOptimizer) try: from ..recommenders.bpr import BPRFMRecommender class BPRFMOptimizer(BaseOptimizerWithEarlyStopping): default_tune_range = [ IntegerSuggestion("n_components", 4, 256), LogUniformSuggestion("item_alpha", 1e-9, 1e-2), LogUniformSuggestion("user_alpha", 1e-9, 1e-2), CategoricalSuggestion("loss", ["bpr", "warp"]), ] recommender_class = BPRFMRecommender _add_docstring(BPRFMOptimizer, _BaseOptimizerWithEarlyStoppingArgsString) except: pass try: from ..recommenders.multvae import MultVAERecommender class MultVAEOptimizer(BaseOptimizerWithEarlyStopping): default_tune_range = [ CategoricalSuggestion("dim_z", [32, 64, 128, 256]), CategoricalSuggestion("enc_hidden_dims", [128, 256, 512]), CategoricalSuggestion("kl_anneal_goal", [0.1, 0.2, 0.4]), ] recommender_class = MultVAERecommender _add_docstring(MultVAEOptimizer, _BaseOptimizerWithEarlyStoppingArgsString) except: warnings.warn("MultVAEOptimizer is not available.") pass
0.870294
0.414899
import sys import time from nlp_toolkit.models import bi_lstm_attention from nlp_toolkit.models import Transformer from nlp_toolkit.models import textCNN, DPCNN from nlp_toolkit.trainer import Trainer from nlp_toolkit.utilities import logger from nlp_toolkit.sequence import BasicIterator from nlp_toolkit.data import Dataset from typing import List, Dict from copy import deepcopy from sklearn.metrics import classification_report # TODO # 1. evaluate func class Classifier(object): """ Classifier Model Zoos. Include following models: 1. TextCNN 2. DPCNN (Deep Pyramid CNN) 3. Bi-LSTM-Attention 4. Multi-Head-Self-Attention (Transformer) 5. HAN (Hierachical Attention Network) """ def __init__(self, model_name, dataset: Dataset, seq_type='bucket'): self.model_name = model_name self.dataset = dataset self.transformer = dataset.transformer if dataset.mode == 'train': self.config = self.dataset.config self.m_cfg = self.config['model'][self.model_name] self.seq_type = seq_type if seq_type == 'bucket': self.config['maxlen'] = None self.model = self.get_model() self.model_trainer = self.get_trainer() elif dataset.mode == 'predict' or dataset.mode == 'eval': pass else: logger.warning('invalid mode name. Current only support "train" "eval" "predict"') def get_model(self): if self.model_name == 'bi_lstm_att': model = bi_lstm_attention( nb_classes=self.config['nb_classes'], nb_tokens=self.config['nb_tokens'], maxlen=self.config['maxlen'], embedding_dim=self.config['embedding_dim'], embeddings=self.config['token_embeddings'], rnn_size=self.m_cfg['rnn_size'], attention_dim=self.m_cfg['attention_dim'], final_dropout_rate=self.m_cfg['final_drop_rate'], embed_dropout_rate=self.m_cfg['embed_drop_rate'], return_attention=self.m_cfg['return_att'] ) elif self.model_name == 'transformer': model = Transformer( nb_classes=self.config['nb_classes'], nb_tokens=self.config['nb_tokens'], maxlen=self.config['maxlen'], embedding_dim=self.config['embedding_dim'], embeddings=self.config['token_embeddings'], pos_embed=self.m_cfg['pos_embed'], nb_transformer=self.m_cfg['nb_transformer'], final_dropout_rate=self.m_cfg['final_drop_rate'], embed_dropout_rate=self.m_cfg['embed_drop_rate'] ) elif self.model_name == 'text_cnn': model = textCNN( nb_classes=self.config['nb_classes'], nb_tokens=self.config['nb_tokens'], maxlen=self.config['maxlen'], embedding_dim=self.config['embedding_dim'], embeddings=self.config['token_embeddings'], conv_kernel_size=self.m_cfg['conv_kernel_size'], pool_size=self.m_cfg['pool_size'], nb_filters=self.m_cfg['nb_filters'], fc_size=self.m_cfg['fc_size'], embed_dropout_rate=self.m_cfg['embed_drop_rate'] ) elif self.model_name == 'dpcnn': model = DPCNN( nb_classes=self.config['nb_classes'], nb_tokens=self.config['nb_tokens'], maxlen=self.config['maxlen'], embedding_dim=self.config['embedding_dim'], embeddings=self.config['token_embeddings'], region_kernel_size=self.m_cfg['region_kernel_size'], conv_kernel_size=self.m_cfg['conv_kernel_size'], pool_size=self.m_cfg['pool_size'], nb_filters=self.m_cfg['nb_filters'], repeat_time=self.m_cfg['repeat_time'], final_dropout_rate=self.m_cfg['final_drop_rate'], embed_dropout_rate=self.m_cfg['embed_drop_rate'] ) else: logger.warning('The model name ' + self.model_name + ' is unknown') model = None return model def get_trainer(self): t_cfg = self.config['train'] model_trainer = Trainer( self.model, model_name=self.model_name, task_type=self.config['task_type'], batch_size=t_cfg['batch_size'], max_epoch=t_cfg['epochs'], train_mode=t_cfg['train_mode'], fold_cnt=t_cfg['nb_fold'], test_size=t_cfg['test_size'], metric=['f1'], nb_bucket=t_cfg['nb_bucket'], patiences=t_cfg['patiences'] ) return model_trainer def train(self): if self.model_name == 'bi_lstm_att': return_att = self.m_cfg['return_att'] else: return_att = False return self.model_trainer.train( self.dataset.texts, self.dataset.labels, self.transformer, self.seq_type, return_att) def predict(self, x: Dict[str, List[List[str]]], batch_size=64, return_attention=False, return_prob=False): n_labels = len(self.transformer._label_vocab._id2token) x_c = deepcopy(x) start = time.time() x_len = [item[-1] for item in x_c['token']] x_c['token'] = [item[:-1] for item in x_c['token']] x_seq = BasicIterator('classification', self.transformer, x_c, batch_size=batch_size) result = self.model.model.predict_generator(x_seq) if return_prob: y_pred = result[:, :n_labels] else: y_pred = self.transformer.inverse_transform(result[:, :n_labels]) used_time = time.time() - start logger.info('predict {} samples used {:4.1f}s'.format( len(x['token']), used_time)) if result.shape[1] > n_labels and self.model_name == 'bi_lstm_att': attention = result[:, n_labels:] attention = [attention[idx][:l] for idx, l in enumerate(x_len)] return y_pred, attention else: return y_pred def evaluate(self, x: Dict[str, List[List[str]]], y: List[str], batch_size=64): n_labels = len(self.transformer._label_vocab._id2token) y = [item[0] for item in y] x_c = deepcopy(x) x_len = [item[-1] for item in x_c['token']] x_c['token'] = [item[:-1] for item in x_c['token']] x_seq = BasicIterator('classification', self.transformer, x_c, batch_size=batch_size) result = self.model.model.predict_generator(x_seq) result = result[:, :n_labels] y_pred = self.transformer.inverse_transform(result, lengths=x_len) print(classification_report(y, y_pred)) def load(self, weight_fname, para_fname): if self.model_name == 'bi_lstm_att': self.model = bi_lstm_attention.load(weight_fname, para_fname) elif self.model_name == 'transformer': self.model = Transformer.load(weight_fname, para_fname) elif self.model_name == 'text_cnn': self.model = textCNN.load(weight_fname, para_fname) elif self.model_name == 'dpcnn': self.model = DPCNN.load(weight_fname, para_fname) else: logger.warning('invalid model name') sys.exit()
nlp_toolkit/classifier.py
import sys import time from nlp_toolkit.models import bi_lstm_attention from nlp_toolkit.models import Transformer from nlp_toolkit.models import textCNN, DPCNN from nlp_toolkit.trainer import Trainer from nlp_toolkit.utilities import logger from nlp_toolkit.sequence import BasicIterator from nlp_toolkit.data import Dataset from typing import List, Dict from copy import deepcopy from sklearn.metrics import classification_report # TODO # 1. evaluate func class Classifier(object): """ Classifier Model Zoos. Include following models: 1. TextCNN 2. DPCNN (Deep Pyramid CNN) 3. Bi-LSTM-Attention 4. Multi-Head-Self-Attention (Transformer) 5. HAN (Hierachical Attention Network) """ def __init__(self, model_name, dataset: Dataset, seq_type='bucket'): self.model_name = model_name self.dataset = dataset self.transformer = dataset.transformer if dataset.mode == 'train': self.config = self.dataset.config self.m_cfg = self.config['model'][self.model_name] self.seq_type = seq_type if seq_type == 'bucket': self.config['maxlen'] = None self.model = self.get_model() self.model_trainer = self.get_trainer() elif dataset.mode == 'predict' or dataset.mode == 'eval': pass else: logger.warning('invalid mode name. Current only support "train" "eval" "predict"') def get_model(self): if self.model_name == 'bi_lstm_att': model = bi_lstm_attention( nb_classes=self.config['nb_classes'], nb_tokens=self.config['nb_tokens'], maxlen=self.config['maxlen'], embedding_dim=self.config['embedding_dim'], embeddings=self.config['token_embeddings'], rnn_size=self.m_cfg['rnn_size'], attention_dim=self.m_cfg['attention_dim'], final_dropout_rate=self.m_cfg['final_drop_rate'], embed_dropout_rate=self.m_cfg['embed_drop_rate'], return_attention=self.m_cfg['return_att'] ) elif self.model_name == 'transformer': model = Transformer( nb_classes=self.config['nb_classes'], nb_tokens=self.config['nb_tokens'], maxlen=self.config['maxlen'], embedding_dim=self.config['embedding_dim'], embeddings=self.config['token_embeddings'], pos_embed=self.m_cfg['pos_embed'], nb_transformer=self.m_cfg['nb_transformer'], final_dropout_rate=self.m_cfg['final_drop_rate'], embed_dropout_rate=self.m_cfg['embed_drop_rate'] ) elif self.model_name == 'text_cnn': model = textCNN( nb_classes=self.config['nb_classes'], nb_tokens=self.config['nb_tokens'], maxlen=self.config['maxlen'], embedding_dim=self.config['embedding_dim'], embeddings=self.config['token_embeddings'], conv_kernel_size=self.m_cfg['conv_kernel_size'], pool_size=self.m_cfg['pool_size'], nb_filters=self.m_cfg['nb_filters'], fc_size=self.m_cfg['fc_size'], embed_dropout_rate=self.m_cfg['embed_drop_rate'] ) elif self.model_name == 'dpcnn': model = DPCNN( nb_classes=self.config['nb_classes'], nb_tokens=self.config['nb_tokens'], maxlen=self.config['maxlen'], embedding_dim=self.config['embedding_dim'], embeddings=self.config['token_embeddings'], region_kernel_size=self.m_cfg['region_kernel_size'], conv_kernel_size=self.m_cfg['conv_kernel_size'], pool_size=self.m_cfg['pool_size'], nb_filters=self.m_cfg['nb_filters'], repeat_time=self.m_cfg['repeat_time'], final_dropout_rate=self.m_cfg['final_drop_rate'], embed_dropout_rate=self.m_cfg['embed_drop_rate'] ) else: logger.warning('The model name ' + self.model_name + ' is unknown') model = None return model def get_trainer(self): t_cfg = self.config['train'] model_trainer = Trainer( self.model, model_name=self.model_name, task_type=self.config['task_type'], batch_size=t_cfg['batch_size'], max_epoch=t_cfg['epochs'], train_mode=t_cfg['train_mode'], fold_cnt=t_cfg['nb_fold'], test_size=t_cfg['test_size'], metric=['f1'], nb_bucket=t_cfg['nb_bucket'], patiences=t_cfg['patiences'] ) return model_trainer def train(self): if self.model_name == 'bi_lstm_att': return_att = self.m_cfg['return_att'] else: return_att = False return self.model_trainer.train( self.dataset.texts, self.dataset.labels, self.transformer, self.seq_type, return_att) def predict(self, x: Dict[str, List[List[str]]], batch_size=64, return_attention=False, return_prob=False): n_labels = len(self.transformer._label_vocab._id2token) x_c = deepcopy(x) start = time.time() x_len = [item[-1] for item in x_c['token']] x_c['token'] = [item[:-1] for item in x_c['token']] x_seq = BasicIterator('classification', self.transformer, x_c, batch_size=batch_size) result = self.model.model.predict_generator(x_seq) if return_prob: y_pred = result[:, :n_labels] else: y_pred = self.transformer.inverse_transform(result[:, :n_labels]) used_time = time.time() - start logger.info('predict {} samples used {:4.1f}s'.format( len(x['token']), used_time)) if result.shape[1] > n_labels and self.model_name == 'bi_lstm_att': attention = result[:, n_labels:] attention = [attention[idx][:l] for idx, l in enumerate(x_len)] return y_pred, attention else: return y_pred def evaluate(self, x: Dict[str, List[List[str]]], y: List[str], batch_size=64): n_labels = len(self.transformer._label_vocab._id2token) y = [item[0] for item in y] x_c = deepcopy(x) x_len = [item[-1] for item in x_c['token']] x_c['token'] = [item[:-1] for item in x_c['token']] x_seq = BasicIterator('classification', self.transformer, x_c, batch_size=batch_size) result = self.model.model.predict_generator(x_seq) result = result[:, :n_labels] y_pred = self.transformer.inverse_transform(result, lengths=x_len) print(classification_report(y, y_pred)) def load(self, weight_fname, para_fname): if self.model_name == 'bi_lstm_att': self.model = bi_lstm_attention.load(weight_fname, para_fname) elif self.model_name == 'transformer': self.model = Transformer.load(weight_fname, para_fname) elif self.model_name == 'text_cnn': self.model = textCNN.load(weight_fname, para_fname) elif self.model_name == 'dpcnn': self.model = DPCNN.load(weight_fname, para_fname) else: logger.warning('invalid model name') sys.exit()
0.46223
0.199542
from airsim import * from game.car_simulator import CarSimulator from ml.model import DeepLearningModel from ml.additional.preprocessing import * from multiprocessing import Queue, Manager, Lock import datetime import glob import matplotlib.pyplot as plt class Environment(): ai_sim_car = None stop_driving = False lock = Lock() lap = None deep_learning_model = None ENVIRONMENT_PARAM_KEY = "env_params" MODEL_PARAM_KEY = "model_params" model_params = None # default values env_params = DictAttr( database_name="ai_driving", ai_car_sim_ip="127.0.0.3", ai_car_sim_port=41451, model_training_folder="./images/raw_data/", model_processed_folder="./images/preprocessed/", model_output_folder="./models/", data_batch_size=32, # Model params # model_image_shape = (1, 144, 256, 3), model_car_stage_shape=(1, 4), region_of_interest=[76, 135, 0, 255] ) trained_rotations = None hybrid_type = 0 def init_with_new_values(self, values): if self.ENVIRONMENT_PARAM_KEY in values: for key in values[self.ENVIRONMENT_PARAM_KEY]: if key in self.env_params: self.env_params[key] = values[self.ENVIRONMENT_PARAM_KEY][key] if self.MODEL_PARAM_KEY in values: self.model_params = values[self.MODEL_PARAM_KEY] def add_hybrid_type(self, hybrid_type): self.hybrid_type = hybrid_type def add_qml_rotations(self, qml_rotations): self.trained_rotations = qml_rotations def init_ai_car_sim(self): self.ai_sim_car = CarSimulator(self.env_params.ai_car_sim_ip, self.env_params.ai_car_sim_port) def connect_to_ai_sim(self): self.ai_sim_car.connect() def reset_ai_car(self): self.ai_sim_car.reset_car() def prepare_deep_learning_model(self, model_name=None, without_model=False): if not self.deep_learning_model: self.deep_learning_model = DeepLearningModel(self.env_params.model_processed_folder, self.env_params.model_output_folder, self.env_params.data_batch_size, self.trained_rotations, self.hybrid_type) if self.model_params: self.deep_learning_model.change_default_params(self.model_params) if not without_model: if model_name: self.deep_learning_model.load_model(model_name) else: if not without_model: if model_name: self.deep_learning_model.load_model(model_name) else: self.deep_learning_model.reset_model() def start_ai_track(self): print("Start ai track") self.init_ai_car_sim() self.ai_sim_car.connect() self.ai_sim_car.enable_api_control() self.ai_sim_car.reset_car() self.stop_driving = False shape_img_buf, region_of_interest = self.deep_learning_model.get_image_buf_shape_and_roi() image_buf = np.zeros(shape_img_buf) state_buf = np.zeros(self.env_params.model_car_stage_shape) index = 0 save_current=False # this flag should save each second timestamp crash_count = 0 start = datetime.datetime.now() while not self.stop_driving: index = index +1 if self.ai_sim_car.get_collision_info().has_collided: if crash_count > 1: self.stop_driving = True break else: crash_count = crash_count +1 car_state = self.ai_sim_car.get_car_state() img1d = self.ai_sim_car.get_images("0", ImageType.Scene, region_of_interest) if len(img1d) > 0: #prev_car_controls = self.ai_sim_car.get_previous_car_controls() car_controls = self.ai_sim_car.get_car_controls() image_buf[0] = img1d state_buf[0] = np.array([car_controls.steering, car_controls.throttle, car_controls.brake, car_state.speed]) result = self.deep_learning_model.predict_result(image_buf, state_buf) predicted_steering = result[0][0] new_steering = round(float(predicted_steering), 2) new_steering = new_steering #print("Predicted: " + str(predicted_steering) + " post_process:" + str(new_steering)) car_controls.steering = new_steering # Additional car stats new_throttle = 0 if -0.1 < car_controls.steering < 0.1: if car_state.speed < 4: new_throttle = 1.0 else: new_throttle = 0.0 else: if car_state.speed < 4: new_throttle = 1.0 else: new_throttle = 0.0 car_controls.throttle = new_throttle self.ai_sim_car.set_new_car_controls(car_controls) else: # No picture print("No picture!") prev_car_controls = self.ai_sim_car.get_previous_car_controls() self.ai_sim_car.set_new_car_controls(prev_car_controls) print("Count iterations: " + str(index)) print("Total time:" + str(round((datetime.datetime.now() - start).total_seconds(), 2))) self.ai_sim_car.disable_api_control() self.ai_sim_car.reset_car() self.ai_sim_car.close() def start_training_ai(self, training_folders=None, epoch=None, model_name=None): pre_processing = None if training_folders: pre_processing = PreProcess() pre_processing.prepare_training_data(training_folders, self.env_params.model_processed_folder, self.env_params.data_batch_size) else: pre_processing = PreProcess() pre_processing.prepare_training_data(self.env_params.model_training_folder, self.env_params.model_processed_folder, self.env_params.data_batch_size) pre_processing.start_processing() if model_name: self.prepare_deep_learning_model(model_name) else: self.prepare_deep_learning_model(without_model=True) self.deep_learning_model.start_training(epoch) def start_test(self, test_folder, original_model=None, output_plots_folder=None): if not test_folder: raise Exception("No test folder defined!") print("Start test") classic_model = None if original_model: classic_model = DeepLearningModel(self.env_params.model_processed_folder, self.env_params.model_output_folder, self.env_params.data_batch_size, self.trained_rotations, self.hybrid_type) if self.model_params: tmp_model_params = dict(self.model_params) tmp_model_params = DictAttr(tmp_model_params) tmp_model_params.hybrid = False classic_model.change_default_params(tmp_model_params) classic_model.load_model(original_model) shape_img_buf, region_of_interest = self.deep_learning_model.get_image_buf_shape_and_roi() image_buf = np.zeros(shape_img_buf) state_buf = np.zeros(self.env_params.model_car_stage_shape) image_folder = os.path.join(test_folder, "images") preprocess = PreProcess() preprocess.prepare_test_data([test_folder]) dataframe = preprocess.get_test_data() image_names = glob.glob(os.path.join(image_folder, "*.png")) for index, item in enumerate(read_images_from_path(image_names)): img1d = item[region_of_interest[0]:region_of_interest[1], region_of_interest[2]:region_of_interest[3], 0:3].astype(float)/255 filename = image_names[index].replace('\\', '/').split("/") filename = filename[len(filename)-1] car_state = dataframe[filename] user_steering = car_state[0][0] image_buf[0] = img1d state_buf[0] = np.array(car_state[1]) result = self.deep_learning_model.predict_result(image_buf, state_buf) predicted_steering = result[0][0] new_steering = round(float(predicted_steering), 2) #print("Predicted: " + str(predicted_steering) + " post_process:" + str(new_steering)) #print("Should predict: " + str(user_steering)) classic_results = None if classic_model: cl_result = classic_model.predict_result(image_buf, state_buf) classic_results = cl_result[0][0] classic_results = round(float(classic_results), 2) #print(classic_results) fig = plt.figure(figsize=(10, 3)) plt.axis('off') axs = fig.add_subplot(1, 3, 1) axs.title.set_text("Original Image") plt.imshow(item) # hybrid steering axs = fig.add_subplot(1, 3, 2) axs.title.set_text("Hybrid Steering") ai_steering = [0,new_steering] user_steering_data = [0,user_steering] ys = [0, 1] axs.plot(user_steering_data, ys, 'gray') axs.plot(ai_steering, ys, 'blue') axs.set_xticks([-1, 1]) axs.set_yticks([0, 1]) axs.set_ylim([0, 1]) axs.get_yaxis().get_major_formatter().labelOnlyBase = False axs.get_xaxis().get_major_formatter().labelOnlyBase = False # classic ai steering if classic_model: axs = fig.add_subplot(1, 3, 3) axs.title.set_text("Classic Steering") cl_ai_steering = [0, classic_results] user_steering_data = [0, user_steering] ys = [0, 1] axs.plot(user_steering_data, ys, 'gray') axs.plot(cl_ai_steering, ys, 'blue') axs.set_xticks([-1, 1]) axs.set_yticks([0, 1]) axs.set_ylim([0, 1]) axs.get_yaxis().get_major_formatter().labelOnlyBase = False axs.get_xaxis().get_major_formatter().labelOnlyBase = False if output_plots_folder: fig.savefig(os.path.join(output_plots_folder, str(index) + "_" + filename)) else: plt.show() plt.close() #break
game/environment.py
from airsim import * from game.car_simulator import CarSimulator from ml.model import DeepLearningModel from ml.additional.preprocessing import * from multiprocessing import Queue, Manager, Lock import datetime import glob import matplotlib.pyplot as plt class Environment(): ai_sim_car = None stop_driving = False lock = Lock() lap = None deep_learning_model = None ENVIRONMENT_PARAM_KEY = "env_params" MODEL_PARAM_KEY = "model_params" model_params = None # default values env_params = DictAttr( database_name="ai_driving", ai_car_sim_ip="127.0.0.3", ai_car_sim_port=41451, model_training_folder="./images/raw_data/", model_processed_folder="./images/preprocessed/", model_output_folder="./models/", data_batch_size=32, # Model params # model_image_shape = (1, 144, 256, 3), model_car_stage_shape=(1, 4), region_of_interest=[76, 135, 0, 255] ) trained_rotations = None hybrid_type = 0 def init_with_new_values(self, values): if self.ENVIRONMENT_PARAM_KEY in values: for key in values[self.ENVIRONMENT_PARAM_KEY]: if key in self.env_params: self.env_params[key] = values[self.ENVIRONMENT_PARAM_KEY][key] if self.MODEL_PARAM_KEY in values: self.model_params = values[self.MODEL_PARAM_KEY] def add_hybrid_type(self, hybrid_type): self.hybrid_type = hybrid_type def add_qml_rotations(self, qml_rotations): self.trained_rotations = qml_rotations def init_ai_car_sim(self): self.ai_sim_car = CarSimulator(self.env_params.ai_car_sim_ip, self.env_params.ai_car_sim_port) def connect_to_ai_sim(self): self.ai_sim_car.connect() def reset_ai_car(self): self.ai_sim_car.reset_car() def prepare_deep_learning_model(self, model_name=None, without_model=False): if not self.deep_learning_model: self.deep_learning_model = DeepLearningModel(self.env_params.model_processed_folder, self.env_params.model_output_folder, self.env_params.data_batch_size, self.trained_rotations, self.hybrid_type) if self.model_params: self.deep_learning_model.change_default_params(self.model_params) if not without_model: if model_name: self.deep_learning_model.load_model(model_name) else: if not without_model: if model_name: self.deep_learning_model.load_model(model_name) else: self.deep_learning_model.reset_model() def start_ai_track(self): print("Start ai track") self.init_ai_car_sim() self.ai_sim_car.connect() self.ai_sim_car.enable_api_control() self.ai_sim_car.reset_car() self.stop_driving = False shape_img_buf, region_of_interest = self.deep_learning_model.get_image_buf_shape_and_roi() image_buf = np.zeros(shape_img_buf) state_buf = np.zeros(self.env_params.model_car_stage_shape) index = 0 save_current=False # this flag should save each second timestamp crash_count = 0 start = datetime.datetime.now() while not self.stop_driving: index = index +1 if self.ai_sim_car.get_collision_info().has_collided: if crash_count > 1: self.stop_driving = True break else: crash_count = crash_count +1 car_state = self.ai_sim_car.get_car_state() img1d = self.ai_sim_car.get_images("0", ImageType.Scene, region_of_interest) if len(img1d) > 0: #prev_car_controls = self.ai_sim_car.get_previous_car_controls() car_controls = self.ai_sim_car.get_car_controls() image_buf[0] = img1d state_buf[0] = np.array([car_controls.steering, car_controls.throttle, car_controls.brake, car_state.speed]) result = self.deep_learning_model.predict_result(image_buf, state_buf) predicted_steering = result[0][0] new_steering = round(float(predicted_steering), 2) new_steering = new_steering #print("Predicted: " + str(predicted_steering) + " post_process:" + str(new_steering)) car_controls.steering = new_steering # Additional car stats new_throttle = 0 if -0.1 < car_controls.steering < 0.1: if car_state.speed < 4: new_throttle = 1.0 else: new_throttle = 0.0 else: if car_state.speed < 4: new_throttle = 1.0 else: new_throttle = 0.0 car_controls.throttle = new_throttle self.ai_sim_car.set_new_car_controls(car_controls) else: # No picture print("No picture!") prev_car_controls = self.ai_sim_car.get_previous_car_controls() self.ai_sim_car.set_new_car_controls(prev_car_controls) print("Count iterations: " + str(index)) print("Total time:" + str(round((datetime.datetime.now() - start).total_seconds(), 2))) self.ai_sim_car.disable_api_control() self.ai_sim_car.reset_car() self.ai_sim_car.close() def start_training_ai(self, training_folders=None, epoch=None, model_name=None): pre_processing = None if training_folders: pre_processing = PreProcess() pre_processing.prepare_training_data(training_folders, self.env_params.model_processed_folder, self.env_params.data_batch_size) else: pre_processing = PreProcess() pre_processing.prepare_training_data(self.env_params.model_training_folder, self.env_params.model_processed_folder, self.env_params.data_batch_size) pre_processing.start_processing() if model_name: self.prepare_deep_learning_model(model_name) else: self.prepare_deep_learning_model(without_model=True) self.deep_learning_model.start_training(epoch) def start_test(self, test_folder, original_model=None, output_plots_folder=None): if not test_folder: raise Exception("No test folder defined!") print("Start test") classic_model = None if original_model: classic_model = DeepLearningModel(self.env_params.model_processed_folder, self.env_params.model_output_folder, self.env_params.data_batch_size, self.trained_rotations, self.hybrid_type) if self.model_params: tmp_model_params = dict(self.model_params) tmp_model_params = DictAttr(tmp_model_params) tmp_model_params.hybrid = False classic_model.change_default_params(tmp_model_params) classic_model.load_model(original_model) shape_img_buf, region_of_interest = self.deep_learning_model.get_image_buf_shape_and_roi() image_buf = np.zeros(shape_img_buf) state_buf = np.zeros(self.env_params.model_car_stage_shape) image_folder = os.path.join(test_folder, "images") preprocess = PreProcess() preprocess.prepare_test_data([test_folder]) dataframe = preprocess.get_test_data() image_names = glob.glob(os.path.join(image_folder, "*.png")) for index, item in enumerate(read_images_from_path(image_names)): img1d = item[region_of_interest[0]:region_of_interest[1], region_of_interest[2]:region_of_interest[3], 0:3].astype(float)/255 filename = image_names[index].replace('\\', '/').split("/") filename = filename[len(filename)-1] car_state = dataframe[filename] user_steering = car_state[0][0] image_buf[0] = img1d state_buf[0] = np.array(car_state[1]) result = self.deep_learning_model.predict_result(image_buf, state_buf) predicted_steering = result[0][0] new_steering = round(float(predicted_steering), 2) #print("Predicted: " + str(predicted_steering) + " post_process:" + str(new_steering)) #print("Should predict: " + str(user_steering)) classic_results = None if classic_model: cl_result = classic_model.predict_result(image_buf, state_buf) classic_results = cl_result[0][0] classic_results = round(float(classic_results), 2) #print(classic_results) fig = plt.figure(figsize=(10, 3)) plt.axis('off') axs = fig.add_subplot(1, 3, 1) axs.title.set_text("Original Image") plt.imshow(item) # hybrid steering axs = fig.add_subplot(1, 3, 2) axs.title.set_text("Hybrid Steering") ai_steering = [0,new_steering] user_steering_data = [0,user_steering] ys = [0, 1] axs.plot(user_steering_data, ys, 'gray') axs.plot(ai_steering, ys, 'blue') axs.set_xticks([-1, 1]) axs.set_yticks([0, 1]) axs.set_ylim([0, 1]) axs.get_yaxis().get_major_formatter().labelOnlyBase = False axs.get_xaxis().get_major_formatter().labelOnlyBase = False # classic ai steering if classic_model: axs = fig.add_subplot(1, 3, 3) axs.title.set_text("Classic Steering") cl_ai_steering = [0, classic_results] user_steering_data = [0, user_steering] ys = [0, 1] axs.plot(user_steering_data, ys, 'gray') axs.plot(cl_ai_steering, ys, 'blue') axs.set_xticks([-1, 1]) axs.set_yticks([0, 1]) axs.set_ylim([0, 1]) axs.get_yaxis().get_major_formatter().labelOnlyBase = False axs.get_xaxis().get_major_formatter().labelOnlyBase = False if output_plots_folder: fig.savefig(os.path.join(output_plots_folder, str(index) + "_" + filename)) else: plt.show() plt.close() #break
0.214609
0.224087
import appdirs import json import os import re import requests import socket import sys import time from PyInquirer import prompt def main(): PRESETS_DIR = appdirs.user_data_dir("wialon_ips", "<NAME>") if not os.path.exists(PRESETS_DIR): os.makedirs(PRESETS_DIR) PRESETS_PATH = os.path.join(PRESETS_DIR, 'wialon_ips_presets.conf') if len(sys.argv) > 1 and sys.argv[1] == 'clear': try: os.remove(PRESETS_PATH) except: pass sys.exit() def endpoint_filter(endpoint): return endpoint.split()[0] DEFAULT_TRACK_URL = 'http://172.16.58.3:8000/wialon_ips/sample_track.txt' ENDPOINTS = { 'Wialon Hosting NL': '172.16.31.10', 'Wialon Hosting MSK': '172.16.17.32', 'Wialon Hosting USA': '192.168.3.11', 'Wialon Hosting TRACE': '192.168.3.11', 'Wialon Hosting TIG': '192.168.127.12', 'Wialon Hosting OLD': '172.16.17.32', 'Specify custom': 'Custom' } LAST_PRESETS = None LAST_CUSTOM_ENDPOINT = None LAST_UID = None LAST_SRC_URL = None LAST_SRC_PATH = None PRESET = None try: with open(PRESETS_PATH, 'r') as cf: conf = json.load(cf) if 'last_uid' in conf: LAST_UID = conf['last_uid'] if 'last_src_url' in conf: LAST_SRC_URL = conf['last_src_url'] if 'last_src_path' in conf: LAST_SRC_PATH = conf['last_src_path'] if 'last_custom_endpoint' in conf: LAST_CUSTOM_ENDPOINT = conf['last_custom_endpoint'] if 'presets' in conf and type(conf['presets']) is dict: LAST_PRESETS = conf['presets'] if len(LAST_PRESETS): load_preset = prompt(dict(message='Load from preset', type='list', choices=['no', 'yes'], name='load_preset'))['load_preset'] if load_preset == 'yes': choosen_preset = prompt(dict(message='Choose preset', type='list', choices=LAST_PRESETS, name='choosen_preset'))['choosen_preset'] if len(choosen_preset): PRESET = LAST_PRESETS[choosen_preset] except: pass SETTINGS = {} if PRESET: SETTINGS = PRESET else: # ASKING PROTOCOL SETTINGS['protocol'] = prompt(dict(message='Protocol', type='list', choices=['TCP', 'UDP'], name='protocol'))['protocol'] # ASKING ENDPOINT endpoint = prompt(dict(message='Choose endpoint', type='list', choices=[ENDPOINTS[ep] + ' (' + ep + ')' for ep in ENDPOINTS], \ name='ep', filter=endpoint_filter))['ep'] if endpoint == 'Custom': ep_q = dict(message='Enter endpoint', type='input', name='ep') if LAST_CUSTOM_ENDPOINT: ep_q['default'] = LAST_CUSTOM_ENDPOINT SETTINGS['endpoint'] = prompt(ep_q)['ep'] if len(SETTINGS['endpoint']): LAST_CUSTOM_ENDPOINT = SETTINGS['endpoint'] else: SETTINGS['endpoint'] = endpoint # ASKING PORT SETTINGS['port'] = int(prompt(dict(message='Port', type='input', default='20332', name='port'))['port']) # ASKING INTERVAL SETTINGS['interval'] = prompt(dict(message='Interval(seconds)', type='input', default='5', name='ival'))['ival'] # ASKING UID uid_q = dict(message='IMEI', type='input', name='uid') if LAST_UID: uid_q['default'] = LAST_UID SETTINGS['uid'] = prompt(uid_q)['uid'] if len(SETTINGS['uid']): LAST_UID = SETTINGS['uid'] # ASKING SRC SETTINGS['track_src_type'] = prompt(dict(message='Track source type', type='list', choices=['URL', 'File'], name='track_src_type'))['track_src_type'] src_q = dict(name='src', type='input') if SETTINGS['track_src_type'] == 'File': src_q['message'] = 'File path' if LAST_SRC_PATH: src_q['default'] = LAST_SRC_PATH SETTINGS['track_src'] = prompt(src_q)['src'] if len(SETTINGS['track_src']): LAST_SRC_PATH = SETTINGS['track_src'] else: src_q['message'] = 'Track URL' if LAST_SRC_URL: src_q['default'] = LAST_SRC_URL else: src_q['default'] = DEFAULT_TRACK_URL SETTINGS['track_src'] = prompt(src_q)['src'] if len(SETTINGS['track_src']): LAST_SRC_URL = SETTINGS['track_src'] try: PROTOCOL = SETTINGS['protocol'] ENDPOINT = SETTINGS['endpoint'] PORT = SETTINGS['port'] UID = SETTINGS['uid'] INTERVAL = SETTINGS['interval'] TRACK_SRC_TYPE = SETTINGS['track_src_type'] TRACK_SRC = SETTINGS['track_src'] except Exception as e: print('Settings are invalid: ' + str(e)) sys.exit() TRACK_DATA = None if TRACK_SRC_TYPE == 'File': try: with open(TRACK_SRC) as f: TRACK_DATA = f.readlines() except Exception as e: print('Failed to get track data from specified source {0} ({1}): {2}'.format(TRACK_SRC, TRACK_SRC_TYPE, e)) elif TRACK_SRC_TYPE == 'URL': try: r = requests.get(TRACK_SRC) TRACK_DATA = r.text.split() except Exception as e: print('Failed to get track data from specified source {0} ({1}): {2}'.format(TRACK_SRC, TRACK_SRC_TYPE, e)) if not TRACK_DATA: sys.exit() try: with open(PRESETS_PATH, 'w') as cf: new_config = dict() if LAST_UID: new_config['last_uid'] = LAST_UID if LAST_CUSTOM_ENDPOINT: new_config['last_custom_endpoint'] = LAST_CUSTOM_ENDPOINT if LAST_SRC_PATH: new_config['last_src_path'] = LAST_SRC_PATH if LAST_SRC_URL: new_config['last_src_url'] = LAST_SRC_URL new_presets = None if LAST_PRESETS: new_presets = LAST_PRESETS if not PRESET: save_to_preset = prompt(dict(message='Save as preset', type='list', choices=['no', 'yes'], name='answer'))['answer'] if save_to_preset == 'yes': preset_name = prompt(dict(message='New preset name', type='input', name='preset_name'))['preset_name'] if len(preset_name): new_presets = new_presets or dict() new_presets[preset_name] = SETTINGS if new_presets: new_config["presets"] = new_presets json.dump(new_config, cf) except Exception as e: print('Failed to save update config: ' + str(e)) def parse_line(input_line): res = re.search(r'(\d+.\d+),(?!A)(\D),(\d+.\d+),(\D)', input_line) lat1 = res.group(1) lat2 = res.group(2) lon1 = res.group(3) lon2 = res.group(4) return (lat1, lat2, lon1, lon2) msgs = [parse_line(line) for line in TRACK_DATA] if PROTOCOL == 'TCP': LOGIN_MESSAGE = b'#L#' LOGIN_MESSAGE = b''.join([LOGIN_MESSAGE, bytearray(UID, 'utf-8')]) LOGIN_MESSAGE = b''.join([LOGIN_MESSAGE, b';NA\r\n']) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ENDPOINT, PORT)) print('Connected to {0}'.format(s.getpeername())) print('Sending login message') sent = s.send(LOGIN_MESSAGE) data = s.recv(1024) if data.decode('utf-8').startswith('#AL#1'): print('Login Success. Sending messages...') else: print('Login Failed: ' + data.decode('utf-8')) sys.exit() while True: for msg in msgs: request = '#SD#NA;NA;{};{};{};{};140;0;100;6'.format(msg[0], msg[1], msg[2], msg[3]).encode('utf-8') + b'\r\n' bytes_sent = s.send(request) print(request) readen_data = s.recv(1024) print(readen_data) time.sleep(float(INTERVAL)) s.close() elif PROTOCOL == 'UDP': sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) while True: for msg in msgs: request = '{}#SD#NA;NA;{};{};{};{};140;0;100;6'.format(UID, msg[0], msg[1], msg[2], msg[3]) r = b''.join([bytearray(request, 'utf-8'), b'\r\n']) print(r) sock.sendto(r, (ENDPOINT, PORT)) # data = sock.recv(400) # print(data) time.sleep(float(INTERVAL)) if __name__ == "__main__": main()
wialon_ips.py
import appdirs import json import os import re import requests import socket import sys import time from PyInquirer import prompt def main(): PRESETS_DIR = appdirs.user_data_dir("wialon_ips", "<NAME>") if not os.path.exists(PRESETS_DIR): os.makedirs(PRESETS_DIR) PRESETS_PATH = os.path.join(PRESETS_DIR, 'wialon_ips_presets.conf') if len(sys.argv) > 1 and sys.argv[1] == 'clear': try: os.remove(PRESETS_PATH) except: pass sys.exit() def endpoint_filter(endpoint): return endpoint.split()[0] DEFAULT_TRACK_URL = 'http://172.16.58.3:8000/wialon_ips/sample_track.txt' ENDPOINTS = { 'Wialon Hosting NL': '172.16.31.10', 'Wialon Hosting MSK': '172.16.17.32', 'Wialon Hosting USA': '192.168.3.11', 'Wialon Hosting TRACE': '192.168.3.11', 'Wialon Hosting TIG': '192.168.127.12', 'Wialon Hosting OLD': '172.16.17.32', 'Specify custom': 'Custom' } LAST_PRESETS = None LAST_CUSTOM_ENDPOINT = None LAST_UID = None LAST_SRC_URL = None LAST_SRC_PATH = None PRESET = None try: with open(PRESETS_PATH, 'r') as cf: conf = json.load(cf) if 'last_uid' in conf: LAST_UID = conf['last_uid'] if 'last_src_url' in conf: LAST_SRC_URL = conf['last_src_url'] if 'last_src_path' in conf: LAST_SRC_PATH = conf['last_src_path'] if 'last_custom_endpoint' in conf: LAST_CUSTOM_ENDPOINT = conf['last_custom_endpoint'] if 'presets' in conf and type(conf['presets']) is dict: LAST_PRESETS = conf['presets'] if len(LAST_PRESETS): load_preset = prompt(dict(message='Load from preset', type='list', choices=['no', 'yes'], name='load_preset'))['load_preset'] if load_preset == 'yes': choosen_preset = prompt(dict(message='Choose preset', type='list', choices=LAST_PRESETS, name='choosen_preset'))['choosen_preset'] if len(choosen_preset): PRESET = LAST_PRESETS[choosen_preset] except: pass SETTINGS = {} if PRESET: SETTINGS = PRESET else: # ASKING PROTOCOL SETTINGS['protocol'] = prompt(dict(message='Protocol', type='list', choices=['TCP', 'UDP'], name='protocol'))['protocol'] # ASKING ENDPOINT endpoint = prompt(dict(message='Choose endpoint', type='list', choices=[ENDPOINTS[ep] + ' (' + ep + ')' for ep in ENDPOINTS], \ name='ep', filter=endpoint_filter))['ep'] if endpoint == 'Custom': ep_q = dict(message='Enter endpoint', type='input', name='ep') if LAST_CUSTOM_ENDPOINT: ep_q['default'] = LAST_CUSTOM_ENDPOINT SETTINGS['endpoint'] = prompt(ep_q)['ep'] if len(SETTINGS['endpoint']): LAST_CUSTOM_ENDPOINT = SETTINGS['endpoint'] else: SETTINGS['endpoint'] = endpoint # ASKING PORT SETTINGS['port'] = int(prompt(dict(message='Port', type='input', default='20332', name='port'))['port']) # ASKING INTERVAL SETTINGS['interval'] = prompt(dict(message='Interval(seconds)', type='input', default='5', name='ival'))['ival'] # ASKING UID uid_q = dict(message='IMEI', type='input', name='uid') if LAST_UID: uid_q['default'] = LAST_UID SETTINGS['uid'] = prompt(uid_q)['uid'] if len(SETTINGS['uid']): LAST_UID = SETTINGS['uid'] # ASKING SRC SETTINGS['track_src_type'] = prompt(dict(message='Track source type', type='list', choices=['URL', 'File'], name='track_src_type'))['track_src_type'] src_q = dict(name='src', type='input') if SETTINGS['track_src_type'] == 'File': src_q['message'] = 'File path' if LAST_SRC_PATH: src_q['default'] = LAST_SRC_PATH SETTINGS['track_src'] = prompt(src_q)['src'] if len(SETTINGS['track_src']): LAST_SRC_PATH = SETTINGS['track_src'] else: src_q['message'] = 'Track URL' if LAST_SRC_URL: src_q['default'] = LAST_SRC_URL else: src_q['default'] = DEFAULT_TRACK_URL SETTINGS['track_src'] = prompt(src_q)['src'] if len(SETTINGS['track_src']): LAST_SRC_URL = SETTINGS['track_src'] try: PROTOCOL = SETTINGS['protocol'] ENDPOINT = SETTINGS['endpoint'] PORT = SETTINGS['port'] UID = SETTINGS['uid'] INTERVAL = SETTINGS['interval'] TRACK_SRC_TYPE = SETTINGS['track_src_type'] TRACK_SRC = SETTINGS['track_src'] except Exception as e: print('Settings are invalid: ' + str(e)) sys.exit() TRACK_DATA = None if TRACK_SRC_TYPE == 'File': try: with open(TRACK_SRC) as f: TRACK_DATA = f.readlines() except Exception as e: print('Failed to get track data from specified source {0} ({1}): {2}'.format(TRACK_SRC, TRACK_SRC_TYPE, e)) elif TRACK_SRC_TYPE == 'URL': try: r = requests.get(TRACK_SRC) TRACK_DATA = r.text.split() except Exception as e: print('Failed to get track data from specified source {0} ({1}): {2}'.format(TRACK_SRC, TRACK_SRC_TYPE, e)) if not TRACK_DATA: sys.exit() try: with open(PRESETS_PATH, 'w') as cf: new_config = dict() if LAST_UID: new_config['last_uid'] = LAST_UID if LAST_CUSTOM_ENDPOINT: new_config['last_custom_endpoint'] = LAST_CUSTOM_ENDPOINT if LAST_SRC_PATH: new_config['last_src_path'] = LAST_SRC_PATH if LAST_SRC_URL: new_config['last_src_url'] = LAST_SRC_URL new_presets = None if LAST_PRESETS: new_presets = LAST_PRESETS if not PRESET: save_to_preset = prompt(dict(message='Save as preset', type='list', choices=['no', 'yes'], name='answer'))['answer'] if save_to_preset == 'yes': preset_name = prompt(dict(message='New preset name', type='input', name='preset_name'))['preset_name'] if len(preset_name): new_presets = new_presets or dict() new_presets[preset_name] = SETTINGS if new_presets: new_config["presets"] = new_presets json.dump(new_config, cf) except Exception as e: print('Failed to save update config: ' + str(e)) def parse_line(input_line): res = re.search(r'(\d+.\d+),(?!A)(\D),(\d+.\d+),(\D)', input_line) lat1 = res.group(1) lat2 = res.group(2) lon1 = res.group(3) lon2 = res.group(4) return (lat1, lat2, lon1, lon2) msgs = [parse_line(line) for line in TRACK_DATA] if PROTOCOL == 'TCP': LOGIN_MESSAGE = b'#L#' LOGIN_MESSAGE = b''.join([LOGIN_MESSAGE, bytearray(UID, 'utf-8')]) LOGIN_MESSAGE = b''.join([LOGIN_MESSAGE, b';NA\r\n']) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ENDPOINT, PORT)) print('Connected to {0}'.format(s.getpeername())) print('Sending login message') sent = s.send(LOGIN_MESSAGE) data = s.recv(1024) if data.decode('utf-8').startswith('#AL#1'): print('Login Success. Sending messages...') else: print('Login Failed: ' + data.decode('utf-8')) sys.exit() while True: for msg in msgs: request = '#SD#NA;NA;{};{};{};{};140;0;100;6'.format(msg[0], msg[1], msg[2], msg[3]).encode('utf-8') + b'\r\n' bytes_sent = s.send(request) print(request) readen_data = s.recv(1024) print(readen_data) time.sleep(float(INTERVAL)) s.close() elif PROTOCOL == 'UDP': sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) while True: for msg in msgs: request = '{}#SD#NA;NA;{};{};{};{};140;0;100;6'.format(UID, msg[0], msg[1], msg[2], msg[3]) r = b''.join([bytearray(request, 'utf-8'), b'\r\n']) print(r) sock.sendto(r, (ENDPOINT, PORT)) # data = sock.recv(400) # print(data) time.sleep(float(INTERVAL)) if __name__ == "__main__": main()
0.0453
0.056705
from abc import abstractmethod from os.path import join import numpy as np from scipy.integrate import trapz from scipy.interpolate import UnivariateSpline import prince_cr.config as config class PhotonField(object): """Base class for constructing target photon densities. Derived classes have to implement the method :func:`PhotonField.get_photon_densities`. """ @abstractmethod def get_photon_density(self, E, z): raise Exception('Base class method called accidentally.') class CombinedPhotonField(PhotonField): """Class to combine (sum) several models, which inherit from :class:`PhotonField`. This class is useful when constructing a realistic photon spectrum, which is typically a superposition of CMB and CIB. The list of models can be passed to the constructor or each model can be added separately using the :func:`add_model`. Args: list_of_classes_and_args: Can be either list of classes or list of tuples (class, args) """ def __init__(self, list_of_classes_and_args): self.model_list = [] for arg in list_of_classes_and_args: cl, cl_arg = None, None if type(arg) not in [tuple, list]: cl = arg cl_arg = [] else: cl = arg[0] cl_arg = arg[1:] self.model_list.append(cl(*cl_arg)) def add_model(self, model_class, model_args=()): """Adds a model class to the combination. """ self.model_list.append(model_class(*model_args)) def get_photon_density(self, E, z): """Returns the redshift-scaled number density of photons as a sum of different models. Args: z (float): redshift E (float): photon energy (GeV) Returns: float: CMB photon spectrum in :math:`{\\rm GeV}}^{-1} {\\rm cm}}^{-3}` """ E = np.atleast_1d(E) res = np.sum([model.get_photon_density(E, z) for model in self.model_list], axis=0) return res class FlatPhotonSpectrum(PhotonField): """Constant photon density for testing. """ def get_photon_density(self, E, z): """Returns the redshift-scaled number density of CMB photons Args: z (float): redshift E (float): photon energy (GeV) Returns: float: CMB photon spectrum in :math:`{\\rm GeV}}^{-1} {\\rm cm}}^{-3}` """ # density at z = 0 nlocal = np.ones_like(E, dtype='double') * 1e12 #nlocal = E**-1 * 1e12 return (1. + z)**2 * nlocal class CMBPhotonSpectrum(PhotonField): """Redshift-scaled number density of CMB photons In the CMB frame (equivalent to the observer's frame). Normalisation from Planck's spectrum. The scaling goes as :math:`n(E,z) = (1+z)^3 n(E/(1+z), z = 0)`. The CMB spectrum is a blackbody spectrum with the present-day temperature T0 = 2.725 K. Ref.: <NAME>, <NAME>, and <NAME>, Phys. Rev. D 79, 083009 (2009) [0902.3993] """ def get_photon_density(self, E, z): """Returns the redshift-scaled number density of CMB photons Args: z (float): redshift E (float): photon energy (GeV) Returns: float: CMB photon spectrum in :math:`{\\rm GeV}}^{-1} {\\rm cm}}^{-3}` """ pref = 1.31868e40 # 1/pi^2/(hbar*c)^3 [GeV^-3 cm^-3] Ered = E / (1. + z) # density at z = 0, for energy E / (1 + z); ECMB = kB * T0 # Call exp only for values within dynamic range of the function eratio = Ered / config.E_CMB exp_range = eratio < 709. # This is the limit for 64 bits nlocal = np.zeros_like(Ered) pref *= (1. + z)**2 # Normalize nlocal[exp_range] = pref * Ered[exp_range]**2 / (np.exp(eratio[exp_range]) - 1.0) del exp_range return nlocal class EBLSplined2D(PhotonField): def __init__(self): self.simple_scaling = None self.int2d = None def get_photon_density(self, E, z): """Returns the redshift-scaled number density of CIB photons Accepts scalar, vector and matrix arguments. Args: z (float): redshift E (float): photon energy (GeV) Returns: float: CMB photon spectrum in :math:`{\\rm GeV}}^{-1} {\\rm cm}}^{-3}` """ # pylint:disable=not-callable if self.simple_scaling: Ered = E / (1. + z) nlocal = self.int2d(Ered, 0., assume_sorted=True) nz = self.int2d(Ered, z, assume_sorted=True) scale = trapz(nz,Ered) / trapz(nlocal,Ered) / (1+z)**3 # print(scale) return (1. + z)**2 * nlocal * scale else: return self.int2d(E, z, assume_sorted=True) class CIBFranceschini2D(EBLSplined2D): """CIB model "1" by Fraceschini et al. CIB photon distribution for z = 0...2. Requires availability of an `scipy.interp2d` object file `data/CIB_franceschini_int2D.ppo`. Ref.: <NAME> et al., Astron. Astrphys. 487, 837 (2008) [arXiv:0805.1841] """ def __init__(self, simple_scaling=False): from prince_cr.data import db_handler self.int2d = db_handler.ebl_spline('Francescini2008','base') self.simple_scaling = simple_scaling class CIBInoue2D(EBLSplined2D): """CIB model "2" by Inoue et al. CIB photon distribution for z = 0...10. Requires availability of an `scipy.interp2d` object file `data/CIB_inoue_int2D.ppo`. A low and high variation of the "third-population" component are also available, by passing Ref.: Y. Inoue et al. [arXiv:1212.1683] """ def __init__(self, model='base', simple_scaling=False): from prince_cr.data import db_handler assert model in ['base', 'upper', 'lower'] self.int2d = db_handler.ebl_spline('Inoue2013', model) self.simple_scaling = simple_scaling class CIBGilmore2D(EBLSplined2D): """CIB model "3" by Gilmore et al. CIB photon distribution for z = 0...7. Requires availability of an `scipy.interp2d` object file `data/CIB_gilmore_int2D.ppo`. Note: Currently uses the fixed model from the reference as standard, for the fiducial model, change the 'model' keyword Ref.: <NAME> et al., MNRAS Soc. 422, 3189 (2012) [arXiv:1104.0671] """ def __init__(self, model='fiducial', simple_scaling=False): from prince_cr.data import db_handler assert model in ['fixed', 'fiducial'] self.int2d = db_handler.ebl_spline('Gilmore2011', model) self.simple_scaling = simple_scaling class CIBDominguez2D(EBLSplined2D): """CIB model "3" by Gilmore et al. CIB photon distribution for z = 0...2. Requires availability of an `scipy.interp2d` object file `data/CIB_dominguez_int2D.ppo`. Note: The class contains an interpolators for the upper and lower limits, which are not yet accessable through a function Ref.: <NAME> et al., MNRAS 410, 2556 (2011) [arXiv:1104.0671] """ def __init__(self, model='base', simple_scaling=False): from prince_cr.data import db_handler assert model in ['base', 'upper', 'lower'] self.int2d = db_handler.ebl_spline('Dominguez2010', model) self.simple_scaling = simple_scaling class CIBFranceschiniZ0(PhotonField): """CIB model "1" by Fraceschini et al. CIB photon distribution at z=0. Ref.: <NAME> et al., Astron. Astrphys. 487, 837 (2008) [arXiv:0805.1841] """ def __init__(self): self.E = np.array([ 1.00000000e-15, 1.46217717e-12, 2.48885732e-12, 3.54813389e-12, 4.97737085e-12, 7.31139083e-12, 8.87156012e-12, 1.12979591e-11, 1.38038426e-11, 1.65958691e-11, 1.77418948e-11, 2.07014135e-11, 3.10455959e-11, 4.13999675e-11, 4.97737085e-11, 6.22300285e-11, 8.27942164e-11, 1.03609601e-10, 1.38102010e-10, 1.55417529e-10, 1.85609414e-10, 2.14387767e-10, 2.75613191e-10, 3.37831390e-10, 4.17637993e-10, 7.31307454e-10, 9.56400953e-10, 1.24299677e-09, 1.55417529e-09, 2.25995608e-09, 3.10813590e-09, 6.21584248e-09, 1.00000000e+01 ]) self.ngamma = np.array([ 1.00000000e+06, 7.91224998e+10, 1.78114797e+11, 2.17470323e+11, 1.87326837e+11, 1.16654098e+11, 7.52488730e+10, 3.74541547e+10, 1.93508479e+10, 1.01765366e+10, 7.91407205e+09, 5.01880128e+09, 1.23026877e+09, 5.61047976e+08, 3.23593657e+08, 2.10377844e+08, 1.08893009e+08, 5.19517283e+07, 2.69649736e+07, 2.26725308e+07, 2.03422974e+07, 1.70529689e+07, 1.41807761e+07, 1.28617481e+07, 1.10458718e+07, 5.57057467e+06, 3.36790630e+06, 1.85152679e+06, 9.67163727e+05, 3.19815862e+05, 9.27897490e+04, 1.09774129e+04, 1.00000000e-29 ]) self.spl_ngamma = UnivariateSpline(self.E, self.ngamma, k=1, s=0) def get_photon_density(self, E, z): """Returns the redshift-scaled number density of CMB photons Args: z (float): redshift E (float): photon energy (GeV) Returns: float: CMB photon spectrum in :math:`{\\rm GeV}}^{-1} {\\rm cm}}^{-3}` """ if z > 0: raise Exception(self.__class__.__name__ + 'get_photon_density(): ' + 'Redshift z > 0 not supported by this class') return self.spl_ngamma(E, assume_sorted=True) class CIBSteckerZ0(PhotonField): """CIB model "1" by Stecker et al. CIB photon distribution at z=0. Ref.: <NAME>., Astrophys. J. 648, 774 (2006) [astro-ph/0510449] """ def __init__(self): self.E = np.array([ 3.30673963e-12, 3.66859694e-12, 4.01143722e-12, 4.32016168e-12, 4.72389244e-12, 5.16416369e-12, 5.73059874e-12, 6.26469598e-12, 6.95184371e-12, 7.48858908e-12, 8.06491882e-12, 8.81860723e-12, 9.49729657e-12, 9.93116048e-12, 1.05390145e-11, 1.13527219e-11, 1.25979535e-11, 1.43979281e-11, 1.59771753e-11, 1.77296434e-11, 2.08785339e-11, 2.35125645e-11, 2.81060620e-11, 3.07255737e-11, 3.46098725e-11, 3.83972393e-11, 4.52168183e-11, 5.24686633e-11, 6.55692174e-11, 8.19407623e-11, 9.36698878e-11, 1.07075473e-10, 1.24231005e-10, 1.42010351e-10, 1.67232237e-10, 1.91165713e-10, 2.05911214e-10, 2.25117885e-10, 2.46116086e-10, 2.81339039e-10, 3.21595527e-10, 3.46409665e-10, 3.78712814e-10, 4.07934090e-10, 4.45974472e-10, 4.80374560e-10, 5.17440002e-10, 5.49123462e-10, 5.82760356e-10, 6.18457699e-10, 6.76129679e-10, 7.28299480e-10, 7.96214349e-10, 8.32530207e-10, 9.10164726e-10, 9.95061676e-10, 1.10415489e-09, 1.17179057e-09, 1.26217624e-09, 1.33949162e-09, 1.42151026e-09, 1.53119323e-09, 1.64930130e-09, 1.85750504e-09, 2.12334224e-09, 2.28712552e-09, 2.50046051e-09, 2.69333268e-09, 2.85831442e-09, 3.07878952e-09, 3.31627090e-09, 3.57215257e-09, 3.79087968e-09, 4.66766845e-09, 5.10305207e-09, 5.57904674e-09, 6.19070344e-09, 7.07668721e-09, 8.33354913e-09, 1.04145378e-08, 1.15563317e-08, 1.22642219e-08, 1.28233058e-08, 1.32102185e-08, 1.40194185e-08, 1.44444164e-08 ]) self.ngamma = np.array([ 1.85951634e+11, 1.76116481e+11, 1.69277798e+11, 1.57180983e+11, 1.43747401e+11, 1.28262588e+11, 1.10001853e+11, 9.33899193e+10, 7.62254505e+10, 6.40766798e+10, 5.38641735e+10, 4.35211137e+10, 3.56861749e+10, 3.09100708e+10, 2.57276430e+10, 2.05825889e+10, 1.48354253e+10, 9.87802225e+09, 6.94592357e+09, 5.00691248e+09, 2.93042088e+09, 2.13348700e+09, 1.29285554e+09, 1.07082869e+09, 8.19275561e+08, 6.68574795e+08, 5.01498918e+08, 3.91399260e+08, 2.63250982e+08, 1.77063890e+08, 1.43783814e+08, 1.13899023e+08, 8.88934988e+07, 7.21855052e+07, 5.69023235e+07, 4.73685401e+07, 4.28982919e+07, 3.82771858e+07, 3.41530898e+07, 2.84308602e+07, 2.36673700e+07, 2.14338408e+07, 1.86560630e+07, 1.68958482e+07, 1.47061842e+07, 1.29921193e+07, 1.14775713e+07, 1.10868967e+07, 1.04469616e+07, 9.84396362e+06, 8.78354843e+06, 7.95463030e+06, 7.09773859e+06, 6.62186008e+06, 5.76381456e+06, 5.01683711e+06, 4.19681669e+06, 3.76313674e+06, 3.32452804e+06, 2.98098644e+06, 2.67294486e+06, 2.30350946e+06, 1.93646655e+06, 1.48156258e+06, 1.11681182e+06, 9.38858192e+05, 7.58577575e+05, 6.22085387e+05, 5.44126654e+05, 4.35281290e+05, 3.56960367e+05, 3.00088947e+05, 2.43652011e+05, 1.33045442e+05, 9.97860887e+04, 7.48393488e+04, 5.39473356e+04, 3.50404762e+04, 1.90370653e+04, 8.19200106e+03, 5.34724398e+03, 4.23525925e+03, 3.66783677e+03, 3.22403687e+03, 2.55358313e+03, 2.24460538e+03 ]) self.spl_ngamma = UnivariateSpline(self.E, self.ngamma, k=1, s=0) def get_photon_density(self, E, z): """Returns the redshift-scaled number density of CMB photons Args: z (float): redshift E (float): photon energy (GeV) Returns: float: CMB photon spectrum in :math:`{\\rm GeV}}^{-1} {\\rm cm}}^{-3}` """ if z > 0: raise Exception(self.__class__.__name__ + 'get_photon_density(): ' + 'Redshift z > 0 not supported by this class') return self.spl_ngamma(E, assume_sorted=True) if __name__ == "__main__": import matplotlib.pyplot as plt erange = np.logspace(-20, -6, 100) cmb = CMBPhotonSpectrum() inoue = CIBInoue2D() fig, ax = plt.subplots(1, 1, figsize=(4, 3)) ax.loglog( erange, erange * cmb.get_photon_density(erange, z=0.), ls='-', lw=2, color='k') ax.set_ylim(1e-9, 1e3) # ax.fill_between(erange, CMB_photon_spectrum(erange, z=0.), # CMB_photon_spectrum(erange, z=6.), color='b', alpha=0.3) ax.set_ylabel(r'$\epsilon$ d$n/$d$\epsilon$ cm$^{-3}$') ax.set_xlabel(r'Photon energy $\epsilon$ (GeV)') fig, ax = plt.subplots(1, 1, figsize=(4, 3)) ax.loglog( erange, erange * inoue.get_photon_density(erange, z=0.), ls='-', lw=2, color='k') ax.set_ylabel(r'$\epsilon$ d$n/$d$\epsilon$ cm$^{-3}$') ax.set_xlabel(r'Photon energy $\epsilon$ (GeV)') mcomb = CombinedPhotonField([CMBPhotonSpectrum, CIBInoue2D]) fig, ax = plt.subplots(1, 1, figsize=(4, 3)) ax.loglog( erange, erange * mcomb.get_photon_density(erange, 0.), ls='-', lw=2, color='k') ax.fill_between( erange, erange * mcomb.get_photon_density(erange, 0.), erange * mcomb.get_photon_density(erange, 6.), color='r', alpha=0.3) ax.set_ylabel(r'$\epsilon$ d$n/$d$\epsilon$ cm$^{-3}$') ax.set_xlabel(r'Photon energy $\epsilon$ (GeV)') plt.show()
prince_cr/photonfields.py
from abc import abstractmethod from os.path import join import numpy as np from scipy.integrate import trapz from scipy.interpolate import UnivariateSpline import prince_cr.config as config class PhotonField(object): """Base class for constructing target photon densities. Derived classes have to implement the method :func:`PhotonField.get_photon_densities`. """ @abstractmethod def get_photon_density(self, E, z): raise Exception('Base class method called accidentally.') class CombinedPhotonField(PhotonField): """Class to combine (sum) several models, which inherit from :class:`PhotonField`. This class is useful when constructing a realistic photon spectrum, which is typically a superposition of CMB and CIB. The list of models can be passed to the constructor or each model can be added separately using the :func:`add_model`. Args: list_of_classes_and_args: Can be either list of classes or list of tuples (class, args) """ def __init__(self, list_of_classes_and_args): self.model_list = [] for arg in list_of_classes_and_args: cl, cl_arg = None, None if type(arg) not in [tuple, list]: cl = arg cl_arg = [] else: cl = arg[0] cl_arg = arg[1:] self.model_list.append(cl(*cl_arg)) def add_model(self, model_class, model_args=()): """Adds a model class to the combination. """ self.model_list.append(model_class(*model_args)) def get_photon_density(self, E, z): """Returns the redshift-scaled number density of photons as a sum of different models. Args: z (float): redshift E (float): photon energy (GeV) Returns: float: CMB photon spectrum in :math:`{\\rm GeV}}^{-1} {\\rm cm}}^{-3}` """ E = np.atleast_1d(E) res = np.sum([model.get_photon_density(E, z) for model in self.model_list], axis=0) return res class FlatPhotonSpectrum(PhotonField): """Constant photon density for testing. """ def get_photon_density(self, E, z): """Returns the redshift-scaled number density of CMB photons Args: z (float): redshift E (float): photon energy (GeV) Returns: float: CMB photon spectrum in :math:`{\\rm GeV}}^{-1} {\\rm cm}}^{-3}` """ # density at z = 0 nlocal = np.ones_like(E, dtype='double') * 1e12 #nlocal = E**-1 * 1e12 return (1. + z)**2 * nlocal class CMBPhotonSpectrum(PhotonField): """Redshift-scaled number density of CMB photons In the CMB frame (equivalent to the observer's frame). Normalisation from Planck's spectrum. The scaling goes as :math:`n(E,z) = (1+z)^3 n(E/(1+z), z = 0)`. The CMB spectrum is a blackbody spectrum with the present-day temperature T0 = 2.725 K. Ref.: <NAME>, <NAME>, and <NAME>, Phys. Rev. D 79, 083009 (2009) [0902.3993] """ def get_photon_density(self, E, z): """Returns the redshift-scaled number density of CMB photons Args: z (float): redshift E (float): photon energy (GeV) Returns: float: CMB photon spectrum in :math:`{\\rm GeV}}^{-1} {\\rm cm}}^{-3}` """ pref = 1.31868e40 # 1/pi^2/(hbar*c)^3 [GeV^-3 cm^-3] Ered = E / (1. + z) # density at z = 0, for energy E / (1 + z); ECMB = kB * T0 # Call exp only for values within dynamic range of the function eratio = Ered / config.E_CMB exp_range = eratio < 709. # This is the limit for 64 bits nlocal = np.zeros_like(Ered) pref *= (1. + z)**2 # Normalize nlocal[exp_range] = pref * Ered[exp_range]**2 / (np.exp(eratio[exp_range]) - 1.0) del exp_range return nlocal class EBLSplined2D(PhotonField): def __init__(self): self.simple_scaling = None self.int2d = None def get_photon_density(self, E, z): """Returns the redshift-scaled number density of CIB photons Accepts scalar, vector and matrix arguments. Args: z (float): redshift E (float): photon energy (GeV) Returns: float: CMB photon spectrum in :math:`{\\rm GeV}}^{-1} {\\rm cm}}^{-3}` """ # pylint:disable=not-callable if self.simple_scaling: Ered = E / (1. + z) nlocal = self.int2d(Ered, 0., assume_sorted=True) nz = self.int2d(Ered, z, assume_sorted=True) scale = trapz(nz,Ered) / trapz(nlocal,Ered) / (1+z)**3 # print(scale) return (1. + z)**2 * nlocal * scale else: return self.int2d(E, z, assume_sorted=True) class CIBFranceschini2D(EBLSplined2D): """CIB model "1" by Fraceschini et al. CIB photon distribution for z = 0...2. Requires availability of an `scipy.interp2d` object file `data/CIB_franceschini_int2D.ppo`. Ref.: <NAME> et al., Astron. Astrphys. 487, 837 (2008) [arXiv:0805.1841] """ def __init__(self, simple_scaling=False): from prince_cr.data import db_handler self.int2d = db_handler.ebl_spline('Francescini2008','base') self.simple_scaling = simple_scaling class CIBInoue2D(EBLSplined2D): """CIB model "2" by Inoue et al. CIB photon distribution for z = 0...10. Requires availability of an `scipy.interp2d` object file `data/CIB_inoue_int2D.ppo`. A low and high variation of the "third-population" component are also available, by passing Ref.: Y. Inoue et al. [arXiv:1212.1683] """ def __init__(self, model='base', simple_scaling=False): from prince_cr.data import db_handler assert model in ['base', 'upper', 'lower'] self.int2d = db_handler.ebl_spline('Inoue2013', model) self.simple_scaling = simple_scaling class CIBGilmore2D(EBLSplined2D): """CIB model "3" by Gilmore et al. CIB photon distribution for z = 0...7. Requires availability of an `scipy.interp2d` object file `data/CIB_gilmore_int2D.ppo`. Note: Currently uses the fixed model from the reference as standard, for the fiducial model, change the 'model' keyword Ref.: <NAME> et al., MNRAS Soc. 422, 3189 (2012) [arXiv:1104.0671] """ def __init__(self, model='fiducial', simple_scaling=False): from prince_cr.data import db_handler assert model in ['fixed', 'fiducial'] self.int2d = db_handler.ebl_spline('Gilmore2011', model) self.simple_scaling = simple_scaling class CIBDominguez2D(EBLSplined2D): """CIB model "3" by Gilmore et al. CIB photon distribution for z = 0...2. Requires availability of an `scipy.interp2d` object file `data/CIB_dominguez_int2D.ppo`. Note: The class contains an interpolators for the upper and lower limits, which are not yet accessable through a function Ref.: <NAME> et al., MNRAS 410, 2556 (2011) [arXiv:1104.0671] """ def __init__(self, model='base', simple_scaling=False): from prince_cr.data import db_handler assert model in ['base', 'upper', 'lower'] self.int2d = db_handler.ebl_spline('Dominguez2010', model) self.simple_scaling = simple_scaling class CIBFranceschiniZ0(PhotonField): """CIB model "1" by Fraceschini et al. CIB photon distribution at z=0. Ref.: <NAME> et al., Astron. Astrphys. 487, 837 (2008) [arXiv:0805.1841] """ def __init__(self): self.E = np.array([ 1.00000000e-15, 1.46217717e-12, 2.48885732e-12, 3.54813389e-12, 4.97737085e-12, 7.31139083e-12, 8.87156012e-12, 1.12979591e-11, 1.38038426e-11, 1.65958691e-11, 1.77418948e-11, 2.07014135e-11, 3.10455959e-11, 4.13999675e-11, 4.97737085e-11, 6.22300285e-11, 8.27942164e-11, 1.03609601e-10, 1.38102010e-10, 1.55417529e-10, 1.85609414e-10, 2.14387767e-10, 2.75613191e-10, 3.37831390e-10, 4.17637993e-10, 7.31307454e-10, 9.56400953e-10, 1.24299677e-09, 1.55417529e-09, 2.25995608e-09, 3.10813590e-09, 6.21584248e-09, 1.00000000e+01 ]) self.ngamma = np.array([ 1.00000000e+06, 7.91224998e+10, 1.78114797e+11, 2.17470323e+11, 1.87326837e+11, 1.16654098e+11, 7.52488730e+10, 3.74541547e+10, 1.93508479e+10, 1.01765366e+10, 7.91407205e+09, 5.01880128e+09, 1.23026877e+09, 5.61047976e+08, 3.23593657e+08, 2.10377844e+08, 1.08893009e+08, 5.19517283e+07, 2.69649736e+07, 2.26725308e+07, 2.03422974e+07, 1.70529689e+07, 1.41807761e+07, 1.28617481e+07, 1.10458718e+07, 5.57057467e+06, 3.36790630e+06, 1.85152679e+06, 9.67163727e+05, 3.19815862e+05, 9.27897490e+04, 1.09774129e+04, 1.00000000e-29 ]) self.spl_ngamma = UnivariateSpline(self.E, self.ngamma, k=1, s=0) def get_photon_density(self, E, z): """Returns the redshift-scaled number density of CMB photons Args: z (float): redshift E (float): photon energy (GeV) Returns: float: CMB photon spectrum in :math:`{\\rm GeV}}^{-1} {\\rm cm}}^{-3}` """ if z > 0: raise Exception(self.__class__.__name__ + 'get_photon_density(): ' + 'Redshift z > 0 not supported by this class') return self.spl_ngamma(E, assume_sorted=True) class CIBSteckerZ0(PhotonField): """CIB model "1" by Stecker et al. CIB photon distribution at z=0. Ref.: <NAME>., Astrophys. J. 648, 774 (2006) [astro-ph/0510449] """ def __init__(self): self.E = np.array([ 3.30673963e-12, 3.66859694e-12, 4.01143722e-12, 4.32016168e-12, 4.72389244e-12, 5.16416369e-12, 5.73059874e-12, 6.26469598e-12, 6.95184371e-12, 7.48858908e-12, 8.06491882e-12, 8.81860723e-12, 9.49729657e-12, 9.93116048e-12, 1.05390145e-11, 1.13527219e-11, 1.25979535e-11, 1.43979281e-11, 1.59771753e-11, 1.77296434e-11, 2.08785339e-11, 2.35125645e-11, 2.81060620e-11, 3.07255737e-11, 3.46098725e-11, 3.83972393e-11, 4.52168183e-11, 5.24686633e-11, 6.55692174e-11, 8.19407623e-11, 9.36698878e-11, 1.07075473e-10, 1.24231005e-10, 1.42010351e-10, 1.67232237e-10, 1.91165713e-10, 2.05911214e-10, 2.25117885e-10, 2.46116086e-10, 2.81339039e-10, 3.21595527e-10, 3.46409665e-10, 3.78712814e-10, 4.07934090e-10, 4.45974472e-10, 4.80374560e-10, 5.17440002e-10, 5.49123462e-10, 5.82760356e-10, 6.18457699e-10, 6.76129679e-10, 7.28299480e-10, 7.96214349e-10, 8.32530207e-10, 9.10164726e-10, 9.95061676e-10, 1.10415489e-09, 1.17179057e-09, 1.26217624e-09, 1.33949162e-09, 1.42151026e-09, 1.53119323e-09, 1.64930130e-09, 1.85750504e-09, 2.12334224e-09, 2.28712552e-09, 2.50046051e-09, 2.69333268e-09, 2.85831442e-09, 3.07878952e-09, 3.31627090e-09, 3.57215257e-09, 3.79087968e-09, 4.66766845e-09, 5.10305207e-09, 5.57904674e-09, 6.19070344e-09, 7.07668721e-09, 8.33354913e-09, 1.04145378e-08, 1.15563317e-08, 1.22642219e-08, 1.28233058e-08, 1.32102185e-08, 1.40194185e-08, 1.44444164e-08 ]) self.ngamma = np.array([ 1.85951634e+11, 1.76116481e+11, 1.69277798e+11, 1.57180983e+11, 1.43747401e+11, 1.28262588e+11, 1.10001853e+11, 9.33899193e+10, 7.62254505e+10, 6.40766798e+10, 5.38641735e+10, 4.35211137e+10, 3.56861749e+10, 3.09100708e+10, 2.57276430e+10, 2.05825889e+10, 1.48354253e+10, 9.87802225e+09, 6.94592357e+09, 5.00691248e+09, 2.93042088e+09, 2.13348700e+09, 1.29285554e+09, 1.07082869e+09, 8.19275561e+08, 6.68574795e+08, 5.01498918e+08, 3.91399260e+08, 2.63250982e+08, 1.77063890e+08, 1.43783814e+08, 1.13899023e+08, 8.88934988e+07, 7.21855052e+07, 5.69023235e+07, 4.73685401e+07, 4.28982919e+07, 3.82771858e+07, 3.41530898e+07, 2.84308602e+07, 2.36673700e+07, 2.14338408e+07, 1.86560630e+07, 1.68958482e+07, 1.47061842e+07, 1.29921193e+07, 1.14775713e+07, 1.10868967e+07, 1.04469616e+07, 9.84396362e+06, 8.78354843e+06, 7.95463030e+06, 7.09773859e+06, 6.62186008e+06, 5.76381456e+06, 5.01683711e+06, 4.19681669e+06, 3.76313674e+06, 3.32452804e+06, 2.98098644e+06, 2.67294486e+06, 2.30350946e+06, 1.93646655e+06, 1.48156258e+06, 1.11681182e+06, 9.38858192e+05, 7.58577575e+05, 6.22085387e+05, 5.44126654e+05, 4.35281290e+05, 3.56960367e+05, 3.00088947e+05, 2.43652011e+05, 1.33045442e+05, 9.97860887e+04, 7.48393488e+04, 5.39473356e+04, 3.50404762e+04, 1.90370653e+04, 8.19200106e+03, 5.34724398e+03, 4.23525925e+03, 3.66783677e+03, 3.22403687e+03, 2.55358313e+03, 2.24460538e+03 ]) self.spl_ngamma = UnivariateSpline(self.E, self.ngamma, k=1, s=0) def get_photon_density(self, E, z): """Returns the redshift-scaled number density of CMB photons Args: z (float): redshift E (float): photon energy (GeV) Returns: float: CMB photon spectrum in :math:`{\\rm GeV}}^{-1} {\\rm cm}}^{-3}` """ if z > 0: raise Exception(self.__class__.__name__ + 'get_photon_density(): ' + 'Redshift z > 0 not supported by this class') return self.spl_ngamma(E, assume_sorted=True) if __name__ == "__main__": import matplotlib.pyplot as plt erange = np.logspace(-20, -6, 100) cmb = CMBPhotonSpectrum() inoue = CIBInoue2D() fig, ax = plt.subplots(1, 1, figsize=(4, 3)) ax.loglog( erange, erange * cmb.get_photon_density(erange, z=0.), ls='-', lw=2, color='k') ax.set_ylim(1e-9, 1e3) # ax.fill_between(erange, CMB_photon_spectrum(erange, z=0.), # CMB_photon_spectrum(erange, z=6.), color='b', alpha=0.3) ax.set_ylabel(r'$\epsilon$ d$n/$d$\epsilon$ cm$^{-3}$') ax.set_xlabel(r'Photon energy $\epsilon$ (GeV)') fig, ax = plt.subplots(1, 1, figsize=(4, 3)) ax.loglog( erange, erange * inoue.get_photon_density(erange, z=0.), ls='-', lw=2, color='k') ax.set_ylabel(r'$\epsilon$ d$n/$d$\epsilon$ cm$^{-3}$') ax.set_xlabel(r'Photon energy $\epsilon$ (GeV)') mcomb = CombinedPhotonField([CMBPhotonSpectrum, CIBInoue2D]) fig, ax = plt.subplots(1, 1, figsize=(4, 3)) ax.loglog( erange, erange * mcomb.get_photon_density(erange, 0.), ls='-', lw=2, color='k') ax.fill_between( erange, erange * mcomb.get_photon_density(erange, 0.), erange * mcomb.get_photon_density(erange, 6.), color='r', alpha=0.3) ax.set_ylabel(r'$\epsilon$ d$n/$d$\epsilon$ cm$^{-3}$') ax.set_xlabel(r'Photon energy $\epsilon$ (GeV)') plt.show()
0.892563
0.468669
import ctypes from . import run_solo_function from . import DataPair, masked_op from . import aliases se_copy_bad_flags = aliases['copy_bad_flags'] def copy_bad_flags(input_list_data, bad, dgi_clip_gate=None, boundary_mask=None): """ Gives an updated mask based on values in input_list_data that are bad. If input_list_data[i] == bad -> flags[i] = True else flags[i] = False Args: input_list_data: A list containing float data, bad: A float that represents a missing/invalid data point, (optional) dgi_clip_gate: An integer determines the end of the ray (default: length of input_list) (optional) boundary_mask: Defines region over which operations will be done. (default: all True). Returns: Numpy masked array: Contains an array of data, mask, and fill_value of results. Throws: ValueError: if input_list and input_boundary_mask are not equal in size, """ args = { "data" : DataPair.DataTypeValue(ctypes.POINTER(ctypes.c_float), input_list_data), "nGates" : DataPair.DataTypeValue(ctypes.c_size_t, None), "bad" : DataPair.DataTypeValue(ctypes.c_float, bad), "dgi_clip_gate" : DataPair.DataTypeValue(ctypes.c_size_t, dgi_clip_gate), "boundary_mask" : DataPair.DataTypeValue(ctypes.POINTER(ctypes.c_bool), boundary_mask), "bad_flag_mask" : DataPair.DataTypeValue(ctypes.POINTER(ctypes.c_bool), [False]*len(input_list_data)), } return run_solo_function(se_copy_bad_flags, args) def copy_bad_flags_masked(masked_array, boundary_mask=None): """ Gives an updated mask based on values in input_list_data that are bad. Args: masked_array: A numpy masked array data structure, Returns: Numpy masked array Throws: ModuleNotFoundError: if numpy is not installed AttributeError: if masked_array arg is not a numpy masked array. """ return masked_op.masked_func(copy_bad_flags, masked_array, boundary_mask = boundary_mask, usesBadFlags=True)
src/pysolo/solo_functions/flags/solo_copy_bad_flags.py
import ctypes from . import run_solo_function from . import DataPair, masked_op from . import aliases se_copy_bad_flags = aliases['copy_bad_flags'] def copy_bad_flags(input_list_data, bad, dgi_clip_gate=None, boundary_mask=None): """ Gives an updated mask based on values in input_list_data that are bad. If input_list_data[i] == bad -> flags[i] = True else flags[i] = False Args: input_list_data: A list containing float data, bad: A float that represents a missing/invalid data point, (optional) dgi_clip_gate: An integer determines the end of the ray (default: length of input_list) (optional) boundary_mask: Defines region over which operations will be done. (default: all True). Returns: Numpy masked array: Contains an array of data, mask, and fill_value of results. Throws: ValueError: if input_list and input_boundary_mask are not equal in size, """ args = { "data" : DataPair.DataTypeValue(ctypes.POINTER(ctypes.c_float), input_list_data), "nGates" : DataPair.DataTypeValue(ctypes.c_size_t, None), "bad" : DataPair.DataTypeValue(ctypes.c_float, bad), "dgi_clip_gate" : DataPair.DataTypeValue(ctypes.c_size_t, dgi_clip_gate), "boundary_mask" : DataPair.DataTypeValue(ctypes.POINTER(ctypes.c_bool), boundary_mask), "bad_flag_mask" : DataPair.DataTypeValue(ctypes.POINTER(ctypes.c_bool), [False]*len(input_list_data)), } return run_solo_function(se_copy_bad_flags, args) def copy_bad_flags_masked(masked_array, boundary_mask=None): """ Gives an updated mask based on values in input_list_data that are bad. Args: masked_array: A numpy masked array data structure, Returns: Numpy masked array Throws: ModuleNotFoundError: if numpy is not installed AttributeError: if masked_array arg is not a numpy masked array. """ return masked_op.masked_func(copy_bad_flags, masked_array, boundary_mask = boundary_mask, usesBadFlags=True)
0.844601
0.409545
import sys import io import time import pprint input_txt = """ 100 """ sys.stdin = io.StringIO(input_txt);input() #sys.stdin = open('in.test') start_time = time.time() # copy the below part and paste to the submission form. # ---------function------------ import math from collections import defaultdict def is_prime(n: int)-> bool: if n == 2: return True if n < 2 or n % 2 == 0: return False # when n is a prime number # x^(n-1) ≡ 1 (mod n) return pow(2, (n-1), n) == 1 def prime_factorize(n: int): prime_factors = [] range_max = int(n //2) + 1 for i in range(2, range_max): if not is_prime(i): continue while True: div, mod = divmod(n, i) if mod == 0: prime_factors.append(i) n = div else: break if n == 1: break prime_factors.append(n) return prime_factors prime_factors_dict = {0: {}} def main(): n = int(input()) for i in range(1,n+1): prime_factors = prime_factorize(i) this_prime_factors = defaultdict(int) for pm in prime_factors: this_prime_factors[pm] += 1 for k, v in prime_factors_dict[i-1].items(): this_prime_factors[k] += v prime_factors_dict[i] = this_prime_factors this_prime_factors = prime_factors_dict[n] prime_factors_list = sorted(list(filter(lambda x:x[0] != 1, this_prime_factors.items()))) cnt_mt_74times = len(list(filter(lambda x: x[1] >= 74, prime_factors_list))) cnt_mt_24times = len(list(filter(lambda x: x[1] >= 24, prime_factors_list))) cnt_mt_14times = len(list(filter(lambda x: x[1] >= 14, prime_factors_list))) cnt_mt_4times = len(list(filter(lambda x: x[1] >= 4, prime_factors_list))) cnt_mt_2times = len(list(filter(lambda x: x[1] >= 2, prime_factors_list))) ans_cnt = 0 # q^74 ans_cnt += cnt_mt_74times # q^24 * p^2 ans_cnt += cnt_mt_24times * (cnt_mt_2times - 1) # q^14 * p^4 ans_cnt += cnt_mt_14times * (cnt_mt_4times - 1) # q^4 * p^4 * r^2 ans_cnt += cnt_mt_4times * (cnt_mt_4times - 1) // 2 * (cnt_mt_2times - 2) print(ans_cnt) return main() # ----------------------------- print("elapsed:", time.time() - start_time) sys.stdin = sys.__stdin__
python/ABC114/ABC114_D.py
import sys import io import time import pprint input_txt = """ 100 """ sys.stdin = io.StringIO(input_txt);input() #sys.stdin = open('in.test') start_time = time.time() # copy the below part and paste to the submission form. # ---------function------------ import math from collections import defaultdict def is_prime(n: int)-> bool: if n == 2: return True if n < 2 or n % 2 == 0: return False # when n is a prime number # x^(n-1) ≡ 1 (mod n) return pow(2, (n-1), n) == 1 def prime_factorize(n: int): prime_factors = [] range_max = int(n //2) + 1 for i in range(2, range_max): if not is_prime(i): continue while True: div, mod = divmod(n, i) if mod == 0: prime_factors.append(i) n = div else: break if n == 1: break prime_factors.append(n) return prime_factors prime_factors_dict = {0: {}} def main(): n = int(input()) for i in range(1,n+1): prime_factors = prime_factorize(i) this_prime_factors = defaultdict(int) for pm in prime_factors: this_prime_factors[pm] += 1 for k, v in prime_factors_dict[i-1].items(): this_prime_factors[k] += v prime_factors_dict[i] = this_prime_factors this_prime_factors = prime_factors_dict[n] prime_factors_list = sorted(list(filter(lambda x:x[0] != 1, this_prime_factors.items()))) cnt_mt_74times = len(list(filter(lambda x: x[1] >= 74, prime_factors_list))) cnt_mt_24times = len(list(filter(lambda x: x[1] >= 24, prime_factors_list))) cnt_mt_14times = len(list(filter(lambda x: x[1] >= 14, prime_factors_list))) cnt_mt_4times = len(list(filter(lambda x: x[1] >= 4, prime_factors_list))) cnt_mt_2times = len(list(filter(lambda x: x[1] >= 2, prime_factors_list))) ans_cnt = 0 # q^74 ans_cnt += cnt_mt_74times # q^24 * p^2 ans_cnt += cnt_mt_24times * (cnt_mt_2times - 1) # q^14 * p^4 ans_cnt += cnt_mt_14times * (cnt_mt_4times - 1) # q^4 * p^4 * r^2 ans_cnt += cnt_mt_4times * (cnt_mt_4times - 1) // 2 * (cnt_mt_2times - 2) print(ans_cnt) return main() # ----------------------------- print("elapsed:", time.time() - start_time) sys.stdin = sys.__stdin__
0.138113
0.278128
import random import numpy as np from tqdm import tqdm import gensim import time import pkg_resources def parallel_generate_walks(d_graph: dict, global_walk_length: int, num_walks: int, cpu_num: int, sampling_strategy: dict = None, num_walks_key: str = None, walk_length_key: str = None, neighbors_key: str = None, probabilities_key: str = None, first_travel_key: str = None, seed: int = None, verbosity: int = 1) -> list: """ Generates the random walks which will be used as the skip-gram input. :return: List of walks. Each walk is a list of nodes. """ np.random.seed(seed) walks = list() if verbosity > 1: pbar = tqdm(total=num_walks, desc='Generating walks (CPU: {})'.format(cpu_num)) for n_walk in range(num_walks): # Update progress bar if verbosity > 1: pbar.update(1) # Shuffle the nodes shuffled_nodes = list(d_graph.keys()) random.shuffle(shuffled_nodes) # Start a random walk from every node for source in shuffled_nodes: # Skip nodes with specific num_walks if source in sampling_strategy and \ num_walks_key in sampling_strategy[source] and \ sampling_strategy[source][num_walks_key] <= n_walk: continue # Start walk walk = [source] # Calculate walk length if source in sampling_strategy: walk_length = sampling_strategy[source].get(walk_length_key, global_walk_length) else: walk_length = global_walk_length # Perform walk while len(walk) < walk_length: walk_options = d_graph[walk[-1]].get(neighbors_key, None) # Skip dead end nodes if not walk_options: break if len(walk) == 1: # For the first step probabilities = d_graph[walk[-1]][first_travel_key] walk_to = np.random.choice(walk_options, size=1, p=probabilities)[0] else: probabilities = d_graph[walk[-1]][probabilities_key][walk[-2]] walk_to = np.random.choice(walk_options, size=1, p=probabilities)[0] walk.append(walk_to) walk = list(map(str, walk)) # Convert all to strings walks.append(walk) if verbosity > 1: pbar.close() return walks def get_hash(astring): ''' Returns consistent values to the word2vec model to ensure reproducibility. Replace python's inconsistent hashing function (notice this is not a real hashing function but it will work for the current use). ''' return int(astring) def parallel_learn_embeddings(walks_file, word2vec_kws, nonzero_indices, num_nodes, cpu_num, verbosity): """ Fit the node2vec model on the sampled walks and returns the learned parameters. :return: A dictionary with the w and w' parameters and the final training loss. """ if verbosity > 1: s_time = time.time() model = gensim.models.Word2Vec(corpus_file=walks_file, hashfxn = get_hash, **word2vec_kws) # The word2vec algorithm does not preserve the nodes order, so we should sort it gensim_version = pkg_resources.get_distribution("gensim").version if gensim_version > '4.0.0': nodes_unordered = np.array([int(node) for node in model.wv.index_to_key]) else: nodes_unordered = np.array([int(node) for node in model.wv.index2word]) sorting_indices = np.argsort(nodes_unordered) # initiate W and W' embed_dims = word2vec_kws['vector_size'] if 'vector_size' in word2vec_kws else word2vec_kws['size'] w = np.empty((num_nodes, embed_dims)) w_apos = np.empty((embed_dims, num_nodes)) # get the trained matrices for the non-zero connected nodes w[nonzero_indices, :] = model.wv.vectors[sorting_indices, :] if pkg_resources.get_distribution("gensim").version >= '4.0.0': w_apos[:, nonzero_indices] = model.syn1neg.T[:, sorting_indices] else: w_apos[:, nonzero_indices] = model.trainables.syn1neg.T[:, sorting_indices] # set random values for the zero connected nodes if len(nonzero_indices) < num_nodes: zero_indices = np.ones((num_nodes), dtype = bool) zero_indices[nonzero_indices] = 0 w[zero_indices, :] = np.random.uniform(low=-0.5, high=0.5, \ size=(int(zero_indices.sum()), embed_dims)) / embed_dims w_apos[:, zero_indices] = np.random.uniform(low=-0.5, high=0.5, \ size=(embed_dims, int(zero_indices.sum()))) / embed_dims training_loss = model.get_latest_training_loss() if verbosity > 1: print('Done training the word2vec model ', cpu_num, 'in {:.4f} seconds.'.format(time.time() - s_time)) return {'w': w, 'w_apos': w_apos, 'training_loss': training_loss}
cepy/parallel.py
import random import numpy as np from tqdm import tqdm import gensim import time import pkg_resources def parallel_generate_walks(d_graph: dict, global_walk_length: int, num_walks: int, cpu_num: int, sampling_strategy: dict = None, num_walks_key: str = None, walk_length_key: str = None, neighbors_key: str = None, probabilities_key: str = None, first_travel_key: str = None, seed: int = None, verbosity: int = 1) -> list: """ Generates the random walks which will be used as the skip-gram input. :return: List of walks. Each walk is a list of nodes. """ np.random.seed(seed) walks = list() if verbosity > 1: pbar = tqdm(total=num_walks, desc='Generating walks (CPU: {})'.format(cpu_num)) for n_walk in range(num_walks): # Update progress bar if verbosity > 1: pbar.update(1) # Shuffle the nodes shuffled_nodes = list(d_graph.keys()) random.shuffle(shuffled_nodes) # Start a random walk from every node for source in shuffled_nodes: # Skip nodes with specific num_walks if source in sampling_strategy and \ num_walks_key in sampling_strategy[source] and \ sampling_strategy[source][num_walks_key] <= n_walk: continue # Start walk walk = [source] # Calculate walk length if source in sampling_strategy: walk_length = sampling_strategy[source].get(walk_length_key, global_walk_length) else: walk_length = global_walk_length # Perform walk while len(walk) < walk_length: walk_options = d_graph[walk[-1]].get(neighbors_key, None) # Skip dead end nodes if not walk_options: break if len(walk) == 1: # For the first step probabilities = d_graph[walk[-1]][first_travel_key] walk_to = np.random.choice(walk_options, size=1, p=probabilities)[0] else: probabilities = d_graph[walk[-1]][probabilities_key][walk[-2]] walk_to = np.random.choice(walk_options, size=1, p=probabilities)[0] walk.append(walk_to) walk = list(map(str, walk)) # Convert all to strings walks.append(walk) if verbosity > 1: pbar.close() return walks def get_hash(astring): ''' Returns consistent values to the word2vec model to ensure reproducibility. Replace python's inconsistent hashing function (notice this is not a real hashing function but it will work for the current use). ''' return int(astring) def parallel_learn_embeddings(walks_file, word2vec_kws, nonzero_indices, num_nodes, cpu_num, verbosity): """ Fit the node2vec model on the sampled walks and returns the learned parameters. :return: A dictionary with the w and w' parameters and the final training loss. """ if verbosity > 1: s_time = time.time() model = gensim.models.Word2Vec(corpus_file=walks_file, hashfxn = get_hash, **word2vec_kws) # The word2vec algorithm does not preserve the nodes order, so we should sort it gensim_version = pkg_resources.get_distribution("gensim").version if gensim_version > '4.0.0': nodes_unordered = np.array([int(node) for node in model.wv.index_to_key]) else: nodes_unordered = np.array([int(node) for node in model.wv.index2word]) sorting_indices = np.argsort(nodes_unordered) # initiate W and W' embed_dims = word2vec_kws['vector_size'] if 'vector_size' in word2vec_kws else word2vec_kws['size'] w = np.empty((num_nodes, embed_dims)) w_apos = np.empty((embed_dims, num_nodes)) # get the trained matrices for the non-zero connected nodes w[nonzero_indices, :] = model.wv.vectors[sorting_indices, :] if pkg_resources.get_distribution("gensim").version >= '4.0.0': w_apos[:, nonzero_indices] = model.syn1neg.T[:, sorting_indices] else: w_apos[:, nonzero_indices] = model.trainables.syn1neg.T[:, sorting_indices] # set random values for the zero connected nodes if len(nonzero_indices) < num_nodes: zero_indices = np.ones((num_nodes), dtype = bool) zero_indices[nonzero_indices] = 0 w[zero_indices, :] = np.random.uniform(low=-0.5, high=0.5, \ size=(int(zero_indices.sum()), embed_dims)) / embed_dims w_apos[:, zero_indices] = np.random.uniform(low=-0.5, high=0.5, \ size=(embed_dims, int(zero_indices.sum()))) / embed_dims training_loss = model.get_latest_training_loss() if verbosity > 1: print('Done training the word2vec model ', cpu_num, 'in {:.4f} seconds.'.format(time.time() - s_time)) return {'w': w, 'w_apos': w_apos, 'training_loss': training_loss}
0.683947
0.364891
from boto3 import Session from boto3.s3.transfer import S3Transfer from .compression.uncompressfile import UncompressFile from .encryption.decryptedfile import DecryptedFile, EncryptionContextMismatch import os from ..cli import cli_library class RestoreFile: def __init__(self, s3_bucket, timestamp, backup_file, restore_path, intermediate_path='/tmp/'): self.s3_bucket = s3_bucket self.timestamp = timestamp self.backup_file = backup_file self.restore_path = restore_path self.intermediate_path = intermediate_path if intermediate_path is not None else '/tmp/' def restore(self, kms_key, aws_profile, encryption_context=None): self._download(aws_profile) self._decrypt(kms_key, aws_profile, encryption_context) self._uncompress() def restore_path(self): return self.saved_encrypted_path def cleanup(self): os.remove(self.saved_encrypted_path) def _download(self, aws_profile): cli_library.echo('Downloading {}...'.format(self.backup_file)) s3_object = self.timestamp + '/' + self.backup_file + '.cipher' s3_client = Session(profile_name=aws_profile).client('s3') s3_object_size = s3_client.head_object(Bucket=self.s3_bucket, Key=s3_object)['ContentLength'] cli_library.create_progressbar('Downloading', s3_object_size) transfer_manager = S3Transfer(s3_client) transfer_manager.download_file(self.s3_bucket, s3_object, self._local_cipher_file(), callback=self._download_progress_callback) cli_library.finish_progressbar('Downloading') cli_library.echo('') def _decrypt(self, kms_key, aws_profile, encryption_context): cli_library.echo('Decrypting {}...'.format(self.backup_file)) decrypted_file = DecryptedFile(self._local_cipher_file(), self._local_compress_file(), kms_key, aws_profile, encryption_context) try: decrypted_file.decrypt() except EncryptionContextMismatch: cli_library.echo("The encrypted file's context did not match the specified context. The file may have " "been tampered with!") os.remove(self._local_compress_file()) raise finally: os.remove(self._local_cipher_file()) def _uncompress(self): cli_library.echo('Uncompressing {}...'.format(self.backup_file)) uncompress_file = UncompressFile(self._local_compress_file(), self.restore_path) uncompress_file.uncompress() os.remove(self._local_compress_file()) @staticmethod def _download_progress_callback(bytes_transfered): cli_library.update_progressbar('Downloading', bytes_transfered) def _local_cipher_file(self): return os.path.join(self.intermediate_path, self.backup_file + '.cipher') def _local_compress_file(self): return os.path.join(self.intermediate_path, self.backup_file + '.tgz')
cloud_backup/backup/restorefile.py
from boto3 import Session from boto3.s3.transfer import S3Transfer from .compression.uncompressfile import UncompressFile from .encryption.decryptedfile import DecryptedFile, EncryptionContextMismatch import os from ..cli import cli_library class RestoreFile: def __init__(self, s3_bucket, timestamp, backup_file, restore_path, intermediate_path='/tmp/'): self.s3_bucket = s3_bucket self.timestamp = timestamp self.backup_file = backup_file self.restore_path = restore_path self.intermediate_path = intermediate_path if intermediate_path is not None else '/tmp/' def restore(self, kms_key, aws_profile, encryption_context=None): self._download(aws_profile) self._decrypt(kms_key, aws_profile, encryption_context) self._uncompress() def restore_path(self): return self.saved_encrypted_path def cleanup(self): os.remove(self.saved_encrypted_path) def _download(self, aws_profile): cli_library.echo('Downloading {}...'.format(self.backup_file)) s3_object = self.timestamp + '/' + self.backup_file + '.cipher' s3_client = Session(profile_name=aws_profile).client('s3') s3_object_size = s3_client.head_object(Bucket=self.s3_bucket, Key=s3_object)['ContentLength'] cli_library.create_progressbar('Downloading', s3_object_size) transfer_manager = S3Transfer(s3_client) transfer_manager.download_file(self.s3_bucket, s3_object, self._local_cipher_file(), callback=self._download_progress_callback) cli_library.finish_progressbar('Downloading') cli_library.echo('') def _decrypt(self, kms_key, aws_profile, encryption_context): cli_library.echo('Decrypting {}...'.format(self.backup_file)) decrypted_file = DecryptedFile(self._local_cipher_file(), self._local_compress_file(), kms_key, aws_profile, encryption_context) try: decrypted_file.decrypt() except EncryptionContextMismatch: cli_library.echo("The encrypted file's context did not match the specified context. The file may have " "been tampered with!") os.remove(self._local_compress_file()) raise finally: os.remove(self._local_cipher_file()) def _uncompress(self): cli_library.echo('Uncompressing {}...'.format(self.backup_file)) uncompress_file = UncompressFile(self._local_compress_file(), self.restore_path) uncompress_file.uncompress() os.remove(self._local_compress_file()) @staticmethod def _download_progress_callback(bytes_transfered): cli_library.update_progressbar('Downloading', bytes_transfered) def _local_cipher_file(self): return os.path.join(self.intermediate_path, self.backup_file + '.cipher') def _local_compress_file(self): return os.path.join(self.intermediate_path, self.backup_file + '.tgz')
0.407569
0.061003